Parsing, Property Parsers
What is Parsing?
Parsing is the process of transforming input data into a target-type object, in this case, a Data
class object. During parsing, type conversions may occur, and various rules may be applied to correctly populate the object's properties.
Primitive Conversions
Primitive conversions are automatically performed for data types such as strings, numbers, booleans, arrays, and objects.
use Looqey\Speca\Data;
enum AlbumType: string {
case EP = 'ep';
case LIVE = 'live';
case LP = 'lp';
case COMPILATION = 'compilation';
case DEMO = 'demo';
}
class Album extends Data {
public function __construct(
public string $name,
public int $tracksCount,
public AlbumType $type
) {}
}
$album = Album::from(['name' => 'Dopethrone', 'tracksCount' => '8', 'type' => 'lp']);
In this example, the tracksCount
field is automatically cast to the int
type, and the type
field will be converted to one of the AlbumType
enum values.
Custom Conversions
For more complex data types, you can implement custom transformation rules using parsers.
Creating and Using a Property Parser
To create your own parser, implement the Transformer