Skip to main content

Transformation

Transformation is the process of converting a property from one type to another. In fact, you can transform data in whichever way suits you best—even substitute values. From a technical standpoint, the only thing that matters is type compliance.

Transformers in Serialization

class Album extends Data {
public function __construct(
public string $name,
#[SerializeBy(StudioSerializer::class)]
public Studio $studio
) {}
}

use Looqey\Speca\Contracts\Transformer;
use Looqey\Speca\Core\Property;

class StudioSerializer implements Transformer {
public function transform(mixed $value, Property $property): mixed {
assert($value instanceof Studio);
return $value->id;
}
}

$album = new Album("Dopethrone", new Studio(id: "f7246ef2-448f-4280-9b29-0a21a3306db1", name: "Some studio"));

$result = $album->toArray();
/* $result: [
* "name" => "Dopethrone",
* "studio" => "f7246ef2-448f-4280-9b29-0a21a3306db1"
] */

This example demonstrates how to use the SerializeBy attribute to apply a serializer that converts a Studio object into its ID during serialization.

Transformers in Parsing

class Studio extends Data {
public function __construct(
public string $id,
public string $name,
public string $city
) {}
}

class IdToStudioParser implements Transformer {
public function transform(mixed $value, Property $property): mixed {
$model = StudioModel::find($value); // find the studio by ID
return new Studio(
$model->id,
$model->name,
$model->city
);
}
}

class Album extends Data {
public function __construct(
public string $name,
public int $tracksCount,
public AlbumType $type,
#[ParseBy(IdToStudioParser::class)]
#[ParseFrom('studio_id')]
public Studio $studio
) {}
}

$album = Album::from(['name' => 'Dopethrone', 'tracksCount' => '8', 'type' => 'lp', 'studio_id' => 'f7246ef2-448f-4280-9b29-0a21a3306db1']);

In this example, the parser IdToStudioParser is used to parse the studio_id field and convert it into a Studio object. The ParseBy attribute specifies the parser, while ParseFrom indicates a possible data source.