/**
  * {@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());
             }
         }
     }
 }
Пример #2
0
 /**
  * @expectedException \Lug\Component\Grid\Exception\InvalidTypeException
  * @expectedExceptionMessage The "name" number column type expects a numeric value, got "stdClass".
  */
 public function testRenderWithoutScalar()
 {
     $this->propertyAccessor->expects($this->once())->method('getValue')->with($this->identicalTo($data = new \stdClass()), $this->identicalTo($path = 'path_value'))->will($this->returnValue(new \stdClass()));
     $column = $this->createColumnMock();
     $column->expects($this->once())->method('getName')->will($this->returnValue('name'));
     $this->type->render($data, ['column' => $column, 'path' => $path]);
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public function getIriFromItem($item, $referenceType = RouterInterface::ABSOLUTE_PATH)
 {
     if ($resource = $this->resourceCollection->getResourceForEntity($item)) {
         return $this->router->generate($this->getRouteName($resource, 'item'), ['id' => $this->propertyAccessor->getValue($item, 'id')], $referenceType);
     }
     throw new \InvalidArgumentException(sprintf('No resource associated with the type "%s".', get_class($item)));
 }
 /**
  * {@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 normalize($violationList, $format = null, array $context = [])
 {
     if ($violationList instanceof \Exception) {
         if ($this->debug) {
             $trace = $violationList->getTrace();
         }
     }
     $data = ['@context' => '/api/contexts/ConstraintViolationList', '@type' => 'ConstraintViolationList', 'title' => 'An error occurred', 'violations' => []];
     foreach ($violationList as $violation) {
         $key = $violation->getPropertyPath();
         $invalidValue = $violation->getInvalidValue();
         if (method_exists($violation->getRoot(), '__toString')) {
             $invalidValue = $this->propertyAccessor->getValue($violation->getRoot(), $violation->getPropertyPath());
         }
         if ($violation->getConstraint() instanceof UniqueEntity) {
             $class = method_exists($violation->getRoot(), 'getConfig') ? $violation->getRoot()->getConfig() : $violation->getRoot();
             $reflexion = new \ReflectionClass($class);
             $key = strtolower($reflexion->getShortname());
         }
         $data['violations'][$key][] = ['property' => $violation->getPropertyPath(), 'invalidValue' => $invalidValue, 'message' => $violation->getMessage()];
     }
     if (isset($trace)) {
         $data['trace'] = $trace;
     }
     return $data;
 }
 /**
  * Transforms an object into an elastica object having the required keys
  *
  * @param object $object the object to convert
  * @param array  $fields the keys we want to have in the returned array
  *
  * @return Document
  **/
 public function transform($object, array $fields)
 {
     $identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
     $document = new Document($identifier);
     foreach ($fields as $key => $mapping) {
         if ($key == '_parent') {
             $property = null !== $mapping['property'] ? $mapping['property'] : $mapping['type'];
             $value = $this->propertyAccessor->getValue($object, $property);
             $document->setParent($this->propertyAccessor->getValue($value, $mapping['identifier']));
             continue;
         }
         $value = $this->propertyAccessor->getValue($object, $key);
         if (isset($mapping['type']) && in_array($mapping['type'], array('nested', 'object')) && isset($mapping['properties']) && !empty($mapping['properties'])) {
             /* $value is a nested document or object. Transform $value into
              * an array of documents, respective the mapped properties.
              */
             $document->set($key, $this->transformNested($value, $mapping['properties']));
             continue;
         }
         if (isset($mapping['type']) && $mapping['type'] == 'attachment') {
             // $value is an attachment. Add it to the document.
             if ($value instanceof \SplFileInfo) {
                 $document->addFile($key, $value->getPathName());
             } else {
                 $document->addFileContent($key, $value);
             }
             continue;
         }
         $document->set($key, $this->normalizeValue($value));
     }
     return $document;
 }
 /**
  * {@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());
             }
         }
     }
 }
Пример #8
0
 /**
  * @param string      $name
  * @param string|null $path
  *
  * @return mixed
  */
 public function get($name, $path = null)
 {
     $path = $path ?: (isset($this->mapping[$name]) ? $this->mapping[$name] : $name);
     if (is_array($this->data)) {
         $path = '[' . str_replace('.', '][', $path) . ']';
     }
     return $this->accessor->getValue($this->data, $path);
 }
Пример #9
0
 /**
  * {@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);
     }
 }
Пример #10
0
 public function readFrom($data)
 {
     $values = array();
     foreach ($this->paths as $path) {
         $values[] = $this->accessor->getValue($data, $path);
     }
     return $values;
 }
Пример #11
0
 /**
  * {@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
     }
 }
Пример #12
0
 /**
  * {@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;
 }
Пример #13
0
 /**
  * @param mixed[] $parameters
  * @param mixed[] $data
  *
  * @return mixed[]
  */
 private function resolveRouteParameters(array $parameters, $data)
 {
     $routeParameters = [];
     foreach ($parameters as $parameter) {
         $routeParameters[$parameter] = $this->propertyAccessor->getValue($data, $parameter);
     }
     return $routeParameters;
 }
Пример #14
0
 /**
  * {@inheritdoc}
  */
 public function getProperty(MetadataSubjectInterface $metadataSubject, $propertyPath = null)
 {
     $metadata = $this->metadataProvider->findMetadataBySubject($metadataSubject);
     if (null === $propertyPath) {
         return $metadata;
     }
     return $this->propertyAccessor->getValue($metadata, $propertyPath);
 }
Пример #15
0
 /**
  * genere le formulaire.
  *
  * @param \Symfony\Component\Form\FormView      $view
  * @param \Symfony\Component\Form\FormInterface $form
  * @param array                                 $options
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     foreach ($view->vars['choices'] as $choice) {
         $dataNode = $choice->data;
         $level = $this->propertyAccessor->getValue($dataNode, 'lvl');
         $choice->label = str_repeat(str_repeat(' ', $level), 4) . $choice->label;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getPrice(array $weightables)
 {
     $total = 0;
     foreach ($weightables as $weightable) {
         $total += $this->propertyAccessor->getValue($weightable, $this->shippingPriceField);
     }
     return $total;
 }
 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);
 }
 /**
  * @param FormInterface $form
  * @return mixed
  */
 public function getFormNormDataLocale(FormInterface $form)
 {
     $classMetadata = $this->getFormTranslatableMetadata($form);
     if (empty($classMetadata) || !$form->getNormData()) {
         return null;
     }
     return $this->propertyAccessor->getValue($form->getNormData(), $classMetadata->localeProperty);
 }
Пример #19
0
 /**
  * @param \Symfony\Component\PropertyAccess\PropertyAccessorInterface $accessor
  * @param \FSi\Bundle\AdminBundle\Display\Property $property
  * @return mixed
  */
 private function getPropertyValue(PropertyAccessorInterface $accessor, Property $property)
 {
     $value = $accessor->getValue($this->object, $property->getPath());
     foreach ($property->getValueFormatters() as $formatter) {
         $value = $formatter->format($value);
     }
     return $value;
 }
Пример #20
0
 /**
  * {@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;
 }
 public function setUp()
 {
     $this->accessor = $this->getMockBuilder('Symfony\\Component\\PropertyAccess\\PropertyAccessorInterface')->getMock();
     $this->accessor->expects($this->any())->method('getValue')->will($this->returnCallback(function ($item, $path) {
         static $i = 0;
         return array($item, $path, $i++);
     }));
     $this->resolver = new PropertyAccessResolver($this->accessor);
 }
Пример #22
0
 /**
  * @return mixed
  */
 public function &get()
 {
     if ($this->path) {
         $value = $this->accessor->getValue($this->object, $this->path);
     } else {
         $value =& $this->object;
     }
     return $value;
 }
 /**
  * @param mixed  $object
  * @param Column $column
  * @param array  $options
  * @return string
  * @throws \Exception
  */
 public function renderObjectValue($object, Column $column, array $options = [])
 {
     try {
         $value = $this->accessor->getValue($object, $column->getPropertyPath());
         return $column->renderValue($value, $options);
     } catch (UnexpectedTypeException $e) {
         return false;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function __invoke(FilterTransformer $transformer, Expression $expression, $element, Configuration $config)
 {
     $name = $expression->getArg(0);
     if (!$name->isValue()) {
         throw new \InvalidArgumentException(sprintf('Field name should be a value, expression "%s" given', $name->getExp()));
     }
     $name = $config->getNameResolver()->resolve($name->getValue());
     return $this->propertyAccessor->getValue($element, $name);
 }
 private function getArguments($payload)
 {
     if ($this->accessor->isReadable($payload, '[args]')) {
         return $this->accessor->getValue($payload, '[args]');
     }
     if ($this->accessor->isReadable($payload, 'args')) {
         return $this->accessor->getValue($payload, 'args');
     }
     return [];
 }
Пример #26
0
 /**
  * {@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 (!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 process($source)
 {
     $this->initializeProperties();
     $row = new Row();
     foreach ($this->propertiesList as $property) {
         $value = $this->accessor->getValue($source, $property);
         $row->appendCell(new Cell($value));
     }
     return $row;
 }
Пример #29
0
 public function testRender()
 {
     $this->urlGenerator->expects($this->once())->method('generate')->with($this->identicalTo($route = 'route_value'), $this->identicalTo([$routeParameter = 'route_parameter' => $routeParameterValue = 'route_parameter_value']), $this->identicalTo($routeReferenceType = UrlGeneratorInterface::ABSOLUTE_PATH))->will($this->returnValue($url = 'url_value'));
     $this->propertyAccessor->expects($this->once())->method('getValue')->with($this->identicalTo($data = new \stdClass()), $this->identicalTo($routeParameter))->will($this->returnValue($routeParameterValue));
     $action = $this->createActionMock();
     $action->expects($this->once())->method('getLabel')->will($this->returnValue($actionLabel = 'action_label'));
     $action->expects($this->once())->method('getOption')->with($this->identicalTo('trans_domain'))->will($this->returnValue($actionTransDomain = 'action_trans_domain'));
     $this->formFactory->expects($this->once())->method('create')->with($this->identicalTo(CsrfProtectionType::class), $this->isNull(), $this->identicalTo(['method' => $method = Request::METHOD_DELETE, 'action' => $url, 'label' => $actionLabel, 'translation_domain' => $actionTransDomain]))->will($this->returnValue($form = $this->createFormMock()));
     $form->expects($this->once())->method('createView')->will($this->returnValue($view = $this->createFormViewMock()));
     $this->assertSame($view, $this->type->render($data, ['action' => $action, 'method' => strtolower($method), 'route' => $route, 'route_parameters' => [$routeParameter], 'route_reference_type' => $routeReferenceType]));
 }
 /**
  * {@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);
 }