PHP code example of cuyz / valinor

1. Go to this page and download the library: Download cuyz/valinor 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/ */

    

cuyz / valinor example snippets


final class Country
{
    public function __construct(
        /** @var non-empty-string */
        public readonly string $name,
        
        /** @var list<City> */
        public readonly array $cities,
    ) {}
}

final class City
{
    public function __construct(
        /** @var non-empty-string */
        public readonly string $name,
        
        public readonly DateTimeZone $timeZone,
    ) {}
}

$json = <<<JSON
    {
        "name": "France",
        "cities": [
            {"name": "Paris", "timeZone": "Europe/Paris"},
            {"name": "Lyon", "timeZone": "Europe/Paris"}
        ]
    }
JSON;

try {
    $country = (new \CuyZ\Valinor\MapperBuilder())
        ->mapper()
        ->map(Country::class, \CuyZ\Valinor\Mapper\Source\Source::json($json));

    echo $country->name; // France 
    echo $country->cities[0]->name; // Paris
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
    // Handle the error…
}