コード例 #1
0
 /**
  * {@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;
 }
コード例 #2
0
ファイル: ObjectNormalizer.php プロジェクト: aWEBoLabs/taxi
 /**
  * {@inheritdoc}
  *
  * @throws CircularReferenceException
  */
 public function normalize($object, $format = null, array $context = array())
 {
     if (!isset($context['cache_key'])) {
         $context['cache_key'] = $this->getCacheKey($context);
     }
     if ($this->isCircularReference($object, $context)) {
         return $this->handleCircularReference($object);
     }
     $data = array();
     $attributes = $this->getAttributes($object, $context);
     foreach ($attributes as $attribute) {
         if (in_array($attribute, $this->ignoredAttributes)) {
             continue;
         }
         $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
         if (isset($this->callbacks[$attribute])) {
             $attributeValue = call_user_func($this->callbacks[$attribute], $attributeValue);
         }
         if (null !== $attributeValue && !is_scalar($attributeValue)) {
             if (!$this->serializer instanceof NormalizerInterface) {
                 throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a normalizer', $attribute));
             }
             $attributeValue = $this->serializer->normalize($attributeValue, $format, $context);
         }
         if ($this->nameConverter) {
             $attribute = $this->nameConverter->normalize($attribute);
         }
         $data[$attribute] = $attributeValue;
     }
     return $data;
 }
コード例 #3
0
 /**
  * {@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());
             }
         }
     }
 }
コード例 #4
0
 /**
  * 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;
 }
コード例 #5
0
 /**
  * {@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());
             }
         }
     }
 }
コード例 #6
0
 /**
  * {@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;
 }
コード例 #7
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)));
 }
コード例 #8
0
ファイル: PathsReader.php プロジェクト: devhelp/normalizer
 public function readFrom($data)
 {
     $values = array();
     foreach ($this->paths as $path) {
         $values[] = $this->accessor->getValue($data, $path);
     }
     return $values;
 }
コード例 #9
0
ファイル: LinkType.php プロジェクト: php-lug/lug
 /**
  * @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;
 }
コード例 #10
0
 /**
  * {@inheritdoc}
  */
 public function getPrice(array $weightables)
 {
     $total = 0;
     foreach ($weightables as $weightable) {
         $total += $this->propertyAccessor->getValue($weightable, $this->shippingPriceField);
     }
     return $total;
 }
コード例 #11
0
 /**
  * @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);
 }
コード例 #12
0
ファイル: Entity.php プロジェクト: jfsimon/datagrid
 /**
  * @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);
 }
コード例 #13
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;
     }
 }
コード例 #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
 /**
  * {@inheritdoc}
  */
 public function getState($object)
 {
     try {
         return $this->propertyAccessor->getValue($object, $this->propertyPath);
     } catch (SymfonyNoSuchPropertyException $e) {
         throw new NoSuchPropertyException(sprintf('Property path "%s" on object "%s" does not exist.', $this->propertyPath, get_class($object)), $e->getCode(), $e);
     }
 }
コード例 #16
0
 /**
  * Loads filesystem translations found in Resource folder
  */
 protected function loadFilesystemTranslations()
 {
     foreach ($this->locales as $locale) {
         $messages = $this->get('translator')->getMessages($locale->getCode());
         $translations = $this->propertyAccessor->getValue($messages, '[wellcommerce]');
         $this->importMessages($translations, $locale);
     }
 }
コード例 #17
0
 /**
  * {@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);
 }
コード例 #18
0
ファイル: Accessor.php プロジェクト: bcncommerce/serializer
 /**
  * @return mixed
  */
 public function &get()
 {
     if ($this->path) {
         $value = $this->accessor->getValue($this->object, $this->path);
     } else {
         $value =& $this->object;
     }
     return $value;
 }
コード例 #19
0
 /**
  * @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;
     }
 }
コード例 #20
0
ファイル: StdPropertyAccessor.php プロジェクト: nelmio/alice
 /**
  * @inheritdoc
  */
 public function getValue($objectOrArray, $propertyPath)
 {
     if (false === $objectOrArray instanceof \stdClass) {
         return $this->decoratedPropertyAccessor->getValue($objectOrArray, $propertyPath);
     }
     if (false === isset($objectOrArray->{$propertyPath})) {
         throw NoSuchPropertyExceptionFactory::createForUnreadablePropertyFromStdClass($propertyPath);
     }
     return $objectOrArray->{$propertyPath};
 }
コード例 #21
0
 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 [];
 }
コード例 #22
0
 /**
  * {@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;
 }
コード例 #23
0
 /**
  * @param FormView      $view
  * @param FormInterface $form
  * @param array         $options
  */
 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     parent::finishView($view, $form, $options);
     foreach ($view->vars['choices'] as $choice) {
         $additionalAttributes = array();
         foreach ($options['option_attributes'] as $attributeName => $choicePath) {
             $additionalAttributes[$attributeName] = $this->propertyAccessor->getValue($choice->data, $choicePath);
         }
         $choice->attr = array_replace(isset($choice->attr) ? $choice->attr : array(), $additionalAttributes);
     }
 }
コード例 #24
0
 /**
  * @param DomainEvent $event
  */
 public function validateDefaultLocale(DomainEvent $event)
 {
     $data = $event->getData();
     if ($data !== $this->localeProvider->getDefaultLocale()) {
         return;
     }
     $resource = $event->getResource();
     $event->setStopped(true);
     $event->setStatusCode(409);
     $event->setMessageType('error');
     $event->setMessage($this->translator->trans('lug.' . $resource->getName() . '.' . $event->getAction() . '.default', ['%' . $resource->getName() . '%' => $this->propertyAccessor->getValue($data, $resource->getLabelPropertyPath())], 'flashes'));
 }
コード例 #25
0
 private function resolveByPath($payload, $callablePath, $argsPath)
 {
     if (!$this->accessor->isReadable($payload, $callablePath)) {
         return;
     }
     $id = $this->accessor->getValue($payload, $callablePath);
     if (!is_string($id)) {
         return;
     }
     $args = $this->accessor->isReadable($payload, $argsPath) ? $this->accessor->getValue($payload, $argsPath) : [];
     return [$this->container[$this->idPrefix . $id], $args];
 }
コード例 #26
0
 /**
  * {@inheritdoc}
  *
  * @throws CircularReferenceException
  */
 public function normalize($object, $format = null, array $context = array())
 {
     if ($this->isCircularReference($object, $context)) {
         return $this->handleCircularReference($object);
     }
     $data = array();
     $attributes = $this->getAllowedAttributes($object, $context, true);
     // If not using groups, detect manually
     if (false === $attributes) {
         $attributes = array();
         // methods
         $reflClass = new \ReflectionClass($object);
         foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
             if (!$reflMethod->isStatic() && !$reflMethod->isConstructor() && !$reflMethod->isDestructor() && 0 === $reflMethod->getNumberOfRequiredParameters()) {
                 $name = $reflMethod->getName();
                 if (strpos($name, 'get') === 0 || strpos($name, 'has') === 0) {
                     // getters and hassers
                     $attributes[lcfirst(substr($name, 3))] = true;
                 } elseif (strpos($name, 'is') === 0) {
                     // issers
                     $attributes[lcfirst(substr($name, 2))] = true;
                 }
             }
         }
         // properties
         foreach ($reflClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $reflProperty) {
             if (!$reflProperty->isStatic()) {
                 $attributes[$reflProperty->getName()] = true;
             }
         }
         $attributes = array_keys($attributes);
     }
     foreach ($attributes as $attribute) {
         if (in_array($attribute, $this->ignoredAttributes)) {
             continue;
         }
         $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
         if (isset($this->callbacks[$attribute])) {
             $attributeValue = call_user_func($this->callbacks[$attribute], $attributeValue);
         }
         if (null !== $attributeValue && !is_scalar($attributeValue)) {
             if (!$this->serializer instanceof NormalizerInterface) {
                 throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a normalizer', $attribute));
             }
             $attributeValue = $this->serializer->normalize($attributeValue, $format, $context);
         }
         if ($this->nameConverter) {
             $attribute = $this->nameConverter->normalize($attribute);
         }
         $data[$attribute] = $attributeValue;
     }
     return $data;
 }
コード例 #27
0
ファイル: NestedAnchorType.php プロジェクト: ekyna/table
 /**
  * Returns the children ids.
  *
  * @param mixed $data
  * @param PropertyAccessorInterface $propertyAccessor
  * @param array $options
  * @return array
  */
 private function getChildrenIds($data, PropertyAccessorInterface $propertyAccessor, array $options)
 {
     $children = $propertyAccessor->getValue($data, $options['children_property_path']);
     if ($children instanceof Collection) {
         $children = $children->toArray();
         if (!empty($children)) {
             return array_map(function ($child) use($propertyAccessor) {
                 return $propertyAccessor->getValue($child, 'id');
             }, $children);
         }
     }
     return [];
 }
コード例 #28
0
 /**
  * @return array
  */
 public function getData()
 {
     $data = [];
     foreach ($this->baseTableData->getData() as $baseRow) {
         $row = [];
         foreach ($this->getColumns() as $column => $label) {
             $value = $this->propertyAccessor->getValue($baseRow, $column);
             $row[$column] = $this->decorator->decorateData($value, $column, $baseRow);
         }
         $data[] = $row;
     }
     return $data;
 }
コード例 #29
0
 /**
  * {@inheritdoc}
  */
 public function process($source)
 {
     $fields = $this->getFields();
     $row = new Row();
     foreach ($this->schemaProvider->getSchema()->getMetadataProperties() as $name) {
         $metaValue = $this->accessor->getValue($source, $name);
         $row->setMetadataProperty($name, $metaValue);
     }
     foreach ($fields as $property => $field) {
         $value = $this->accessor->getValue($source, $property);
         $row->appendCell(new Cell($value, $field));
     }
     return $row;
 }
コード例 #30
0
 /**
  * Gets the ID from an URI or a raw ID.
  *
  * @param string $value
  *
  * @return string
  */
 private function getFilterValueFromUrl($value)
 {
     if (is_array($value)) {
         $items = [];
         foreach ($value as $iri) {
             try {
                 if ($item = $this->iriConverter->getItemFromIri($iri)) {
                     $items[] = $this->propertyAccessor->getValue($item, 'id');
                 } else {
                     $items[] = $iri;
                 }
             } catch (\InvalidArgumentException $e) {
                 $items[] = $iri;
             }
         }
         return $items;
     }
     try {
         if ($item = $this->iriConverter->getItemFromIri($value)) {
             return $this->propertyAccessor->getValue($item, 'id');
         }
     } catch (\InvalidArgumentException $e) {
         // Do nothing, return the raw value
     }
     return $value;
 }