/** * {@inheritdoc} */ public function apply(Request $request, ParamConverter $configuration) : bool { $class = $configuration->getClass(); $constant = sprintf('%s::EMPTY_PROPERTIES', $class); $propertiesToBeSkipped = []; $instance = new $class(); $declaredProperties = array_filter((new \ReflectionClass($class))->getProperties(), function (ReflectionProperty $property) use($class) { return $property->getDeclaringClass()->name === $class; }); // fetch result properties that are optional and to be skipped as those must not be processed if (defined($constant)) { $propertiesToBeSkipped = constant($constant); } /** @var ReflectionProperty $property */ foreach ($declaredProperties as $property) { $propertyName = $property->getName(); if (in_array($propertyName, $propertiesToBeSkipped, true)) { continue; } // non-writable properties cause issues with the DTO creation if (!$this->propertyAccess->isWritable($instance, $propertyName)) { throw new \RuntimeException($this->getInvalidPropertyExceptionMessage($class, $propertyName)); } $this->propertyAccess->setValue($instance, $propertyName, $this->findAttributeInRequest($request, $property, $this->propertyAccess->getValue($instance, $propertyName))); } $request->attributes->set($configuration->getName(), $instance); return true; }
/** * {@inheritdoc} */ public function mapFormsToData($forms, &$data) { if (null === $data) { return; } if (!is_array($data) && !is_object($data)) { throw new UnexpectedTypeException($data, 'object, array or empty'); } foreach ($forms as $form) { $propertyPath = $form->getPropertyPath(); $config = $form->getConfig(); // Write-back is disabled if the form is not synchronized (transformation failed), // if the form was not submitted and if the form is disabled (modification not allowed) if (null !== $propertyPath && $config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) { // If the field is of type DateTime and the data is the same skip the update to // keep the original object hash if ($form->getData() instanceof \DateTime && $form->getData() == $this->propertyAccessor->getValue($data, $propertyPath)) { continue; } // If the data is identical to the value in $data, we are // dealing with a reference if (!is_object($data) || !$config->getByReference() || $form->getData() !== $this->propertyAccessor->getValue($data, $propertyPath)) { $this->propertyAccessor->setValue($data, $propertyPath, $form->getData()); } } } }
/** * @param object $entity Entity * * @throws \Darvin\Utils\DefaultValue\DefaultValueException */ protected function setDefaultValues($entity) { $entityClass = ClassUtils::getClass($entity); $meta = $this->extendedMetadataFactory->getExtendedMetadata($entityClass); if (!isset($meta['defaultValues']) || empty($meta['defaultValues'])) { return; } $defaultValuesMap = $meta['defaultValues']; $this->filterDefaultValuesMap($defaultValuesMap, $entity, $entityClass); if (empty($defaultValuesMap)) { return; } $sourcePropertyValues = $this->getSourcePropertyValues(array_unique(array_values($defaultValuesMap)), $entity, $entityClass); $recomputeChangeSet = false; foreach ($defaultValuesMap as $targetProperty => $sourcePropertyPath) { if (null === $sourcePropertyValues[$sourcePropertyPath]) { continue; } if (!$this->propertyAccessor->isWritable($entity, $targetProperty)) { throw new DefaultValueException(sprintf('Property "%s::$%s" is not writable.', $entityClass, $targetProperty)); } $this->propertyAccessor->setValue($entity, $targetProperty, $sourcePropertyValues[$sourcePropertyPath]); $recomputeChangeSet = true; } if ($recomputeChangeSet) { $this->recomputeChangeSet($entity); } }
/** * {@inheritdoc} */ public function mapFormsToData(array $forms, &$data) { if (null === $data) { return; } if (!is_array($data) && !is_object($data)) { throw new UnexpectedTypeException($data, 'object, array or empty'); } $iterator = new VirtualFormAwareIterator($forms); $iterator = new \RecursiveIteratorIterator($iterator); foreach ($iterator as $form) { /* @var \Symfony\Component\Form\FormInterface $form */ $propertyPath = $form->getPropertyPath(); $config = $form->getConfig(); // Write-back is disabled if the form is not synchronized (transformation failed) // and if the form is disabled (modification not allowed) if (null !== $propertyPath && $config->getMapped() && $form->isSynchronized() && !$form->isDisabled()) { // If the data is identical to the value in $data, we are // dealing with a reference if (!is_object($data) || !$config->getByReference() || $form->getData() !== $this->propertyAccessor->getValue($data, $propertyPath)) { $this->propertyAccessor->setValue($data, $propertyPath, $form->getData()); } } } }
function it_creates_theme_from_valid_array($themeClassName, PropertyAccessorInterface $propertyAccessor) { $data = ['name' => 'Foo bar', 'logical_name' => 'foo/bar']; $propertyAccessor->setValue(Argument::any(), 'name', 'Foo bar')->shouldBeCalled(); $propertyAccessor->setValue(Argument::any(), 'logical_name', 'foo/bar')->shouldBeCalled(); $propertyAccessor->setValue(Argument::any(), 'parentsNames', [])->shouldBeCalled(); $this->createFromArray($data)->shouldHaveType($themeClassName); }
/** * @inheritdoc */ public function setValue(&$objectOrArray, $propertyPath, $value) { if ($objectOrArray instanceof \stdClass) { $objectOrArray->{$propertyPath} = $value; return; } $this->decoratedPropertyAccessor->setValue($objectOrArray, $propertyPath, $value); }
/** * {@inheritdoc} */ public function setState(&$object, $value) { try { $this->propertyAccessor->setValue($object, $this->propertyPath, $value); } catch (SymfonyNoSuchPropertyException $e) { throw new NoSuchPropertyException(sprintf('Property path "%s" on object "%s" does not exist.', $this->propertyPath, get_class($object)), $e->getCode(), $e); } }
/** * {@inheritdoc} */ protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = array()) { try { $this->propertyAccessor->setValue($object, $attribute, $value); } catch (NoSuchPropertyException $exception) { // Properties not found are ignored } }
/** * @param mixed $value */ public function set($value) { if ($this->path) { $this->accessor->setValue($this->object, $this->path, $value); } else { $this->object = $value; } }
/** * {@inheritdoc} */ public function create($entityClass, array $defaultValues = array(), array $options = array()) { $object = new $entityClass(); foreach ($defaultValues as $propertyPath => $value) { $this->propertyAccessor->setValue($object, $propertyPath, $value); } return $object; }
/** * {@inheritdoc} */ public function create(array $options = []) { $class = $this->resource->getModel(); $object = new $class(); foreach ($options as $propertyPath => $value) { $this->propertyAccessor->setValue($object, $propertyPath, $value); } return $object; }
/** * @inheritdoc */ public function create(array $parameters = array()) { $class = $this->options['class']; $object = new $class(); foreach ($parameters as $key => $value) { $this->propertyAccessor->setValue($object, $key, $value); } return $object; }
/** * {@inheritdoc} */ public function setValue($object, ColumnInfoInterface $columnInfo, $data, array $options = array()) { if (!isset($options['propertyPath'])) { throw new \InvalidArgumentException('propertyPath option is required'); } foreach ($data as $locale => $value) { $object->setLocale($locale); $this->propertyAccessor->setValue($object, 'translation.' . $options['propertyPath'], $value); } }
/** * {@inheritdoc} */ public function createFromArray(array $themeData) { /** @var ThemeInterface $theme */ $theme = new $this->themeClassName(); $themeData = $this->optionsResolver->resolve($themeData); foreach ($themeData as $attributeKey => $attributeValue) { $this->propertyAccessor->setValue($theme, $this->normalizeAttributeKey($attributeKey), $attributeValue); } return $theme; }
/** * {@inheritdoc} */ public function setValue($object, ColumnInfoInterface $columnInfo, $data, array $options = array()) { if ($columnInfo->getLocale()) { $locale = $columnInfo->getLocale(); } else { $suffixes = $columnInfo->getSuffixes(); $locale = array_shift($suffixes); } $object->setLocale($locale); $this->propertyAccessor->setValue($object, 'translation.' . $columnInfo->getPropertyPath(), $data); }
/** * {@inheritdoc} */ public function apply(Request $request, ParamConverter $configuration) { $instance = $this->getDTOInstance($configuration->getClass()); foreach ($this->getDTOParametersByClass($configuration->getClass()) as $property) { $propertyName = $property->getName(); if (!$this->propertyAccess->isWritable($instance, $propertyName)) { throw new \RuntimeException($this->getInvalidPropertyExceptionMessage($configuration->getClass(), $propertyName)); } $this->propertyAccess->setValue($instance, $propertyName, $this->findAttributeInRequest($request, $property)); } $request->attributes->set($configuration->getName(), $instance); return true; }
/** * @param object $object Object to clone * * @return object * @throws \Darvin\Utils\Cloner\ClonerException */ private function cloneObject($object) { $objectHash = spl_object_hash($object); if (isset($this->clonedObjects[$objectHash])) { return $this->clonedObjects[$objectHash]; } $class = ClassUtils::getClass($object); if (false === strpos($class, '\\')) { $clone = clone $object; $this->clonedObjects[$objectHash] = $clone; return $clone; } $meta = $this->extendedMetadataFactory->getExtendedMetadata($class); if (!isset($meta['clonable'])) { $message = sprintf('Class "%s" must be annotated with "%s" annotation in order to create clone of it\'s instance.', $class, Clonable::ANNOTATION); throw new ClonerException($message); } $clone = new $class(); $this->clonedObjects[$objectHash] = $clone; foreach ($meta['clonable']['properties'] as $property) { if (!$this->propertyAccessor->isReadable($object, $property)) { throw new ClonerException(sprintf('Property "%s::$%s" is not readable.', $class, $property)); } if (!$this->propertyAccessor->isWritable($clone, $property)) { throw new ClonerException(sprintf('Property "%s::$%s" is not writable.', $class, $property)); } $value = $this->propertyAccessor->getValue($object, $property); $valueCopy = $this->copyValue($value); $this->propertyAccessor->setValue($clone, $property, $valueCopy); } $this->eventDispatcher->dispatch(Events::POST_CLONE, new CloneEvent($object, $clone)); return $clone; }
/** * {@inheritdoc} */ public function mapFormsToData($forms, &$data) { if (null === $data) { return; } if (!is_array($data) && !is_object($data)) { throw new UnexpectedTypeException($data, 'object, array or empty'); } foreach ($forms as $form) { $propertyPath = $form->getPropertyPath(); $config = $form->getConfig(); // Write-back is disabled if the form is not synchronized (transformation failed), // if the form was not submitted and if the form is disabled (modification not allowed) if (null !== $propertyPath && $config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) { // If $data is out ContentCreateStruct, we need to map it to the corresponding field // in the struct if ($data instanceof DataWrapper) { /** @var $data \Netgen\Bundle\EzFormsBundle\Form\DataWrapper */ $this->mapFromForm($form, $data, $propertyPath); } else { // If the field is of type DateTime and the data is the same skip the update to // keep the original object hash if ($form->getData() instanceof \DateTime && $form->getData() == $this->propertyAccessor->getValue($data, $propertyPath)) { continue; } if (!is_object($data) || !$config->getByReference() || $form->getData() !== $this->propertyAccessor->getValue($data, $propertyPath)) { $this->propertyAccessor->setValue($data, $propertyPath, $form->getData()); } } } } }
/** * @param object $entity Entity * @param string $propertyPath Property path * @param mixed $value Value * * @throws \Darvin\Utils\CustomObject\CustomObjectException */ private function setPropertyValue($entity, $propertyPath, $value) { if (!$this->propertyAccessor->isWritable($entity, $propertyPath)) { throw new CustomObjectException(sprintf('Property "%s::$%s" is not writable.', ClassUtils::getClass($entity), $propertyPath)); } $this->propertyAccessor->setValue($entity, $propertyPath, $value); }
/** * @param FormEvent $event */ private function setFormDataLocale(FormEvent $event) { if (!($data = $event->getData())) { return; } $this->propertyAccessor->setValue($data, $this->getFormDataTranslatableMetadata($event)->localeProperty, $this->getCurrentLocale()); }
/** * {@inheritdoc} */ public function denormalize($data, $class, $format = null, array $context = array()) { if (!isset($context['cache_key'])) { $context['cache_key'] = $this->getCacheKey($context); } $allowedAttributes = $this->getAllowedAttributes($class, $context, true); $normalizedData = $this->prepareForDenormalization($data); $reflectionClass = new \ReflectionClass($class); $object = $this->instantiateObject($normalizedData, $class, $context, $reflectionClass, $allowedAttributes); foreach ($normalizedData as $attribute => $value) { if ($this->nameConverter) { $attribute = $this->nameConverter->denormalize($attribute); } $allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes); $ignored = in_array($attribute, $this->ignoredAttributes); if ($allowed && !$ignored) { try { $this->propertyAccessor->setValue($object, $attribute, $value); } catch (NoSuchPropertyException $exception) { // Properties not found are ignored } } } return $object; }
/** * @param mixed $object * @param mixed $key * @return mixed */ public function settleKey(&$object, $key) { if ($this->keyPropertyPath) { $this->propertyAccessor->setValue($object, $this->keyPropertyPath, $key); } return $object; }
/** * @param $object * @param string $lockType * @return bool * @throws \Exception */ public function switchLock($object, $lockType = ObjectLockParams::FULL_LOCK) { $objectClassName = $this->getObjectClassName($object); $objectDetail = $this->getObjectDetail($objectClassName); if (!$objectDetail) { $objectDetail = $this->setupObjectDetail($objectClassName); } if ($this->accessor->getValue($objectDetail, $lockType) === true) { $this->accessor->setValue($objectDetail, $lockType, false); } else { $this->accessor->setValue($objectDetail, $lockType, true); } $this->em->persist($objectDetail); $this->em->flush(); return true; }
/** * {@inheritdoc} * * @throws NoSuchPropertyException * @throws InaccessiblePropertyException * @throws InvalidArgumentException When the typehint does not match for example * @throws HydrationException */ public function hydrate(ObjectInterface $object, Property $property, GenerationContext $context) : ObjectInterface { $instance = $object->getInstance(); try { $this->propertyAccessor->setValue($instance, $property->getName(), $property->getValue()); } catch (SymfonyNoSuchPropertyException $exception) { throw HydrationExceptionFactory::createForCouldNotHydrateObjectWithProperty($object, $property, 0, $exception); } catch (SymfonyAccessException $exception) { throw HydrationExceptionFactory::createForInaccessibleProperty($object, $property, 0, $exception); } catch (SymfonyInvalidArgumentException $exception) { throw HydrationExceptionFactory::createForInvalidProperty($object, $property, 0, $exception); } catch (SymfonyPropertyAccessException $exception) { throw HydrationExceptionFactory::create($object, $property, 0, $exception); } return new SimpleObject($object->getId(), $instance); }
/** * Sets a value of the object using the PropertyAccess component. * * @param object $object * @param string $attributeName * @param mixed $value */ private function setValue($object, $attributeName, $value) { try { $this->propertyAccessor->setValue($object, $attributeName, $value); } catch (NoSuchPropertyException $exception) { // Properties not found are ignored } }
/** * * @param Dictionary $dictionary */ protected function addDatabaseTranslation(Dictionary $dictionary) { foreach ($this->locales as $locale) { $translation = $dictionary->translate($locale->getCode())->getValue(); $propertyPath = '[' . $locale->getCode() . ']' . Helper::convertDotNotation($dictionary->getIdentifier()); $this->propertyAccessor->setValue($this->databaseTranslations, $propertyPath, $translation); } }
/** * Builds the entity * * @param ClassMetadata $metadata * @param array $data * * @return object * @throws \Exception */ private function buildEntity(ClassMetadata $metadata, $data) { $class = $metadata->getName(); $entity = new $class(); foreach ($data as $propertyPath => $value) { // Field if ($metadata->hasField($propertyPath)) { $builtValue = $this->buildFieldValue($metadata, $propertyPath, $value); // Association } elseif ($metadata->hasAssociation($propertyPath)) { $builtValue = $this->buildAssociationValue($metadata, $propertyPath, $value); } else { throw new \Exception("Unexpected property path '{$propertyPath}'."); } $this->accessor->setValue($entity, $propertyPath, $builtValue); } return $entity; }
/** * @param MetadataInterface $metadata * @param array $defaultValues * * @return MetadataInterface */ private function setDefaultValuesOnMetadata(MetadataInterface $metadata, array $defaultValues) { foreach ($defaultValues as $propertyPath => $value) { if (null !== $this->propertyAccessor->getValue($metadata, $propertyPath)) { continue; } $this->propertyAccessor->setValue($metadata, $propertyPath, $value); } }
/** * {@inheritdoc} * * @throws MappingException */ public function process($item, callable $next) { try { foreach ($this->mappings as $from => $to) { $value = $this->accessor->getValue($item, $from); $this->accessor->setValue($item, $to, $value); $from = str_replace(['[', ']'], '', $from); // Check if $item is an array, because properties can't be unset. // So we don't call unset for objects to prevent side affects. if (is_array($item) && isset($item[$from])) { unset($item[$from]); } } } catch (NoSuchPropertyException $exception) { throw new MappingException('Unable to map item', null, $exception); } catch (UnexpectedTypeException $exception) { throw new MappingException('Unable to map item', null, $exception); } return $next($item); }
/** * Replaces the TemporaryUploadedFile or TempImage with the actual instance. Automatically sets the * reference to the owning entity. * * @param string $targetEntity The entity to create * @param TempUploadedFile|TempImage $source The source entity * @param object $target The entity where to set the property * * @return object The newly created object instance */ protected function setReplacementFile($targetEntity, $source, $target) { /** * @var UploadedFile */ $newFile = new $targetEntity(); $this->replaceFile($newFile, $source); $setterName = $this->getReferenceSetter($newFile, $target); if ($setterName !== false) { $this->propertyAccessor->setValue($newFile, $setterName, $target); } return $newFile; }