/** * Parse a value using given types. * * @param mixed $value * @param array $types * @param \ReflectionProperty $property * @param object $object * * @return array|bool|float|int|string */ private function parseValue($value, $types, \ReflectionProperty $property, $object) { foreach ($types as $type) { foreach ($this->context->getParsers() as $parser) { if ($parser instanceof ValueParserInterface) { if (is_array($value) && strpos($type, '[]') !== false) { //support for nesting children //https://github.com/rafrsr/lib-array2object/issues/1 if (count($value) === 1 && is_array(current($value))) { if (array_key_exists(0, current($value))) { $value = current($value); } } $tmpArray = []; foreach ($value as $key => $arrayValue) { $parsedValue = $parser->toObjectValue($arrayValue, str_replace('[]', null, $type), $property, $object); //the annotation [] is used alone to ignore array keys if (in_array('[]', $types, true)) { $tmpArray[] = $parsedValue; } else { $tmpArray[$key] = $parsedValue; } } $value = $tmpArray; } else { $value = $parser->toObjectValue($value, str_replace('[]', null, $type), $property, $object); } } else { throw new \InvalidArgumentException(sprintf('%s is not a valid parser.', get_class($parser))); } } } return $value; }
public function testPrependParsers() { $context = new Array2ObjectContext(); $parsers = [new StringParser(), new IntegerParser()]; $context->setParsers($parsers); $context->prependParser(new IntegerParser()); static::assertEquals(['integer' => new IntegerParser(), 'string' => new StringParser()], $context->getParsers()); }