PHP code example of magicsunday / jsonmapper

1. Go to this page and download the library: Download magicsunday/jsonmapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

magicsunday / jsonmapper example snippets


@var SomeCollection<DateTime>
@var SomeCollection<string>
@var Collection\SomeCollection<App\Entity\SomeEntity>

/**
 * @var array<string>
 *
 * @MagicSunday\JsonMapper\Annotation\ReplaceNullWithDefaultValue
 */
public array $array = [];

/**
 * @MagicSunday\JsonMapper\Annotation\ReplaceProperty("type", replaces="crypticTypeNameProperty")
 */
class FooClass
{
    /**
     * @var string
     */
    public $type;
}

use \Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use \Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use \Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use \Symfony\Component\PropertyAccess\PropertyAccessor;

$listExtractors = [ new ReflectionExtractor() ];
$typeExtractors = [ new PhpDocExtractor() ];
$propertyInfoExtractor = new PropertyInfoExtractor($listExtractors, $typeExtractors);

$propertyAccessor = PropertyAccess::createPropertyAccessor();

$nameConverter = new \MagicSunday\JsonMapper\Converter\CamelCasePropertyNameConverter();

$classMap = [
    SdkFoo::class => Foo::class,
];

$mapper = new \MagicSunday\JsonMapper(
    $propertyInfoExtractor,
    $propertyAccessor,
    $nameConverter,
    $classMap
);

$mapper->addType(
    Bar::class,
    /** @var mixed $value JSON data */
    static function ($value): ?Bar {
        return $value ? new Bar($value['name']) : null;
    }
);

$mapper->addType(
    \DateTime::class,
    /** @var mixed $value JSON data */
    static function ($value): ?\DateTime {
        return $value ? new \DateTime($value) : null;
    }
);

$json = json_decode('JSON STRING', true, 512, JSON_THROW_ON_ERROR);

$mappedResult = $mapper->map($json, Foo::class, FooCollection::class);

/**
 * Returns an instance of the JsonMapper for testing.
 *
 * @param string[]|Closure[] $classMap A class map to override the class names
 *
 * @return \MagicSunday\JsonMapper
 */
protected function getJsonMapper(array $classMap = []): \MagicSunday\JsonMapper
{
    $listExtractors = [ new ReflectionExtractor() ];
    $typeExtractors = [ new PhpDocExtractor() ];
    $extractor      = new PropertyInfoExtractor($listExtractors, $typeExtractors);

    return new \MagicSunday\JsonMapper(
        $extractor,
        PropertyAccess::createPropertyAccessor(),
        new CamelCasePropertyNameConverter(),
        $classMap
    );
}
bash
composer update
composer ci:cgl
composer ci:test
composer ci:test:php:phplint
composer ci:test:php:phpstan
composer ci:test:php:rector
composer ci:test:php:unit