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; }
/** * @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); } }
/** * @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; }
/** * @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)); } } }
/** * {@inheritdoc} */ public function transform($value) { if (null === $value) { return null; } if (!is_array($value) && !$value instanceof \Traversable) { throw new UnexpectedTypeException($value, 'array or Traversable'); } $result = [LocalizedFallbackValueCollectionType::FIELD_VALUES => [], LocalizedFallbackValueCollectionType::FIELD_IDS => []]; foreach ($value as $localizedFallbackValue) { /** @var LocalizedFallbackValue $localizedFallbackValue */ $locale = $localizedFallbackValue->getLocale(); if ($locale) { $key = $locale->getId(); } else { $key = 0; } $fallback = $localizedFallbackValue->getFallback(); if ($fallback) { $value = new FallbackType($fallback); } else { $value = $this->propertyAccessor->getValue($localizedFallbackValue, $this->field); } $result[LocalizedFallbackValueCollectionType::FIELD_VALUES][$key ?: null] = $value; $result[LocalizedFallbackValueCollectionType::FIELD_IDS][$key] = $localizedFallbackValue->getId(); } return $result; }
/** * @param AttributeDefaultValue|null $defaultValue * @param string $field * @return mixed */ protected function getDefaultValueByField($defaultValue, $field) { if ($defaultValue) { return $this->propertyAccessor->getValue($defaultValue, $field); } else { return null; } }
/** * {@inheritdoc} */ public function convertItem($item) { $result = []; foreach ($this->fields as $field) { $result[$field] = $this->accessor->getValue($item, $field); } return $result; }
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); }
/** * 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; }
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; }
/** * @inheritdoc */ public function transform($value) { if (null === $value) { return []; } $text = is_null($this->property) ? (string) $value : $this->propertyAccessor->getValue($value, $this->property); $identifier = $this->propertyAccessor->getValue($value, $this->metadata->getIdentifier()[0]); return [$identifier ?: $text => $text]; }
/** * {@inheritdoc} */ public function &get(&$node, $singlePath) { if (!$singlePath || !$this->isReadable($node, $singlePath)) { throw new InvalidPathException(sprintf('Path %s is not readable', $singlePath)); } // Only variables may be returned as reference $value = $this->propertyAccess->getValue($node, $singlePath); return $value; }
/** * @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); }; }
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 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; }
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); } }
/** * {@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)); }
/** * @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; }, []); }
/** * @inheritdoc */ public function transform($value) { if (is_null($value) || count($value) === 0) { return array(); } $data = array(); foreach ($value as $item) { $text = is_null($this->property) ? (string) $item : $this->propertyAccessor->getValue($item, $this->property); $identifier = $this->propertyAccessor->getValue($item, $this->metadata->getIdentifier()[0]); $data[$identifier ?: $text] = $text; } return $data; }
/** * {@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; }
/** * {@inheritdoc} */ public function __invoke($input) { if (!is_object($input)) { throw new UnexpectedTypeException($input, 'object'); } if (null === $this->propertyPath && !method_exists($input, '__toString')) { throw new \RuntimeException(); } if (null === $this->propertyPath) { return (string) $input; } $path = new PropertyPath($this->propertyPath); return $this->propertyAccessor->getValue($input, $path); }
/** * @param $entity */ private function persistAllAssociations($entity) { $meta = $this->em->getClassMetadata(get_class($entity)); foreach ($meta->getAssociationMappings() as $mapping) { $child = $this->accessor->getValue($entity, $mapping['fieldName']); if (null === $child) { continue; } if ($this->isCollection($mapping)) { $this->persistCollection($child); } else { $this->persistEntity($child); } } }
/** * {@inheritdoc} */ public function buildColumn(ColumnInterface $column, array $options) { $dataProvider = $options['data_provider']; $parentDataProvider = $options['parent_data_provider']; if (!$dataProvider instanceof \Closure) { $dataProvider = $parentDataProvider ?: function ($data) use($column, $dataProvider) { static $path; if (null === $path) { $path = $this->createDataProviderPath($column, $data, $dataProvider); } return $this->propertyAccessor->getValue($data, $path); }; } $column->setDataProvider($dataProvider); }
/** * {@inheritdoc} */ public function resolveParameter($name, $object) { $class = get_class($object); switch (true) { case isset($this->mapping[$class][$name]): $path = $this->mapping[$class][$name]; break; case isset($this->mapping[$class]['_fallback']): $path = $this->mapping[$class]['_fallback']; break; default: $path = $name; } return (string) $this->propertyAccessor->getValue($object, $path); }
/** * @param Collection $collection * @param ConfigIdInterface $fieldConfig * * @return array */ protected function getValueForCollection(Collection $collection, ConfigIdInterface $fieldConfig) { $extendConfig = $this->extendProvider->getConfigById($fieldConfig); $titleFieldName = $extendConfig->get('target_title'); $value = $this->getEntityRouteOptions($extendConfig->get('target_entity')); $values = []; $priorities = []; /** @var object $item */ foreach ($collection as $item) { $value['route_params']['id'] = $item->getId(); $title = []; foreach ($titleFieldName as $fieldName) { $title[] = $this->propertyAccessor->getValue($item, $fieldName); } $values[] = ['id' => $item->getId(), 'link' => $value['route'] ? $this->router->generate($value['route'], $value['route_params']) : false, 'title' => implode(' ', $title)]; if ($item instanceof PriorityItem) { $priorities[] = $item->getPriority(); } } // sort values by priority if needed if (!empty($priorities) && count($priorities) === count($values)) { array_multisort($priorities, $values); } $value['values'] = $values; return $value; }
protected function getRowSpecialParams($row, $isAjax = true) { $params = array(); $attr = $this->options['row_attr']; // Id parameter: if (isset($attr['id']) && $attr['id'] !== null) { $paramName = $isAjax ? 'DT_RowId' : 'id'; try { $params[$paramName] = $this->name . '_row_' . $this->propertyAccessor->getValue($row, $attr['id']); } catch (\Exception $e) { unset($params[$paramName], $attr['id']); } } // Class parameter: if (isset($attr['class']) && $attr['class'] !== null) { $paramName = $isAjax ? 'DT_RowClass' : 'class'; $params[$paramName] = (string) $attr['class']; unset($attr['class']); } // Add custom attributes to row: if (is_array($attr)) { foreach ($attr as $name => $value) { if (is_callable($value)) { $params['_rowAttr'][$name] = $value($row); } else { $params['_rowAttr'][$name] = $value; } } } if ($isAjax) { $params['_isAjax'] = true; } return $params; }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { /** @var InStock $constraint */ Assert::isInstanceOf($constraint, InStock::class); $stockable = $this->accessor->getValue($value, $constraint->stockablePath); if (null === $stockable) { return; } $quantity = $this->accessor->getValue($value, $constraint->quantityPath); if (null === $quantity) { return; } if (!$this->availabilityChecker->isStockSufficient($stockable, $quantity)) { $this->context->addViolation($constraint->message, ['%stockable%' => $stockable->getInventoryName()]); } }
/** * {@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())); }
/** * {@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); }
/** * {@inheritdoc} */ public function getValue($objectOrArray, $propertyPath) { try { return parent::getValue($objectOrArray, $propertyPath); } catch (Exception\NoSuchPropertyException $e) { $tags = array(); if (!$objectOrArray instanceof ProductInterface) { return $tags; } $propertyPath = strtolower((string) $propertyPath); foreach ($objectOrArray->getAvailableVariants() as $variant) { foreach ($variant->getOptions() as $option) { if ($propertyPath === strtolower($option->getPresentation())) { $tags[] = $option->getValue(); } } } foreach ($objectOrArray->getAttributes() as $attribute) { if ($propertyPath === strtolower(str_replace(' ', '_', $attribute->getPresentation()))) { $tags[] = $attribute->getValue(); } } return array_values(array_unique($tags)); } }