protected function getConstraintViolation(ConstraintViolation $constraintViolation, array &$messages) { $path = new PropertyPath($constraintViolation->getPropertyPath()); $elements = $path->getElements(); $elements[] = $constraintViolation->getConstraint()->validatedBy(); $this->propertyAccessor->setValue($messages, $this->buildPath($elements), $constraintViolation->getMessage()); }
/** * {@inheritdoc} */ public function create(&$node, $singlePath, $value) { if (!$this->isWritable($node, $singlePath)) { throw new InvalidPathException(sprintf('Path %s could not be created in object of type %s', $singlePath, gettype($node))); } $this->propertyAccess->setValue($node, $singlePath, $value); }
/** * {@inheritdoc} */ public function convert($value) { $ref = new \ReflectionClass($this->class); $data = $ref->newInstanceWithoutConstructor(); $this->propertyAccessor->setValue($data, $this->label, $value); return (object) $data; }
/** * Transforms date string to DateTime object * * @param object $modelData * @param PropertyPathInterface $propertyPath * @param mixed $value */ public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $value) { if (false === ($date = $this->createDateFromString($value))) { $date = null; } $this->propertyAccessor->setValue($modelData, $propertyPath, $date); }
/** * Applies the given mapping on a given object or array. * * @param object|array $raw The input object or array * @param array $mapping The mapping * @param object|array $transformed The output object or array. * @return array */ public function transform($raw, array $mapping, $transformed = []) { foreach ($mapping as $destination => $source) { $value = $this->propertyAccessor->isReadable($raw, $source) ? $this->propertyAccessor->getValue($raw, $source) : null; $this->propertyAccessor->setValue($transformed, $destination, $value); } return $transformed; }
/** * {@inheritdoc} */ protected function addWhereCondition($entityClassName, $tableAlias, $fieldName, $columnExpr, $columnAlias, $filterName, array $filterData) { $filter = ['column' => $this->getFilterByExpr($entityClassName, $tableAlias, $fieldName, $columnExpr), 'filter' => $filterName, 'filterData' => $filterData]; if ($columnAlias) { $filter['columnAlias'] = $columnAlias; } $this->accessor->setValue($this->filters, $this->currentFilterPath, $filter); $this->incrementCurrentFilterPath(); }
private function duplicateTranslatableEntity(LocaleAwareInterface $entity, array $properties, LocaleInterface $targetLocale) { $duplicate = clone $entity; foreach ($properties as $propertyName) { $value = sprintf('%s-%s', $this->propertyAccessor->getValue($entity, $propertyName), $targetLocale->getCode()); $this->propertyAccessor->setValue($duplicate, $propertyName, $value); $duplicate->setLocale($targetLocale->getCode()); $this->doctrineHelper->getEntityManager()->persist($duplicate); } }
protected function copyTranslatableEntity(LocaleAwareInterface $entity, LocaleInterface $targetLocale) { $duplicate = clone $entity; foreach ($entity->getCopyingSensitiveProperties() as $propertyName) { $value = sprintf('%s-%s', $this->propertyAccessor->getValue($entity, $propertyName), $targetLocale->getCode()); $this->propertyAccessor->setValue($duplicate, $propertyName, $value); $duplicate->setLocale($targetLocale->getCode()); $this->entityManager->persist($duplicate); } }
/** * @param AssociationTypeInterface $associationType * @param string $field * @param mixed $data */ protected function setData(AssociationTypeInterface $associationType, $field, $data) { if ('labels' === $field) { foreach ($data as $localeCode => $label) { $associationType->setLocale($localeCode); $translation = $associationType->getTranslation(); $translation->setLabel($label); } } else { $this->accessor->setValue($associationType, $field, $data); } }
/** * @inheritdoc */ public function reverseTransform($value) { if (is_null($value)) { return null; } if (!is_numeric($value) && $this->tags && $this->property) { $object = $this->metadata->newInstance(); $this->propertyAccessor->setValue($object, $this->property, $value); return $object; } return $this->em->getRepository($this->class)->find($value); }
/** * @param object $entity * @param array $data */ protected function fillFromArray($entity, array $data) { foreach ($data as $key => $value) { try { $this->guessTypeAndConvert($key, $value); $this->propertyAccessor->setValue($entity, $key, $value); } catch (NoSuchPropertyException $e) { if ($key !== 'reference') { printf('--- Unknown property %s. Omitted.' . PHP_EOL, $key); } } } }
private function setValue(&$item, $key, $value, $options = []) { $this->debug && $this->logger->info("Value adding is started."); switch ($options['type']) { case "string": case "text": case "integer": case "collection": case "bool": if (isset($options['modifier'])) { $value = $this->modify($value, $options['modifier'], $item); } break; case "date": if (!array_key_exists('format', $options)) { $options['format'] = "Y-m-d H:i:s"; } $value = !empty($value) ? \DateTime::createFromFormat($options['format'], $value) : new \DateTime(); break; case "object": $value = $this->setObjectValue($item, $key, $value, $options); break; } if (array_key_exists('value', $options)) { $value = $options['value']; } $value ? $this->accessor->setValue($item, $key, $value) : $this->logger->alert("Value is null for {$key}."); $this->debug && $this->logger->info("Value adding is completed."); }
/** * @param Attribute $attribute * @param array $options */ public function setDefaultOptions(Attribute $attribute, array $options) { $attributeOptions = []; $attributeDefaultValues = []; foreach ($options as $optionData) { $order = $this->getOption($optionData, 'order', 0); $data = $this->getOption($optionData, 'data', []); $masterOptionId = $this->getOption($optionData, 'master_option_id'); $masterOption = $attribute->getOptionById($masterOptionId); if (!$masterOption) { $masterOption = new AttributeOption(); $attribute->addOption($masterOption); } foreach ($data as $localeId => $localeData) { $localeValue = $this->getOption($localeData, 'value', ''); $option = $this->generateOption($masterOption, $localeId, $localeValue, $order); $attributeOptions[] = $option; if (!empty($localeData['is_default'])) { $attributeDefaultValues[] = $this->generateOptionDefaultValue($attribute, $option, $localeId); } } } $this->propertyAccessor->setValue($attribute, 'options', $attributeOptions); $this->propertyAccessor->setValue($attribute, 'defaultValues', $attributeDefaultValues); }
public function testSetTypeHint() { $date = new \DateTimeImmutable(); $object = new TestClass('Kévin'); $this->propertyAccessor->setValue($object, 'date', $date); $this->assertSame($date, $object->getDate()); }
public function testSetValueDeepWithMagicGetter() { $obj = new TestClassMagicGet('foo'); $obj->publicProperty = array('foo' => array('bar' => 'some_value')); $this->propertyAccessor->setValue($obj, 'publicProperty[foo][bar]', 'Updated'); $this->assertSame('Updated', $obj->publicProperty['foo']['bar']); }
private function setValue(&$item, $key, $value, $options = []) { try { $this->debug && $this->logger->info("Value adding is started."); switch ($options['type']) { case "string": case "text": case "integer": case "collection": case "bool": if (isset($options['modifier'])) { $value = $this->modify($value, $options['modifier'], $item); } break; case "date": if (isset($options['modifier'])) { $value = $this->modify($value, $options['modifier'], $item); } else { $value = $this->modifyDate($value, $options); } break; case "object": $value = $this->setObjectValue($item, $key, $value, $options); break; } if (array_key_exists('value', $options)) { $value = $options['value']; } $value ? $this->accessor->setValue($item, $key, $value) : $this->logger->alert("Value is null for {$key}."); $this->debug && $this->logger->info("Value adding is completed."); } catch (\Exception $e) { $this->logger->critical($e->getMessage()); } }
public function fetch($hash, $className) { $metadata = $this->metadataManager->loadByClassname($className); $data = null; if ($this->storageAdapter->contains($hash, $metadata->getContext())) { $data = $this->storageAdapter->fetch($hash, $metadata->getContext()); } // dispatch event $event = new DatabaseFetchEvent($hash, $data, $className, $metadata); $this->eventDispatcher->dispatch(DatabaseEvent::FETCH_EVENT, $event); // possibility to cancel store in a event-handler if ($event->isCanceled()) { return; } // possibility to change data in the event-handler $data = $event->getData(); if (!$data) { throw new \Exception('Object not found'); } if ($data['class'] !== $className) { throw new \Exception('Classname not match!'); } $model = $this->getModel($data['class']); $this->accessor->setValue($model, 'hash', $hash); if ($model instanceof DistributedModelInterface) { $this->accessor->setValue($model, 'policyCollection', unserialize($data['policies'])); } $this->serializer->deserialize($model, $data['data'], array_merge($metadata->getDataFields(), $metadata->getMetadataFields()), $this); return $model; }
/** * {@inheritdoc} */ public function invoke(callable $callable, $requestObject) { /** @var Attribute $attributeAnnotation */ $attributeAnnotation = $this->annotationReader->getMethodAnnotation(ReflectionFunctionFactory::createReflectionMethodFromCallable($callable), Attribute::class); $attributeName = $attributeAnnotation->name; $attributeValue = $this->propertyAccessor->getValue($requestObject, $attributeAnnotation->valueAt); $userId = $this->userProvider->getUserId(); if (!is_array($attributeValue) && !$this->guard->isGranted($userId, $attributeName, $attributeValue)) { throw new AccessDeniedException(); } if (is_array($attributeValue)) { $attributeValue = $this->guard->filterGranted($userId, $attributeName, $attributeValue); $this->propertyAccessor->setValue($requestObject, $attributeAnnotation->valueAt, $attributeValue); } return $this->methodInvoker->invoke($callable, $requestObject); }
function it_does_nothing_if_form_data_is_empty(FormEvent $event, FormInterface $form, PropertyAccessor $propertyAccessor) { $event->getForm()->willReturn($form); $form->getData()->willReturn(null); $event->setData(Argument::any())->shouldNotBeCalled(); $propertyAccessor->setValue(Argument::any(), Argument::any(), Argument::any())->shouldNotBeCalled(); $this->preSubmit($event); }
/** * @param CategoryInterface $category * @param string $field * @param mixed $data */ protected function setData(CategoryInterface $category, $field, $data) { if ('labels' === $field) { foreach ($data as $localeCode => $label) { $category->setLocale($localeCode); } } elseif ('parent' === $field) { $categoryParent = $this->findParent($data); if (null !== $categoryParent) { $category->setParent($categoryParent); } else { throw new \InvalidArgumentException(sprintf('The parent category "%s" does not exist', $data)); } } else { $this->accessor->setValue($category, $field, $data); } }
public function testArrayNotBeeingOverwritten() { $value = array('value1' => 'foo', 'value2' => 'bar'); $object = new TestClass($value); $this->propertyAccessor->setValue($object, 'publicAccessor[value2]', 'baz'); $this->assertSame('baz', $this->propertyAccessor->getValue($object, 'publicAccessor[value2]')); $this->assertSame(array('value1' => 'foo', 'value2' => 'baz'), $object->getPublicAccessor()); }
/** * Update field * * @param $resource object * @param $path string * @param $value */ protected function updateField(&$resource, $path, $value) { // create property accessor if (!$this->propertyAccessor) { $this->propertyAccessor = new PropertyAccessor(); } $this->propertyAccessor->setValue($resource, $path, $value); }
/** * Builds the json. * * @return string The builded json. */ public function build() { $json = array(); foreach ($this->values as $path => $value) { $this->accessor->setValue($json, $path, $value); } return str_replace(array_keys($this->escapes), array_values($this->escapes), json_encode($json, $this->jsonEncodeOptions)); }
/** * @param mixed $entity * @param array $entityData * * @return mixed */ protected function populate($entity, array $entityData) { foreach ($entityData as $key => $value) { if ($this->propertyAccessor->isWritable($entity, $key)) { $this->propertyAccessor->setValue($entity, $key, $value); } } return $entity; }
/** * @param mixed $entity * @param string $fieldName * @param mixed $value * @param int $level */ protected function fixEntityField($entity, $fieldName, $value, $level) { if ($this->isEntityDetached($value)) { $value = $this->reloadEntity($value); $this->propertyAccessor->setValue($entity, $fieldName, $value); } else { $this->fixEntityAssociationFields($value, $level - 1); } }
/** * @inheritdoc */ public function reverseTransform($value) { if (!is_array($value) || count($value) === 0) { return new ArrayCollection(); } if ($this->tags && $this->property) { $objects = []; foreach ($value as $val) { if (!is_numeric($value)) { $objects[] = $this->metadata->newInstance(); $this->propertyAccessor->setValue(end($objects), $this->property, $val); } $objects[] = $this->em->getRepository($this->class)->find($val); } return $objects; } return $this->em->getRepository($this->class)->findBy([$this->metadata->getIdentifier()[0] => $value]); }
/** * {@inheritdoc} */ public function offsetSet($offset, $value) { $action = new BatchAction($offset); $accessor = new PropertyAccessor(); foreach ($value as $property => $val) { $accessor->setValue($action, $property, $val); } $this->actions[$offset] = $action; }
/** * Do merge between remote data and local data relation * If field changed on both sides check priority * * @param array $fieldsList List of scalar fields to merge * @param object $remoteData Data from remote instance * @param object $localData Current database data * @param object $mergedData Data needs to merge */ protected function mergeScalars(array $fieldsList, $remoteData, $localData, $mergedData) { foreach ($fieldsList as $field) { if (!$this->isFieldChanged($field, $localData, $mergedData) || $this->isRemotePrioritized()) { // override always except when field is changed and local data has greater priority $this->accessor->setValue($mergedData, $field, $this->accessor->getValue($remoteData, $field)); } } }
/** * {@inheritdoc} * * @throws MappingException */ public function process(&$item) { 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); } }
/** * @param AttributeInterface $attribute * @param string $field * @param mixed $data * * @throws \InvalidArgumentException */ protected function setData(AttributeInterface $attribute, $field, $data) { if ('labels' === $field) { foreach ($data as $localeCode => $label) { $attribute->setLocale($localeCode); $translation = $attribute->getTranslation(); $translation->setLabel($label); } } elseif ('group' === $field) { $attributeGroup = $this->findAttributeGroup($data); if (null !== $attributeGroup) { $attribute->setGroup($attributeGroup); } else { throw new \InvalidArgumentException(sprintf('AttributeGroup "%s" does not exist', $data)); } } else { $this->accessor->setValue($attribute, $field, $data); } }