Author: Bernhard Schussek (bschussek@gmail.com)
Author: Kévin Dunglas (dunglas@gmail.com)
Author: Nicolas Grekas (p@tchwork.com)
Inheritance: implements Symfony\Component\PropertyAccess\PropertyAccessorInterface
コード例 #1
1
 public function renderBlock(\Twig_Template $template, ColumnInterface $column, $object, $context, $blocks)
 {
     try {
         $value = $this->accessor->getValue($object, $column->getName());
     } catch (ExceptionInterface $exception) {
         $value = null;
     }
     $block = 'crudify_field_' . $column->getType();
     // check if the block exists
     $hasBlock = false;
     if (!isset($blocks[$block])) {
         $current = $template;
         do {
             if ($current->hasBlock($block)) {
                 break;
             }
             $current = $current->getParent($context);
         } while ($current instanceof \Twig_Template);
         if ($current instanceof \Twig_Template) {
             $hasBlock = true;
         }
     } else {
         $hasBlock = true;
     }
     if ($hasBlock) {
         $context['value'] = $value;
         $context['definition'] = $column->getParent()->getParent();
         $context['column'] = $column;
         $context['object'] = $object;
         $result = $template->renderBlock($block, $context, $blocks);
     } else {
         $result = htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'utf-8');
     }
     return $result;
 }
コード例 #2
0
 /**
  * {@inheritDoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $admin = clone $this->getAdmin($options);
     if ($admin->hasParentFieldDescription()) {
         $admin->getParentFieldDescription()->setAssociationAdmin($admin);
     }
     if ($options['delete'] && $admin->isGranted('DELETE')) {
         if (!array_key_exists('translation_domain', $options['delete_options']['type_options'])) {
             $options['delete_options']['type_options']['translation_domain'] = $admin->getTranslationDomain();
         }
         $builder->add('_delete', $options['delete_options']['type'], $options['delete_options']['type_options']);
     }
     // hack to make sure the subject is correctly set
     // https://github.com/sonata-project/SonataAdminBundle/pull/2076
     if ($builder->getData() === null) {
         $p = new PropertyAccessor(false, true);
         try {
             $subject = $p->getValue($admin->getParentFieldDescription()->getAdmin()->getSubject(), $this->getFieldDescription($options)->getFieldName() . $options['property_path']);
             $builder->setData($subject);
         } catch (NoSuchIndexException $e) {
             // no object here
         }
     }
     $admin->setSubject($builder->getData());
     $admin->defineFormBuilder($builder);
     $builder->addModelTransformer(new ArrayToModelTransformer($admin->getModelManager(), $admin->getClass()));
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 public function convert($value)
 {
     $ref = new \ReflectionClass($this->class);
     $data = $ref->newInstanceWithoutConstructor();
     $this->propertyAccessor->setValue($data, $this->label, $value);
     return (object) $data;
 }
コード例 #4
0
 /**
  * @param FormView $formView
  * @param array    $data
  *
  * @return FormView
  */
 public function formAttributes(FormView $formView, array $data)
 {
     $formView = clone $formView;
     foreach ($data as $key => $value) {
         $path = 'children[' . str_replace('.', '].children[', $key) . ']';
         if (false === $this->accessor->isReadable($formView, $path)) {
             continue;
         }
         /** @var FormView $field */
         $field = $this->accessor->getValue($formView, $path);
         if (false === $field instanceof FormView) {
             throw new \RuntimeException("Cannot set form attribute: {$key} is not a FormView instance");
         }
         if (is_string($value)) {
             $value = ["class" => " {$value}"];
         }
         if (false === isset($field->vars['attr'])) {
             $field->vars['attr'] = [];
         }
         foreach ($value as $name => $attribute) {
             if (isset($field->vars['attr'][$name]) && " " === substr($attribute, 0, 1)) {
                 $attribute = $field->vars['attr'][$name] . $attribute;
             }
             $field->vars['attr'][$name] = trim($attribute);
         }
     }
     return $formView;
 }
コード例 #5
0
 /**
  * @param object     $entity
  * @param Constraint $constraint
  *
  * @throws UnexpectedTypeException
  * @throws ConstraintDefinitionException
  */
 public function validate($entity, Constraint $constraint)
 {
     if (!$constraint instanceof HasEnabledEntity) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\HasEnabledEntity');
     }
     $enabled = $this->accessor->getValue($entity, $constraint->enabledPath);
     if ($enabled === true) {
         return;
     }
     $objectManager = $this->getProperObjectManager($constraint->objectManager, $entity);
     $this->ensureEntityHasProvidedEnabledField($objectManager, $entity, $constraint->enabledPath);
     $criteria = array($constraint->enabledPath => true);
     $repository = $objectManager->getRepository(get_class($entity));
     $results = $repository->{$constraint->repositoryMethod}($criteria);
     /* If the result is a MongoCursor, it must be advanced to the first
      * element. Rewinding should have no ill effect if $result is another
      * iterator implementation.
      */
     if ($results instanceof \Iterator) {
         $results->rewind();
     } elseif (is_array($results)) {
         reset($results);
     }
     if ($this->isLastEnabledEntity($results, $entity)) {
         $errorPath = null !== $constraint->errorPath ? $constraint->errorPath : $constraint->enabledPath;
         $this->context->addViolationAt($errorPath, $constraint->message);
     }
 }
コード例 #6
0
 /**
  * @param object $entity
  * @param string $field
  * @param string $locale
  * @param mixed $fieldData
  * @throws \Bigfoot\Bundle\CoreBundle\Exception\InvalidArgumentException
  */
 public function translate($entity, $field, $locale, $fieldData)
 {
     $em = $this->em;
     $meta = $em->getClassMetadata(get_class($entity));
     $listener = $this->getTranslatableListener();
     $persistDefaultLocaleTransInEntity = $listener->getPersistDefaultLocaleTranslation();
     if (is_object($entity)) {
         $entityClass = $entity instanceof Proxy ? get_parent_class($entity) : get_class($entity);
     } else {
         throw new InvalidArgumentException('Argument 1 passed to TranslationRepository::translate must be an object');
     }
     $reflectionClass = new \ReflectionClass($entityClass);
     $entityTranslationClass = $this->isPersonnalTranslationRecursive($reflectionClass)->class;
     if ($locale === $listener->getTranslatableLocale($entity, $meta)) {
         $meta->getReflectionProperty($field)->setValue($entity, $fieldData);
         $em->persist($entity);
     } elseif (!$persistDefaultLocaleTransInEntity && $locale === $listener->getDefaultLocale()) {
         $trans = new $entityTranslationClass($locale, $field, $fieldData);
         $listener->setTranslationInDefaultLocale(spl_object_hash($entity), $field, $trans);
     } else {
         $translationClassRepository = $this->em->getRepository($entityTranslationClass);
         $meta = $em->getClassMetadata(get_class($entity));
         $identifier = $meta->getSingleIdentifierFieldName();
         $translation = null;
         if ($entity && $this->propertyAccessor->getValue($entity, $identifier)) {
             $translation = $translationClassRepository->findOneBy(array('locale' => $locale, 'field' => $field, 'object' => $entity));
         }
         if ($translation) {
             $translation->setContent($fieldData);
         } elseif ($fieldData !== null) {
             $entity->addTranslation(new $entityTranslationClass($locale, $field, $fieldData));
         }
     }
 }
コード例 #7
0
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $propertyAccessor = new PropertyAccessor();
     $builder->add('firstName', null, array('label' => false, 'widget_form_group' => false, 'attr' => array('placeholder' => 'First name'), 'constraints' => array(new NotBlank(), new Length(array('max' => 100)))))->add('lastName', null, array('label' => false, 'widget_form_group' => false, 'attr' => array('placeholder' => 'Last name'), 'constraints' => array(new NotBlank(), new Length(array('max' => 100)))))->add('headline', null, array('label' => 'Occupation', 'render_required_asterisk' => true))->add('about', 'textarea', array('attr' => array('rows' => 3)))->add('contactEmail', 'email', array('render_required_asterisk' => true))->add('contactNumber', 'tel', array('format' => PhoneNumberFormat::INTERNATIONAL, 'attr' => array('placeholder' => 'International format (e.g. +61 412 345 678)'), 'invalid_message' => 'Phone number must follow international format (e.g. +61 412 345 678)', 'render_required_asterisk' => true))->add('industryPreference', 'entity', array('class' => 'App\\ResumeBundle\\Entity\\Industry', 'multiple' => true))->add('availableDate', 'date', array('widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'html5' => false, 'label' => 'Available for employment from', 'attr' => array('class' => 'date-picker')))->add('employmentStatus', 'entity', array('class' => 'App\\ResumeBundle\\Entity\\EmploymentStatus', 'empty_data' => '', 'empty_value' => 'N/A', 'required' => false, 'choice_attr' => function ($choice, $key) use(&$propertyAccessor) {
         $value = $propertyAccessor->getValue($choice, 'noticeRequired');
         return ['data-require-notice' => $value ? 1 : 0];
     }, 'attr' => array('class' => 'employment-status-select')))->add('weeksOfNotice', null, array('label' => 'How many weeks of notice do you need?', 'widget_form_group_attr' => array('class' => 'form-group weeks-of-notice hidden')))->add('gs1Certifications', 'collection', array('label' => 'GS1 certifications', 'allow_add' => true, 'allow_delete' => true, 'type' => 'student_gs1_cert', 'prototype' => true, 'horizontal_wrap_children' => true, 'error_bubbling' => false, 'options' => array('label_render' => false, 'widget_remove_btn' => array('horizontal_wrapper_div' => array('class' => "col-sm-1"), 'wrapper_div' => false), 'horizontal' => true, 'horizontal_label_offset_class' => "", 'horizontal_input_wrapper_class' => "col-sm-11")))->add('certifications', 'collection', array('label' => 'Certifications', 'allow_add' => true, 'allow_delete' => true, 'type' => 'student_cert', 'prototype' => true, 'horizontal_wrap_children' => true, 'error_bubbling' => false, 'options' => array('label_render' => false, 'widget_remove_btn' => array('horizontal_wrapper_div' => array('class' => "col-sm-1"), 'wrapper_div' => false), 'horizontal' => true, 'horizontal_label_offset_class' => "", 'horizontal_input_wrapper_class' => "col-sm-11")))->add('educations', 'collection', array('label' => 'Education', 'allow_add' => true, 'allow_delete' => true, 'type' => 'student_education', 'prototype' => true, 'horizontal_wrap_children' => true, 'error_bubbling' => false, 'options' => array('label_render' => false, 'widget_remove_btn' => array('horizontal_wrapper_div' => array('class' => "col-sm-1  col-xs-12"), 'wrapper_div' => false), 'horizontal' => true, 'horizontal_label_offset_class' => "", 'horizontal_input_wrapper_class' => "col-sm-11  col-xs-12")))->add('socialNetworks', 'collection', array('allow_add' => true, 'allow_delete' => true, 'type' => 'student_social_network', 'prototype' => true, 'horizontal_wrap_children' => true, 'error_bubbling' => false, 'options' => array('label_render' => false, 'widget_remove_btn' => array('horizontal_wrapper_div' => array('class' => "col-sm-1"), 'wrapper_div' => false), 'horizontal' => true, 'horizontal_label_offset_class' => "", 'horizontal_input_wrapper_class' => "col-sm-11")))->add('country', 'country', array('preferred_choices' => array('AU'), 'label' => 'Country (current residence)', 'render_required_asterisk' => true))->add('state', 'text', array('label' => 'State (current residence)', 'render_required_asterisk' => true))->add('city', 'text', array('label' => 'City (current residence)', 'render_required_asterisk' => true))->add('workingRight', 'choice', array('choices' => array(0 => 'No', 1 => 'Yes'), 'render_required_asterisk' => true, 'choice_value' => function ($choiceKey) {
         if (null === $choiceKey) {
             return null;
         }
         $stringChoiceKey = (string) $choiceKey;
         if ('1' === $stringChoiceKey) {
             return 'true';
         }
         if ('0' === $stringChoiceKey || '' === $stringChoiceKey) {
             return 'false';
         }
         throw new \Exception('Unexpected choice key: ' . $choiceKey);
     }, 'expanded' => true, 'label' => 'Do you have full working rights in Australia?'))->add('avatar', 'student_avatar')->add('resume', 'student_resume', array('render_required_asterisk' => true))->add('save', 'submit', array('attr' => array('class' => 'save btn-sm btn-info')));
     // Make sure resume is uploaded
     $builder->get('resume')->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
         $resume = $event->getData();
         if ($resume->getId() === null && $resume->getFile() === null) {
             $event->getForm()->get('file')->addError(new FormError("You must upload a resume"));
         }
     });
 }
コード例 #8
0
 /**
  * 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);
 }
 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);
 }
コード例 #10
0
 /**
  * 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;
 }
コード例 #11
0
 private function processResults($entities, $targetEntityConfig)
 {
     $results = array();
     foreach ($entities as $entity) {
         $results[] = array('id' => $this->propertyAccessor->getValue($entity, $targetEntityConfig['primary_key_field_name']), 'text' => (string) $entity);
     }
     return $results;
 }
コード例 #12
0
 /**
  * {@inheritdoc}
  */
 public function convertItem($item)
 {
     $result = [];
     foreach ($this->fields as $field) {
         $result[$field] = $this->accessor->getValue($item, $field);
     }
     return $result;
 }
コード例 #13
0
 function it_should_not_add_violation_if_stock_is_sufficient(PropertyAccessor $propertyAccessor, InventoryUnitInterface $inventoryUnit, StockableInterface $stockable, AvailabilityCheckerInterface $availabilityChecker)
 {
     $propertyAccessor->getValue($inventoryUnit, 'stockable')->willReturn($stockable);
     $propertyAccessor->getValue($inventoryUnit, 'quantity')->willReturn(1);
     $availabilityChecker->isStockSufficient($stockable, 1)->willReturn(true);
     $constraint = new InStock();
     $this->validate($inventoryUnit, $constraint);
 }
コード例 #14
0
 /**
  * {@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;
 }
コード例 #15
0
 /**
  * {@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();
 }
コード例 #16
0
ファイル: FileExtensionFilter.php プロジェクト: cocur/plum
 /**
  * @param mixed $item
  *
  * @return bool
  */
 public function filter($item)
 {
     $filename = $this->property === null ? $item : $this->accessor->getValue($item, $this->property);
     foreach ($this->extensions as $extension) {
         if (preg_match(sprintf('/\\.%s/', $extension), $filename) === 1) {
             return true;
         }
     }
     return false;
 }
コード例 #17
0
ファイル: Originator.php プロジェクト: Strontium-90/Sylius
 /**
  * {@inheritdoc}
  */
 public function setOrigin(OriginAwareInterface $originAware, $origin)
 {
     if (!is_object($origin)) {
         throw new UnexpectedTypeException($origin, 'object');
     }
     if (null === ($id = $this->accessor->getValue($origin, $this->identifier))) {
         throw new \InvalidArgumentException(sprintf('Origin %s is not set.', $this->identifier));
     }
     $originAware->setOriginId($id)->setOriginType(get_class($origin));
 }
コード例 #18
0
ファイル: JsonValidator.php プロジェクト: hogosha/monitor
 /**
  * {@inheritdoc}
  */
 public function check($value, $match)
 {
     $accessor = new PropertyAccessor();
     try {
         $json = $this->decode($value);
         $accessor->getValue($json, $match);
     } catch (RuntimeException $e) {
         throw new ValidatorException($e->getMessage());
     }
 }
コード例 #19
0
 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);
     }
 }
コード例 #20
0
 /**
  * @inheritdoc
  */
 public function resolve($func)
 {
     if (!is_string($func)) {
         return null;
     }
     $propertyPath = new PropertyPath($func);
     return function ($item) use($propertyPath) {
         return $this->propertyAccessor->getValue($item, $propertyPath);
     };
 }
コード例 #21
0
 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);
     }
 }
コード例 #22
0
 protected function transformSingleEntity($data)
 {
     if (!$this->unitOfWork->isInIdentityMap($data)) {
         throw new RuntimeException('Entities passed to the choice field must be managed');
     }
     if ($this->property) {
         $propertyAccessor = new PropertyAccessor();
         return $propertyAccessor->getValue($data, $this->property);
     }
     return current($this->unitOfWork->getEntityIdentifier($data));
 }
コード例 #23
0
 /**
  * @param object $object
  *
  * @return array
  */
 public function getEntityContactData($object)
 {
     $activityContactConfigs = $this->getEntityActivityContactFields($object);
     return array_reduce($activityContactConfigs, function ($carry, ConfigInterface $item) use($object) {
         /** @var FieldConfigId $fieldConfigId */
         $fieldConfigId = $item->getId();
         $fieldName = $fieldConfigId->getFieldName();
         $carry[$fieldName] = $this->propertyAccessor->getValue($object, $fieldName);
         return $carry;
     }, []);
 }
コード例 #24
0
 /**
  * @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);
 }
コード例 #25
0
 /**
  * {@inheritdoc}
  */
 public function process(&$item)
 {
     $accessor = new PropertyAccessor();
     foreach ($this->converters as $property => $converters) {
         foreach ($converters as $converter) {
             $orgValue = $accessor->getValue($item, $property);
             $value = call_user_func($converter, $orgValue);
             $accessor->setValue($item, $property, $value);
         }
     }
     return true;
 }
コード例 #26
0
 /**
  * {@inheritdoc}
  */
 public function buildResponse(AutocompleteResults $results, AutocompleteContextInterface $context)
 {
     $array = [];
     $property = $context->getParameter('autocomplete');
     $accessor = new PropertyAccessor();
     foreach ($results as $id => $result) {
         if ($accessor->isReadable($result, $property)) {
             $array[] = $accessor->getValue($result, $property);
         }
     }
     return new JsonResponse($array);
 }
コード例 #27
0
 /**
  * Transforms Entity to Entity,Label pair
  * @param $entity
  * @return array
  * @throws TransformationFailedException
  */
 public function transform($entity)
 {
     if (null === $entity) {
         return array('storage' => null, 'helper' => '');
     }
     $class = $this->class;
     if (!$entity instanceof $class) {
         throw new TransformationFailedException('Transformed entity is not instanse of ' . $this->class);
     }
     $accessor = new PropertyAccessor();
     return array('storage' => $entity, 'helper' => $accessor->getValue($entity, $this->path));
 }
コード例 #28
0
 /**
  * @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);
     }
 }
コード例 #29
0
 /**
  * @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);
             }
         }
     }
 }
コード例 #30
0
 /**
  * {@inheritdoc}
  */
 public function validate($object, $property)
 {
     $this->validators = $this->fixValidators($this->validators);
     $errors = array();
     $value = $this->propertyAccessor->getValue($object, $property);
     foreach ($this->validators as $validator) {
         $validatorErrors = $validator->validate($value);
         if ($validatorErrors) {
             $errors = array_merge($validatorErrors, $errors);
         }
     }
     return $errors;
 }