Skip to content

Parsers

Rafael Santos edited this page Jun 22, 2016 · 1 revision

Parsers convert the value from array to object property and viceversa.

The library has some default parses See Available Types, but you can implement your own parser.

Using callback as parser

Can use a parser called "CallableParser" to create a parser using a callable.

//this parser remove the '$' symbol in the value before apply to salary property
$salaryParser =  new CallableParser(
                function ($value, $type, \ReflectionProperty $property, $object) {
                    if ($property->getName() === 'salary') {
                        $value = str_replace('$', null, $value);
                    }
                    return $value;
                }
            );
$array2Object = Array2ObjectBuilder::create()->addParser($salaryParser)->build();

Standalone parser class

Can implements your own parser class implementing Rafrsr\LibArray2Object\Parser\ValueParserInterface

class SalaryParser implements ValueParserInterface
{
    /**
     * @inheritDoc
     */
    public function getName()
    {
        return 'salary_parser';
    }

    /**
     * @inheritDoc
     */
    public function toObjectValue($value, $type, \ReflectionProperty $property, $object)
    {
        // TODO: Implement toObjectValue() method.
    }

    /**
     * @inheritDoc
     */
    public function toArrayValue($value, $type, \ReflectionProperty $property, $object)
    {
        // TODO: Implement toArrayValue() method.
    }
}
Clone this wiki locally