public function testGetSetPropertyWriter() { $context = new Array2ObjectContext(); $writer = new AccessorWriter(); $context->setWriter($writer); static::assertEquals($writer, $context->getWriter()); }
public function testParse() { $context = new Array2ObjectContext(); $context->setWriter(new AccessorWriter()); $context->setMatcher(new CamelizeMatcher()); $context->setParsers([new StringParser()]); $parser = new ObjectParser($context); $object = new Team(); $property = new \ReflectionProperty(get_class($object), 'name'); /** @var Team $team */ $team = $parser->toObjectValue(['name' => 'New Name'], 'Team', $property, $object); static::assertInstanceOf(Team::class, $team); static::assertEquals('New Name', $team->getName()); }
/** * 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; }