unicon/yaml

Validates YAML file using given class and, if matches, creates an object. Understands PhpDoc, converts values if necessary. Works recursively, so the YAML file may have complicated structure, and the given class may have properties of other classes.

1.0.0 2024-01-10 08:55 UTC

This package is auto-updated.

Last update: 2024-05-11 18:47:18 UTC


README

Validates YAML file using given class and, if matches, creates an object. Understands PhpDoc, converts values if necessary. Works recursively, so the YAML file may have complicated structure, and the given class may have properties of other classes.

Installation

composer require unicon/yarn

Usage

$reader = new Yaml(MyClass::class);
$object = $reader->read('my_yaml.yml');

Example

class Simple
{
    public int $integerParameter = 1;
    /** @var positive-int */
    public int $positiveIntegerParameter;
    public ?bool $booleanOrNullParameter;
    public string $stringParameter = 'default';
}

Success example

integer_parameter: '777'
positive_integer_parameter: 666
boolean_or_null_parameter: null
string_parameter: 888

Failures

YamlException is thrown if the YAML file doesn't match the class:

Yaml parameter positive_integer_parameter must be greater or equal to 1, "-1" given

integer_parameter: '777'
positive_integer_parameter: '-1'
boolean_or_null_parameter: null
string_parameter: 888

Can't convert integer_parameter 777.777 to int

integer_parameter: 777.777
positive_integer_parameter: 666
boolean_or_null_parameter: null
string_parameter: 888

Can't convert integer_parameter "xxx" to int

integer_parameter: 'xxx'
positive_integer_parameter: 666
boolean_or_null_parameter: null
string_parameter: 888

Yaml parameter positive_integer_parameter is missed

(integer_parameter and boolean_or_null_parameter are missed too, but one has default values, another is nullable)

string_parameter: 'aaa'

Yaml parameter extra_parameter with value true is unexpected

(this exception is never thrown for stdClass or \AllowDynamicProperties classes)

extra_parameter: true
integer_parameter: '777'
positive_integer_parameter: 666
boolean_or_null_parameter: null
string_parameter: 888

You can find more examples in the test directory including dates, complicated structures and trees (classes with array<self> properties).