PHP code example of eliashaeussler / valinor-xml

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

    

eliashaeussler / valinor-xml example snippets


final readonly class Address
{
    public function __construct(
        public string $street,
        public string $postcode,
        public string $city,
        public string $country,
    ) {}
}

final readonly class Contact
{
    public function __construct(
        public string $phone,
    ) {}
}

final readonly class Person
{
    public function __construct(
        public string $name,
        public Address $address,
        public Contact $contact,
    ) {}
}

use CuyZ\Valinor;
use EliasHaeussler\ValinorXml;

$mapper = (new Valinor\MapperBuilder())->mapper();
$source = ValinorXml\Mapper\Source\XmlSource::fromXmlString($xml);
$person = $mapper->map(Person::class, $source); // instanceof Person

use CuyZ\Valinor;
use EliasHaeussler\ValinorXml;

$mapper = (new Valinor\MapperBuilder())->mapper();
$source = ValinorXml\Mapper\Source\XmlSource::fromXmlFile($file);
$person = $mapper->map(Person::class, $source); // instanceof Person

final readonly class Community
{
    /**
      * @param list<Person> $member
      */
    public function __construct(
        public array $member,
    ) {}
}

use CuyZ\Valinor;
use EliasHaeussler\ValinorXml;

$mapper = (new Valinor\MapperBuilder())->mapper();
$source = ValinorXml\Mapper\Source\XmlSource::fromXmlFile($file);
$person = $mapper->map(Community::class, $source); // throws exception

use CuyZ\Valinor;
use EliasHaeussler\ValinorXml;

$mapper = (new Valinor\MapperBuilder())->mapper();
$source = ValinorXml\Mapper\Source\XmlSource::fromXmlFile($file)
    ->asCollection('member')
;
$person = $mapper->map(Community::class, $source); // instanceof Community

use CuyZ\Valinor;
use EliasHaeussler\ValinorXml;

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"

CuyZ\Valinor\Mapper\TypeTreeMapperError: Could not map type `Community` with value array{member: array{…}}.