brendt/php-make-object

Simple wrapper for symfony/serializer for the 90% use-case

0.5.0 2022-12-01 10:14 UTC

README

Latest Version on Packagist Tests Total Downloads

Write this:

$post = make(Post::class)->from($postData);

instead of this:

$reflectionExtractor = new ReflectionExtractor();

$phpDocExtractor = new PhpDocExtractor();

$propertyTypeExtractor = new PropertyInfoExtractor(
    listExtractors: [$reflectionExtractor],
    typeExtractors: [$phpDocExtractor, $reflectionExtractor],
    descriptionExtractors: [$phpDocExtractor],
    accessExtractors: [$reflectionExtractor],
    initializableExtractors: [$reflectionExtractor]
);

$normalizer = new ObjectNormalizer(
    propertyTypeExtractor: $propertyTypeExtractor
);

$arrayNormalizer = new ArrayDenormalizer();

$serializer = new SymfonySerializer(
    normalizers: [
        $arrayNormalizer,
        $normalizer,
    ],
    encoders: [
        new XmlEncoder(),
        new JsonEncoder(),
    ],
);

$post = $serializer->denormalize($postData, Post::class)

Installation

You can install the package via composer:

composer require brendt/php-make-object

Usage

This package abstracts away all configuration needed for complex deserialization with symfony/serializer. All you need to do is say which class you want to make, provide it some input (arrays, JSON, XML, files or objects), and this package will take care of the rest.

Added bonus: proper static analysis, so you'll know what kind of object was created.

$post = make(Post::class)->from($postData);

Input types

Arrays

$post = make(Post::class)->from([
    'title' => 'test',
]);

JSON

$post = make(Post::class)->from(<<<JSON
    {
        "title": "test"
    }
JSON);

XML

$post = make(Post::class)->from(<<<XML
    <post>
        <title>test</title>
    </post>
XML);

Files

$post = make(Post::class)->from(__DIR__ . '/post.json');

The Make interface

The Make interface can be added on any class, allowing that class to provide data that can be used to create an object.

$post = make(Post::class)->from(new PostRequest());
final class PostRequest implements Makes
{
    public function data(): array
    {
        return [
            'title' => 'test',
        ];
    }
}

Collections

$posts = make(Post::class)->fromCollection([
    ['title' => 'a'],
    ['title' => 'b'],
    ['title' => 'c'],
]);

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.