code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function readAction(Request $request, DataInterface $data, FamilyInterface $family = null) { $this->initDataFamily($data, $family); $form = $this->getForm($request, $data, ['disabled' => true]); return $this->renderAction($this->getViewParameters($request, $form, $data)); }
@Security("is_granted('read', data)") @param Request $request @param DataInterface $data @param FamilyInterface $family @throws \Exception @return Response
public function editAction(Request $request, DataInterface $data, FamilyInterface $family = null) { $this->initDataFamily($data, $family); $form = $this->getForm($request, $data, $family->getFormOptions()); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->saveEntity($data); $parameters = $request->query->all(); $parameters['success'] = 1; return $this->redirectToEntity($data, 'edit', $parameters); } return $this->renderAction($this->getViewParameters($request, $form, $data)); }
@Security("is_granted('edit', data)") @param Request $request @param DataInterface $data @param FamilyInterface $family @throws \Exception @return Response
public function cloneAction(Request $request, DataInterface $data, FamilyInterface $family = null) { return $this->editAction($request, clone $data, $family); }
Dedicated permission for cloning ? @Security("(is_granted('create', family) and is_granted('read', data))") @param Request $request @param DataInterface $data @param FamilyInterface $family @throws \Exception @return Response
public function deleteAction(Request $request, DataInterface $data, FamilyInterface $family = null) { $this->initDataFamily($data, $family); $constrainedEntities = $this->get(IntegrityConstraintManager::class)->getEntityConstraints($data); $formOptions = $this->getDefaultFormOptions($request, $data->getId()); unset($formOptions['family'], $formOptions['fieldset_options']); $builder = $this->createFormBuilder(null, $formOptions); $form = $builder->getForm(); $dataId = $data->getId(); if (0 === \count($constrainedEntities)) { $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->deleteEntity($data); if ($request->isXmlHttpRequest()) { return $this->renderAction( array_merge( $this->getViewParameters($request, $form), [ 'dataId' => $dataId, 'success' => 1, ] ) ); } return $this->redirect($this->getAdminListPath()); } } return $this->renderAction( array_merge( $this->getViewParameters($request, $form, $data), [ 'dataId' => $dataId, 'constrainedEntities' => $constrainedEntities, ] ) ); }
@Security("is_granted('delete', data)") @param Request $request @param DataInterface $data @param FamilyInterface $family @throws \Exception @return Response
protected function getDataGridConfigCode(): string { if ($this->family) { // If datagrid code set in options, use it $familyCode = $this->family->getCode(); /* @noinspection UnSafeIsSetOverArrayInspection */ if (isset($this->admin->getOption('families')[$familyCode]['datagrid'])) { return $this->admin->getOption('families')[$familyCode]['datagrid']; } // Check if family has a datagrid with the same name if ($this->get(DataGridRegistry::class)->hasDataGrid($familyCode)) { return $familyCode; } // Check in lowercase (this should be deprecated ?) $code = strtolower($familyCode); if ($this->get(DataGridRegistry::class)->hasDataGrid($code)) { return $code; } } return parent::getDataGridConfigCode(); }
Resolve datagrid code. @throws \UnexpectedValueException @return string
protected function getDefaultFormOptions(Request $request, $dataId, Action $action = null): array { if (!$action) { $action = $this->admin->getCurrentAction(); } $formOptions = parent::getDefaultFormOptions($request, $dataId, $action); $formOptions['family'] = $this->family; $formOptions['label'] = $this->tryTranslate( [ "admin.family.{$this->family->getCode()}.{$action->getCode()}.title", "admin.{$this->admin->getCode()}.{$action->getCode()}.title", "admin.action.{$action->getCode()}.title", ], [], ucfirst($action->getCode()) ); return $formOptions; }
@param Request $request @param string $dataId @param Action|null $action @throws \InvalidArgumentException @return array
protected function getViewParameters(Request $request, Form $form = null, $data = null): array { $parameters = parent::getViewParameters($request, $form, $data); if ($this->family) { $parameters['family'] = $this->family; } return $parameters; }
@param Request $request @param Form $form @param DataInterface $data @throws \Exception @return array
protected function getAdminListPath($data = null, array $parameters = []): string { if ($this->family) { $parameters = array_merge(['familyCode' => $this->family->getCode()], $parameters); } return parent::getAdminListPath($data, $parameters); }
{@inheritdoc}
protected function saveEntity($data) { if ($data instanceof AbstractData) { $data->setUpdatedAt(new \DateTime()); } parent::saveEntity($data); }
@param DataInterface $data @throws \Exception
protected function getExportConfig(Request $request) { $configKey = $request->get('configKey'); if (!$configKey) { return []; } $session = $request->getSession(); $selectedIds = null; $selectedColumns = null; if ($session) { $selectedIds = $session->get('export_selected_ids_'.$configKey); $selectedColumns = $session->get('export_selected_columns_'.$configKey); } $attributes = []; if (\is_array($selectedColumns)) { /** @var array $selectedColumns */ foreach ($selectedColumns as $selectedColumn) { $attributes[$selectedColumn] = [ 'enabled' => true, ]; } } return [ 'selectedIds' => \is_array($selectedIds) ? implode('|', $selectedIds) : null, 'onlySelectedEntities' => (bool) $selectedIds, 'attributes' => $attributes, ]; }
@param Request $request @return array
protected function redirectToExport(DataGrid $dataGrid, SessionInterface $session) { $filterConfig = $dataGrid->getQueryHandler(); $selectedIds = []; if ($filterConfig instanceof DoctrineQueryHandlerInterface) { $alias = $filterConfig->getAlias(); $qb = $filterConfig->getQueryBuilder(); $qb->select($alias.'.id'); $selectedIds = []; foreach ($qb->getQuery()->getArrayResult() as $result) { $selectedIds[] = $result['id']; } } $selectedColumns = []; foreach ($dataGrid->getColumns() as $column) { $selectedColumns[] = $column->getPropertyPath(); } $configKey = uniqid('', false); $session->set('export_selected_ids_'.$configKey, $selectedIds); $session->set('export_selected_columns_'.$configKey, $selectedColumns); return $this->redirectToAction( 'export', [ 'familyCode' => $this->family->getCode(), 'configKey' => $configKey, ] ); }
@param DataGrid $dataGrid @param SessionInterface $session @throws \Exception @return \Symfony\Component\HttpFoundation\RedirectResponse
protected function normalizeRelation(DataInterface $entity, $serializedColumn, $value) { if (!$serializedColumn || !\is_array($value)) { return $value; } if (array_key_exists($serializedColumn, $value)) { return $value[$serializedColumn]; } if (null !== $value) { throw new \UnexpectedValueException( "Unknown serialized format for entity #{$entity->getId()}" ); } return $value; }
@param DataInterface $entity @param string $serializedColumn @param mixed $value @throws \UnexpectedValueException @return string
protected function execute(InputInterface $input, OutputInterface $output): ?int { $username = $this->getUsername($input, $output); if ($input->getOption('if-not-exists')) { try { $user = $this->userManager->loadUserByUsername($username); } catch (\Exception $e) { $user = null; } if ($user) { $message = $this->translator->trans( 'user.already_exists', [ '%username%' => $username, ], 'security' ); $output->writeln("<comment>{$message}</comment>"); return 0; } } try { $user = $this->userManager->createUser($username); } catch (BadUsernameException $e) { $output->writeln("<error>{$e->getMessage()}</error>"); return 1; } $user->setSuperAdmin($input->getOption('admin')); $password = $this->getPassword($input, $output); if ($password) { $this->userManager->setPlainTextPassword($user, $password); } $this->userManager->save($user); $message = $this->translator->trans('user.created_success', ['%username%' => $username], 'security'); $output->writeln("<info>{$message}</info>"); return 0; }
@param InputInterface $input @param OutputInterface $output @throws \Exception @return int|null
public function normalize($object, $format = null, array $context = []) { $resourceClass = $this->resourceClassResolver->getResourceClass( $object, $context['resource_class'] ?? null, true ); $context = $this->initContext($resourceClass, $context); $context['api_normalize'] = true; return $this->normalizer->normalize($object, $format, $context); }
{@inheritdoc} @throws \ApiPlatform\Core\Exception\InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\CircularReferenceException @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\LogicException
public function denormalize($data, $class, $format = null, array $context = []) { // Avoid issues with proxies if we populated the object if (isset($data['id']) && !isset($context['object_to_populate'])) { if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) { throw new InvalidArgumentException('Update is not allowed for this operation.'); } $this->updateObjectToPopulate($data, $context); } $context['api_denormalize'] = true; if (!isset($context['resource_class'])) { $context['resource_class'] = $class; } return $this->denormalizer->denormalize($data, $class, $format, $context); }
{@inheritdoc} @throws InvalidArgumentException @throws \ApiPlatform\Core\Exception\PropertyNotFoundException @throws \ApiPlatform\Core\Exception\ResourceClassNotFoundException @throws \Symfony\Component\Serializer\Exception\BadMethodCallException @throws \Symfony\Component\Serializer\Exception\ExtraAttributesException @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\LogicException @throws \Symfony\Component\Serializer\Exception\RuntimeException @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
public function supportsNormalization($data, $format = null) { return $this->normalizer && $this->normalizer->supportsNormalization($data, $format) && parent::supportsNormalization($data, $format); }
{@inheritdoc}
public function supportsDenormalization($data, $type, $format = null) { return $this->denormalizer && $this->denormalizer->supportsDenormalization($data, $type, $format) && parent::supportsDenormalization($data, $type, $format); }
{@inheritdoc}
protected function updateObjectToPopulate(array $data, array &$context) { try { $context['object_to_populate'] = $this->iriConverter->getItemFromIri( (string) $data['id'], $context + ['fetch_data' => false] ); } catch (InvalidArgumentException $e) { $identifier = null; $properties = $this->propertyNameCollectionFactory->create($context['resource_class'], $context); foreach ($properties as $propertyName) { if ($this->propertyMetadataFactory->create($context['resource_class'], $propertyName)->isIdentifier()) { $identifier = $propertyName; break; } } if (null === $identifier) { throw $e; } $context['object_to_populate'] = $this->iriConverter->getItemFromIri( sprintf( '%s/%s', $this->iriConverter->getIriFromResourceClass($context['resource_class']), $data[$identifier] ), $context + ['fetch_data' => false] ); } }
@param array $data @param array $context @throws \ApiPlatform\Core\Exception\InvalidArgumentException @throws \ApiPlatform\Core\Exception\PropertyNotFoundException @throws \ApiPlatform\Core\Exception\ResourceClassNotFoundException
public function hasPermission($permission): bool { if (!\in_array($permission, $this::$permissions, true)) { throw new \UnexpectedValueException("Permissions does not exists: {$permission}"); } $accessor = PropertyAccess::createPropertyAccessor(); return $accessor->getValue($this, $permission); }
@param string $permission @return bool @throws \Exception
public function setUser(User $user = null): FamilyPermission { $this->user = $user; if ($user && !$user->getFamilyPermissions()->contains($this)) { $user->getFamilyPermissions()->add($this); } return $this; }
@param User $user @return FamilyPermission
public function setGroup(Group $group = null): FamilyPermission { $this->group = $group; if ($group && !$group->getFamilyPermissions()->contains($this)) { $group->getFamilyPermissions()->add($this); } return $this; }
@param Group $group @return FamilyPermission
public function setFamily(FamilyInterface $family = null): FamilyPermission { $this->familyCode = $family ? $family->getCode() : null; return $this; }
@param FamilyInterface $family @return FamilyPermission
public function load(array $configs, ContainerBuilder $container) { $configuration = $this->createConfiguration(); $this->globalConfig = $this->processConfiguration($configuration, $configs); $container->setParameter($this->rootAlias.'.configuration', $this->globalConfig); parent::load($configs, $container); }
{@inheritdoc} @throws BadMethodCallException @throws \Exception
public function execute(ProcessState $state) { $entity = $state->getInput(); if (!$entity instanceof DataInterface) { throw new \UnexpectedValueException('Expecting a DataInterface as input'); } $family = $entity->getFamily(); $options = $this->getOptions($state); if (!$family->hasAttribute($options['attribute'])) { throw new MissingAttributeException($options['attribute']); } /** @var EntityManager $em */ $em = $this->doctrine->getManager(); $attribute = $family->getAttribute($options['attribute']); $entity->set($attribute->getCode(), $options['value']); // Set actual value $valueEntity = $entity->getValue($attribute); // Get value "entity" with updated value $em->persist($valueEntity); // Persist if new $em->flush($valueEntity); // Flush value ONLY }
@param ProcessState $state @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface @throws \InvalidArgumentException @throws \Sidus\EAVModelBundle\Exception\MissingAttributeException @throws \Doctrine\ORM\OptimisticLockException @throws \Doctrine\ORM\ORMInvalidArgumentException @throws \Sidus\EAVModelBundle\Exception\InvalidValueDataException @throws \Sidus\EAVModelBundle\Exception\ContextException @throws \Doctrine\ORM\ORMException
public function listAction(Request $request) { $dataGrid = $this->getDataGrid(); $this->bindDataGridRequest($dataGrid, $request); return $this->renderAction( array_merge( $this->getViewParameters($request), ['datagrid' => $dataGrid] ) ); }
@param Request $request @throws \Exception @return Response
public function createAction(Request $request) { $class = $this->admin->getEntity(); $data = new $class(); return $this->editAction($request, $data); }
@param Request $request @throws \Exception @return Response
public function editAction(Request $request, $data = null) { if (null === $data) { $data = $this->getDataFromRequest($request); } $form = $this->getForm($request, $data); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->saveEntity($data); $parameters = $request->query->all(); $parameters['success'] = 1; return $this->redirectToEntity($data, 'edit', $parameters); } return $this->renderAction($this->getViewParameters($request, $form, $data)); }
@param Request $request @param mixed $data @throws \Exception @return Response
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root($this->root); $rootNode ->children() ->scalarNode('home_route')->defaultValue('eavmanager_layout.dashboard')->end() ->append($this->getMailerConfigurationTreeBuilder()) ->end(); return $treeBuilder; }
{@inheritdoc} @throws \RuntimeException
protected function getMailerConfigurationTreeBuilder() { $builder = new TreeBuilder(); $node = $builder->root('mailer'); $node ->children() ->scalarNode('company')->end() ->scalarNode('from_email')->end() ->scalarNode('from_name')->end() ->end(); return $node; }
@return NodeDefinition @throws \RuntimeException
protected function filterAttribute( EAVQueryBuilderInterface $eavQb, AttributeQueryBuilderInterface $attributeQueryBuilder, $value, $strategy = null, string $operationName = null ) { $dqlHandlers = []; if (isset($value[BaseRangeFilter::PARAMETER_BETWEEN])) { list($lower, $upper) = explode('..', $value[BaseRangeFilter::PARAMETER_BETWEEN]); return $attributeQueryBuilder->between($lower, $upper); } if (isset($value[BaseRangeFilter::PARAMETER_LESS_THAN])) { $dqlHandlers[] = $attributeQueryBuilder->lt($value[BaseRangeFilter::PARAMETER_LESS_THAN]); } if (isset($value[BaseRangeFilter::PARAMETER_LESS_THAN_OR_EQUAL])) { $dqlHandlers[] = $attributeQueryBuilder->lte($value[BaseRangeFilter::PARAMETER_LESS_THAN_OR_EQUAL]); } if (isset($value[BaseRangeFilter::PARAMETER_GREATER_THAN])) { $dqlHandlers[] = $attributeQueryBuilder->gt($value[BaseRangeFilter::PARAMETER_GREATER_THAN]); } if (isset($value[BaseRangeFilter::PARAMETER_GREATER_THAN_OR_EQUAL])) { $dqlHandlers[] = $attributeQueryBuilder->gte($value[BaseRangeFilter::PARAMETER_GREATER_THAN_OR_EQUAL]); } return $eavQb->getAnd($dqlHandlers); }
{@inheritdoc}
public function selectDataAction(Request $request, $configName) { $formOptions = []; $selectorConfig = $this->getParameter('cleverage_eavmanager.configuration')['wysiwyg']; if (array_key_exists($configName, $selectorConfig)) { $formOptions = $selectorConfig[$configName]; } $formData = [ 'data' => $this->getData($request), ]; $builder = $this->createFormBuilder( $formData, [ 'show_legend' => false, ] ); $builder->add('data', ComboDataSelectorType::class, $formOptions); $form = $builder->getForm(); $form->handleRequest($request); return $this->render( 'CleverAgeEAVManagerAdminBundle:Wysiwyg:select'.ucfirst($configName).'.html.twig', ['form' => $form->createView()] ); }
@param Request $request @param string $configName @throws \InvalidArgumentException @return Response
public function selectMediaAction(Request $request) { $formData = [ 'data' => $this->getData($request), 'filter' => $request->get('dataFilter'), 'responsive' => '1' === (string) $request->get('dataResponsive'), ]; $builder = $this->createFormBuilder( $formData, [ 'show_legend' => false, ] ); $builder->add( 'data', MediaBrowserType::class, [ 'allowed_families' => ['Image'], ] ); $filterConfig = $this->get('liip_imagine.filter.manager')->getFilterConfiguration()->all(); $choices = array_combine(array_keys($filterConfig), array_keys($filterConfig)); $builder->add( 'filter', ChoiceType::class, [ 'choices' => $choices, ] ); $builder->add( 'responsive', SwitchType::class, [ 'label' => 'Responsive', 'required' => false, ] ); $form = $builder->getForm(); $form->handleRequest($request); return [ 'form' => $form->createView(), ]; }
@Template("@CleverAgeEAVManagerAdmin/Wysiwyg/selectMedia.html.twig") @param Request $request @throws \Exception @return array
protected function getData(Request $request) { $data = null; if ($request->query->has('dataId')) { $data = $this->get(DataRepository::class)->find($request->query->get('dataId')); } return $data; }
@param Request $request @throws \InvalidArgumentException @return DataInterface|null
public function sendNewUserMail(User $user) { $parameters = [ 'user' => $user, 'subject' => $this->translator->trans('user.account_creation', [], 'security'), 'company' => $this->configuration->getMailerCompany(), ]; $text = $this->twig->render('CleverAgeEAVManagerUserBundle:Email:newUser.txt.twig', $parameters); $html = $this->twig->render('CleverAgeEAVManagerUserBundle:Email:newUser.html.twig', $parameters); $message = $this->createMessage(); $message->setSubject($parameters['subject']); $message->setTo([$user->getEmail()]); $message->setBody($text); $message->addPart($html, 'text/html'); $this->mailer->send($message); }
@param User $user @throws \Twig_Error_Loader @throws \Twig_Error_Runtime @throws \Twig_Error_Syntax @throws \Symfony\Component\Translation\Exception\InvalidArgumentException
public function normalize($object, $format = null, array $context = []) { // Do the same for 'by_reference' ? if ($this->iriConverter && $this->byReferenceHandler->isByShortReference($context) ) { return $this->iriConverter->getIriFromItem($object); } return parent::normalize($object, $format, $context); }
Normalizes an object into a set of arrays/scalars. @param DataInterface $object object to normalize @param string $format format the normalization result will be encoded as @param array $context Context options for the normalizer @throws InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\RuntimeException @throws \Symfony\Component\PropertyAccess\Exception\ExceptionInterface @throws \Sidus\EAVModelBundle\Exception\EAVExceptionInterface @throws \Sidus\EAVModelBundle\Exception\InvalidValueDataException @throws \Symfony\Component\Serializer\Exception\CircularReferenceException @throws \ApiPlatform\Core\Exception\RuntimeException @throws \ApiPlatform\Core\Exception\InvalidArgumentException @return array
protected function getAttributeValue( DataInterface $object, $attribute, $format = null, array $context = [] ) { $rawValue = $this->propertyAccessor->getValue($object, $attribute); if (!\is_array($rawValue) && !$rawValue instanceof \Traversable) { $subContext = $this->getAttributeContext($object, $attribute, $rawValue, $context); return $this->normalizer->normalize($rawValue, $format, $subContext); } $collection = []; /** @var array $rawValue */ foreach ($rawValue as $item) { $subContext = $this->getAttributeContext($object, $attribute, $item, $context); $collection[] = $this->normalizer->normalize($item, $format, $subContext); } return $collection; }
We must override this method because we cannot expect the normalizer to work normally with collection with the API Platform framework. @param DataInterface $object @param string $attribute @param string $format @param array $context @throws \Symfony\Component\PropertyAccess\Exception\ExceptionInterface @throws \Symfony\Component\Serializer\Exception\LogicException @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\CircularReferenceException @return mixed
protected function getEAVAttributeValue( DataInterface $object, AttributeInterface $attribute, $format = null, array $context = [] ) { $rawValue = $object->get($attribute->getCode()); if (!\is_array($rawValue) && !$rawValue instanceof \Traversable) { $subContext = $this->getEAVAttributeContext($object, $attribute, $rawValue, $context); return $this->normalizer->normalize($rawValue, $format, $subContext); } $collection = []; /** @var array $rawValue */ foreach ($rawValue as $item) { $subContext = $this->getEAVAttributeContext($object, $attribute, $item, $context); $collection[] = $this->normalizer->normalize($item, $format, $subContext); } return $collection; }
We must override this method because we cannot expect the normalizer to work normally with collection with the API Platform framework. @param DataInterface $object @param AttributeInterface $attribute @param string $format @param array $context @throws EAVExceptionInterface @throws \Sidus\EAVModelBundle\Exception\MissingAttributeException @throws \Sidus\EAVModelBundle\Exception\InvalidValueDataException @throws \Sidus\EAVModelBundle\Exception\ContextException @throws \Symfony\Component\Serializer\Exception\LogicException @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException @throws \Symfony\Component\Serializer\Exception\CircularReferenceException @return mixed
protected function getAttributeContext( DataInterface $object, $attribute, /* @noinspection PhpUnusedParameterInspection */ $rawValue, array $context ) { $resolvedContext = parent::getAttributeContext($object, $attribute, $rawValue, $context); if (!\is_object($rawValue)) { return $resolvedContext; } $resolvedContext['resource_class'] = ClassUtils::getClass($rawValue); unset($resolvedContext['item_operation_name'], $resolvedContext['collection_operation_name']); return $resolvedContext; }
@param DataInterface $object @param string $attribute @param mixed $rawValue @param array $context @return array
protected function getEAVAttributeContext( DataInterface $object, AttributeInterface $attribute, /* @noinspection PhpUnusedParameterInspection */ $rawValue, array $context ) { $resolvedContext = parent::getEAVAttributeContext($object, $attribute, $rawValue, $context); if (!\is_object($rawValue)) { return $resolvedContext; } $resolvedContext['resource_class'] = ClassUtils::getClass($rawValue); unset($resolvedContext['item_operation_name'], $resolvedContext['collection_operation_name']); return $resolvedContext; }
@param DataInterface $object @param AttributeInterface $attribute @param mixed $rawValue @param array $context @return array
protected function configureOptions(OptionsResolver $resolver) { $resolver->setRequired( [ 'family', ] ); /** @noinspection PhpUnusedParameterInspection */ $resolver->setNormalizer( 'family', function (Options $options, $value) { if ($value instanceof FamilyInterface) { return $value; } return $this->familyRegistry->getFamily($value); } ); $resolver->setAllowedTypes('family', ['string', FamilyInterface::class]); }
{@inheritDoc} @throws \Sidus\EAVModelBundle\Exception\MissingFamilyException
protected function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults( [ 'criteria' => [], 'extended_criteria' => [], 'repository' => null, 'order_by' => [], 'limit' => null, 'offset' => null, ] ); $resolver->setNormalizer( 'repository', function (Options $options, $value) { if ($value instanceof DataRepository) { return $value; } /** @var FamilyInterface $family */ $family = $options['family']; return $this->entityManager->getRepository($family->getDataClass()); } ); $resolver->setAllowedTypes('criteria', ['array']); $resolver->setAllowedTypes('extended_criteria', ['array']); $resolver->setAllowedTypes('repository', ['NULL', DataRepository::class]); $resolver->setAllowedTypes('order_by', ['array']); $resolver->setAllowedTypes('limit', ['NULL', 'integer']); $resolver->setAllowedTypes('offset', ['NULL', 'integer']); }
{@inheritDoc}
protected function getQueryBuilder(ProcessState $state, $alias = 'e') { $options = $this->getOptions($state); $criteria = $options['extended_criteria']; foreach ($options['criteria'] as $key => $value) { $criteria[] = [ $key, \is_array($value) ? 'in' : '=', $value, ]; } $qb = $this->eavFinder->getFilterByQb($options['family'], $criteria, $options['order_by'], $alias); $qb->distinct(); return $qb; }
@deprecated Use getPaginator instead because this method can't handle limit and offset properly @param ProcessState $state @param string $alias @throws \InvalidArgumentException @throws \UnexpectedValueException @throws \LogicException @throws \Sidus\EAVModelBundle\Exception\MissingAttributeException @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface @return QueryBuilder
protected function getPaginator(ProcessState $state, $alias = 'e') { $options = $this->getOptions($state); /** @noinspection PhpDeprecationInspection */ $paginator = new Paginator($this->getQueryBuilder($state, $alias)); if (null !== $options['limit']) { $paginator->getQuery()->setMaxResults($options['limit']); } if (null !== $options['offset']) { $paginator->getQuery()->setFirstResult($options['offset']); } return $paginator; }
If a limit or an offset is specified, we are forced to use a paginator to handle joins properly @param ProcessState $state @param string $alias @throws \InvalidArgumentException @throws \UnexpectedValueException @throws \Sidus\EAVModelBundle\Exception\MissingAttributeException @throws \LogicException @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface @return Paginator
public function getAdminForEntity($entity): Admin { $default = null; foreach ($this->adminRegistry->getAdmins() as $admin) { if (is_a($entity, $admin->getEntity())) { if ($entity instanceof DataInterface) { $default = $default ?: $admin; /** @var array $families */ $families = $admin->getOption('families', []); foreach ($families as $family => $config) { if ($entity->getFamilyCode() === $family) { return $admin; } } } else { return $admin; } } } if ($default) { // Or throw exception anyway ? return $default; } $class = \get_class($entity); throw new \UnexpectedValueException("No admin matching for entity {$class}"); }
@param mixed $entity @return Admin @throws \UnexpectedValueException
public function execute(ProcessState $state) { $options = $this->getOptions($state); if ($this->closed) { $logContext = $this->getLogContext($state); if ($options['allow_reset']) { $this->closed = false; $this->iterator = null; $this->logger->error('Reader was closed previously, restarting it', $logContext); } else { throw new \RuntimeException('Reader was closed previously, stopping the process'); } } if (null === $this->iterator) { $paginator = $this->getPaginator($state); $this->iterator = $paginator->getIterator(); // Log the data count if ($this->getOption($state, 'log_count')) { $count = \count($paginator); $logContext = $this->getLogContext($state); $this->logger->info("{$count} items found with current query", $logContext); } } // Handle empty results if (0 === $this->iterator->count()) { $logContext = $this->getLogContext($state); $this->logger->log($options['empty_log_level'], 'Empty resultset for query', $logContext); $state->setSkipped(true); return; } $state->setOutput($this->iterator->current()); }
{@inheritDoc} @throws \InvalidArgumentException @throws \Pagerfanta\Exception\NotIntegerCurrentPageException @throws \Pagerfanta\Exception\OutOfRangeCurrentPageException @throws \Pagerfanta\Exception\LessThan1CurrentPageException @throws \UnexpectedValueException @throws \Sidus\EAVModelBundle\Exception\MissingAttributeException @throws \LogicException @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface
public function next(ProcessState $state) { if (!$this->iterator instanceof \Iterator) { throw new \LogicException('No iterator initialized'); } $this->iterator->next(); $valid = $this->iterator->valid(); if (!$valid) { $this->closed = true; } return $valid; }
Moves the internal pointer to the next element, return true if the task has a next element return false if the task has terminated it's iteration @param ProcessState $state @throws \LogicException @return bool
protected function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults( [ 'allow_reset' => false, // Allow the reader to reset it's iterator 'log_count' => false, // Log in state history the result count 'empty_log_level' => LogLevel::WARNING, ] ); $resolver->setAllowedValues( 'empty_log_level', [ LogLevel::ALERT, LogLevel::CRITICAL, LogLevel::DEBUG, LogLevel::EMERGENCY, LogLevel::ERROR, LogLevel::INFO, LogLevel::NOTICE, LogLevel::WARNING, ] ); }
{@inheritDoc} @throws \Sidus\EAVModelBundle\Exception\MissingFamilyException
protected function getLogContext(ProcessState $state) { $logContext = $state->getLogContext(); $options = $this->getOptions($state); if (array_key_exists('family', $options)) { $options['family'] = $options['family']->getCode(); } if (array_key_exists('repository', $options)) { $options['repository'] = \get_class($options['repository']); } $logContext['options'] = $options; return $logContext; }
@param \CleverAge\ProcessBundle\Model\ProcessState $state @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface @return array
public function onKernelResponse(FilterResponseEvent $event) { if (!$event->getRequest()->attributes->has('_admin')) { return; } $admin = $event->getRequest()->attributes->get('_admin'); if (!$admin instanceof Admin) { throw new \UnexpectedValueException('_admin request attribute is not an Admin object'); } $resolver = new OptionsResolver(); $resolver->setDefaults( [ 'Cache-Control' => 'private, no-cache, no-store, must-revalidate', 'Pragma' => 'private', 'Expires' => 0, ] ); $headers = $resolver->resolve($admin->getOption('http_cache', [])); $event->getResponse()->headers->add($headers); }
@param FilterResponseEvent $event @throws \InvalidArgumentException @throws AccessException @throws \UnexpectedValueException @throws InvalidOptionsException @throws MissingOptionsException @throws NoSuchOptionException @throws OptionDefinitionException @throws UndefinedOptionsException
public function supportsNormalization($data, $format = null) { return self::FORMAT === $format && parent::supportsNormalization($data, $format); }
{@inheritdoc}
public function normalize($object, $format = null, array $context = []) { $resourceClass = $this->resourceClassResolver->getResourceClass( $object, $context['resource_class'] ?? null, true ); $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass); $data = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context); $rawData = parent::normalize($object, $format, $context); if (!\is_array($rawData)) { return $rawData; } $data['@id'] = $this->iriConverter->getIriFromItem($object); $data['@type'] = $resourceMetadata->getIri() ?: $resourceMetadata->getShortName(); return $data + $rawData; }
{@inheritdoc} @throws \ApiPlatform\Core\Exception\RuntimeException @throws InvalidArgumentException @throws \ApiPlatform\Core\Exception\ResourceClassNotFoundException
public function supportsDenormalization($data, $type, $format = null) { return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format); }
{@inheritdoc}
public function denormalize($data, $class, $format = null, array $context = []) { // Avoid issues with proxies if we populated the object if (isset($data['@id']) && !isset($context['object_to_populate'])) { if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) { throw new InvalidArgumentException('Update is not allowed for this operation.'); } $context['object_to_populate'] = $this->iriConverter->getItemFromIri( $data['@id'], $context + ['fetch_data' => true] ); } return parent::denormalize($data, $class, $format, $context); }
{@inheritdoc} @throws InvalidArgumentException
public function getImageSizeAttrs(Image $image, $filter) { $config = $this->liipFilterConfiguration->get($filter); $width = $image->getWidth(); $height = $image->getHeight(); if (isset($config['filters']['thumbnail'])) { list($width, $height) = $config['filters']['thumbnail']['size']; if ('inset' === $config['filters']['thumbnail']['mode']) { if ($image->getWidth() >= $image->getHeight()) { $height = floor($width / $image->getWidth() * $image->getHeight()); } if ($image->getWidth() <= $image->getHeight()) { $width = floor($height / $image->getHeight() * $image->getWidth()); } } } return strtr( 'width="%w%" height="%h%"', [ '%w%' => $width, '%h%' => $height, ] ); }
@param Image $image @param string $filter @return string @throws NonExistingFilterException
public function setParent(LeafRole $parent = null) { if ($parent && !$parent->getChildren()->contains($this)) { $parent->addChild($this); } $this->parent = $parent; return $this; }
@param LeafRole $parent @return LeafRole
public function addChild(LeafRole $child) { $this->children->add($child); $child->setParent($this); return $this; }
@param LeafRole $child @return LeafRole
public function removeChild(LeafRole $child) { $this->children->remove($child); $child->setParent(null); return $this; }
@param LeafRole $child @return LeafRole
public function setChildren($children) { $this->clearChildren(); foreach ($children as $child) { $this->addChild($child); } return $this; }
@param Collection|LeafRole[] $children @return LeafRole
protected function filterAttribute( EAVQueryBuilderInterface $eavQb, AttributeQueryBuilderInterface $attributeQueryBuilder, $value, $strategy = null, string $operationName = null ) { $dqlHandlers = []; if (BaseDateFilter::EXCLUDE_NULL === $strategy) { $dqlHandlers[] = $attributeQueryBuilder->isNotNull(); } if (isset($value[BaseDateFilter::PARAMETER_BEFORE])) { $handler = $attributeQueryBuilder->lte($value[BaseDateFilter::PARAMETER_BEFORE]); if (BaseDateFilter::INCLUDE_NULL_BEFORE === $strategy) { $eavQb->getOr( [ $handler, $attributeQueryBuilder->isNull(), ] ); } $dqlHandlers[] = $handler; } if (isset($values[BaseDateFilter::PARAMETER_AFTER])) { $handler = $attributeQueryBuilder->gte($value[BaseDateFilter::PARAMETER_AFTER]); if (BaseDateFilter::INCLUDE_NULL_AFTER === $strategy) { $eavQb->getOr( [ $handler, $attributeQueryBuilder->isNull(), ] ); } $dqlHandlers[] = $handler; } return $eavQb->getAnd($dqlHandlers); }
{@inheritdoc}
public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setRequired( [ 'attribute', ] ); $resolver->setAllowedTypes('attribute', ['string', AttributeInterface::class]); $resolver->setNormalizer( 'attribute', function (Options $options, $value) { /** @var FamilyInterface $family */ $family = $options['family']; if ($value instanceof AttributeInterface) { if (!$family->hasAttribute($value->getCode())) { throw new \UnexpectedValueException( "Family {$family->getCode()} has no attribute named {$value->getCode()}" ); } return $value; } return $family->getAttribute($value); } ); }
@param OptionsResolver $resolver @throws \Exception
protected function findData($value, array $options) { /** @var FamilyInterface $family */ $family = $options['family']; /** @var AttributeInterface $attribute */ $attribute = $options['attribute']; /** @var DataRepository $repository */ $repository = $options['repository']; $data = $repository->findByUniqueAttribute($family, $attribute, $value); if (null === $data && !$options['ignore_missing']) { $msg = "Missing entity for family {$family->getCode()} and"; $msg .= " attribute {$attribute->getCode()} with value '{$value}'"; throw new \UnexpectedValueException($msg); } return $data; }
@param string|int $value @param array $options @throws \Exception @return \Sidus\EAVModelBundle\Entity\DataInterface
public function getCollection(string $resourceClass, string $operationName = null) { if (!is_a($resourceClass, FamilyInterface::class, true)) { throw new ResourceClassNotSupportedException(); } return $this->familyRegistry->getFamilies(); }
Retrieves a collection. @param string $resourceClass @param string|null $operationName @throws ResourceClassNotSupportedException @return FamilyInterface[]|PaginatorInterface|\Traversable
public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []) { if (!is_a($resourceClass, FamilyInterface::class, true)) { throw new ResourceClassNotSupportedException(); } return $this->familyRegistry->getFamily($id); }
Retrieves an item. @param string $resourceClass @param int|string $id @param string|null $operationName @param array $context @throws ResourceClassNotSupportedException @throws \Sidus\EAVModelBundle\Exception\MissingFamilyException @return FamilyInterface|null
public function getFamily(string $resourceClass): FamilyInterface { $matchingFamilies = $this->getFamilies($resourceClass); if (1 === \count($matchingFamilies)) { return reset($matchingFamilies); } throw new \LogicException("Cannot resolve family for class '{$resourceClass}'"); }
@param string $resourceClass @throws \LogicException @return FamilyInterface
public function getFamilies(string $resourceClass): array { $matchingFamilies = []; foreach ($this->familyRegistry->getFamilies() as $family) { if (ltrim($family->getDataClass(), '\\') === ltrim($resourceClass, '\\')) { $matchingFamilies[] = $family; } } return $matchingFamilies; }
@param string $resourceClass @return FamilyInterface[]
public function vote(TokenInterface $token, $object, array $attributes) { $result = VoterInterface::ACCESS_ABSTAIN; if (!$this->supportsClass($object)) { return $result; } if (VoterInterface::ACCESS_GRANTED === $this->roleHierarchyVoter->vote($token, null, ['ROLE_USER_MANAGER'])) { return VoterInterface::ACCESS_GRANTED; } return $result; }
{@inheritdoc} @throws \Exception
public function getTypeOf($entity, $full = false): string { if ($entity instanceof DataInterface) { if ($full) { return (string) $entity->getFamilyCode(); } return (string) $entity->getFamily(); } $refl = new \ReflectionClass($entity); if ($full) { $refl->getName(); } return $refl->getShortName(); }
@param object $entity @param bool $full @throws \ReflectionException @return string
public function getRoles() { $roles = $this->roles; foreach ($this->getGroups() as $group) { /** @noinspection SlowArrayOperationsInLoopInspection */ $roles = array_merge($roles, $group->getRoles()); } // we need to make sure to have at least one role $roles[] = static::ROLE_DEFAULT; return array_unique($roles); }
Returns the user roles. @return array The roles
public function addRole($role) { $role = strtoupper($role); if (static::ROLE_DEFAULT === $role) { return $this; } if (!$this->hasRole($role)) { $this->roles[] = $role; } return $this; }
@param string $role @return User
public function removeRole($role) { $key = array_search(strtoupper($role), $this->roles, true); if (false !== $key) { /** @var string $key */ unset($this->roles[$key]); $this->roles = array_values($this->roles); } return $this; }
@param string $role @return $this
public function setSuperAdmin($boolean) { if (true === $boolean) { $this->addRole(static::ROLE_SUPER_ADMIN); } else { $this->removeRole(static::ROLE_SUPER_ADMIN); } return $this; }
@param bool $boolean @return $this
public function removeFamilyPermission(FamilyPermission $familyPermission) { $this->familyPermissions->removeElement($familyPermission); $familyPermission->setUser(null); return $this; }
@param FamilyPermission $familyPermission @return $this
public function unserialize($serialized) { list( $this->id, $this->username, $this->password, $this->salt, $this->roles ) = unserialize($serialized, []); }
Constructs the object. @param string $serialized the string representation of the object
public function editInlineAction(Request $request, DataInterface $data) { $parameters = array_merge( $request->query->all(), [ 'familyCode' => $data->getFamilyCode(), 'id' => $data->getId(), ] ); return $this->redirectToAction('edit', $parameters); }
@deprecated @param Request $request @param DataInterface $data @throws \Exception @return Response
public function previewAction(Request $request, DataInterface $data) { return $this->editAction($request, $data, $data->getFamily()); }
Alias for edit action but with custom form options @param Request $request @param DataInterface $data @throws \Exception @return Response
protected function getViewParameters(Request $request, Form $form = null, $data = null): array { $parameters = parent::getViewParameters($request, $form, $data); if ('preview' === $this->admin->getCurrentAction()->getCode()) { $parameters['disabled'] = $request->query->getBoolean('disabled'); } return $parameters; }
@param Request $request @param Form $form @param mixed $data @throws \Exception @return array
public function execute(ProcessState $state) { $input = $state->getInput(); $options = $this->getOptions($state); if (\is_array($input)) { if (!array_key_exists('id', $input)) { throw new \UnexpectedValueException('Expecting an array with the "id" key'); } $input = $input['id']; } /** @var FamilyInterface $family */ $family = $options['family']; /** @var DataRepository $repository */ $repository = $this->entityManager->getRepository($family->getDataClass()); $data = $repository->find($input); if (!$data instanceof DataInterface) { throw new \UnexpectedValueException("Data not found for id '{$input}'"); } if ($data instanceof ContextualDataInterface && null !== $options['context']) { $data->setCurrentContext($options['context']); } $this->dataLoader->loadSingle($data, $options['load_depth']); $state->setOutput($data); }
{@inheritdoc} @throws ExceptionInterface @throws \UnexpectedValueException
public function mediaUrlAction(Request $request, DataInterface $data, $filter) { if ('Image' !== $data->getFamilyCode()) { throw new \UnexpectedValueException("Data should be of family 'Image', '{$data->getFamilyCode()}' given"); } /** @var \Sidus\EAV\Image $data */ $image = $data->getImageFile(); if (!$image instanceof Image) { throw $this->createNotFoundException("No actual media associated to image #{$data->getId()}"); } return $this->get('liip_imagine.controller')->filterAction($request, $image->getPath(), $filter); }
@param Request $request @param DataInterface $data @param string $filter @return Response @throws \Exception
public function setContainer(ContainerInterface $container = null) { $this->container = $container; if ($container) { // Specifically inject translator for tryTranslate method $this->translator = $container->get('translator'); } }
@param ContainerInterface|null $container @throws ServiceCircularReferenceException @throws ServiceNotFoundException
protected function getTarget(Request $request) { if (!$request->isXmlHttpRequest()) { return $this->defaultTarget; } return $request->get('target', $this->defaultTarget); }
@param Request $request @return string|null
protected function getViewParameters(Request $request, Form $form = null, $data = null): array { $parameters = [ 'isAjax' => $request->isXmlHttpRequest(), 'target' => $request->get('target'), 'success' => $request->get('success'), 'isModal' => $request->isXmlHttpRequest() && $request->get('modal'), 'listPath' => $this->getAdminListPath($data), 'admin' => $this->admin, ]; if ($form) { $parameters['form'] = $form->createView(); } if ($data) { $parameters['data'] = $data; } return $parameters; }
@param Request $request @param Form $form @param mixed $data @throws \Exception @return array
protected function getAdminListPath($data = null, array $parameters = []): string { if (!$this->admin->hasAction('list')) { return $this->generateUrl('eavmanager_layout.dashboard', [], UrlGeneratorInterface::ABSOLUTE_PATH); } /** @var AdminRouter $adminRouter */ $adminRouter = $this->get(AdminRouter::class); return $adminRouter->generateAdminPath($this->admin, 'list', $parameters); }
@param mixed $data @param array $parameters @throws \Exception @return string
protected function bindDataGridRequest(DataGrid $dataGrid, Request $request, array $formOptions = []) { $formOptions = array_merge( [ 'attr' => [ 'data-target-element' => $this->getTarget($request), 'data-admin-code' => $this->admin->getCode(), ], ], $formOptions ); parent::bindDataGridRequest($dataGrid, $request, $formOptions); }
{@inheritdoc}
public function updateResourceMetadata(ResourceInterface $resource, File $file) { if ($resource instanceof Document) { $mimeType = $file->getMimetype(); $resource ->setFileModifiedAt($file->getTimestamp()) ->setFileSize($file->getSize()) ->setMimeType($mimeType); } if ($resource instanceof Image) { $imageSize = getimagesizefromstring($file->read()); $resource ->setWidth($imageSize[0] ?? null) ->setHeight($imageSize[1] ?? null); } }
@param ResourceInterface $resource @param File $file @throws \UnexpectedValueException
protected function execute(InputInterface $input, OutputInterface $output): ?int { $username = $this->getUsername($input, $output); $user = $this->findUser($output, $username); if (null === $user) { return 1; } $user->setSuperAdmin(!$input->getOption('demote')); $this->userManager->save($user); if ($user->isSuperAdmin()) { $message = $this->translator->trans( 'user.promoted', ['%username%' => $username], 'security' ); } else { $message = $this->translator->trans( 'user.demoted', ['%username%' => $username], 'security' ); } $output->writeln("<info>{$message}</info>"); return 0; }
@param InputInterface $input @param OutputInterface $output @throws \Exception @return int|null
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration($this->createConfiguration(), $configs); $container->setParameter('eavmanager_user.config', $config); parent::load($configs, $container); }
{@inheritdoc} @throws \Exception
public function channel(string $channel): Observable { // Only join a channel once if (isset($this->channels[$channel])) { return $this->channels[$channel]; } // Ensure we only get messages for the given channel $channelMessages = $this->messages->filter(function (Event $event) use ($channel) { return $event->getChannel() !== '' && $event->getChannel() === $channel; }); $subscribe = $this->connected ->do(function () use ($channel) { // Subscribe to pusher channel after connected $this->send(Event::subscribeOn($channel)); }) ->flatMapTo(Observable::empty()); // Observable representing channel events $this->channels[$channel] = $channelMessages ->merge($subscribe) ->filter([Event::class, 'subscriptionSucceeded']) ->retryWhen(function (Observable $errors) { return $errors->flatMap(function (Throwable $throwable) { return $this->handleLowLevelError($throwable); }); }) ->finally(function () use ($channel) { // Send unsubscribe event $this->send(Event::unsubscribeOn($channel)); // Remove our channel from the channel list so we don't resubscribe in case we reconnect unset($this->channels[$channel]); }) ->singleInstance(); return $this->channels[$channel]; }
Listen on a channel. @param string $channel Channel to listen on @throws \InvalidArgumentException @return Observable
private function timeout(Observable $events): Observable { $timeoutDuration = $this->connected->map(function (Event $event) { return ($event->getData()['activity_timeout'] ?? self::NO_ACTIVITY_TIMEOUT) * 1000; }); return $timeoutDuration ->combineLatest([$events]) ->pluck(0) ->concat(Observable::of(-1)) ->flatMapLatest(function (int $time) { // If the events observable ends, return an empty observable so we don't keep the stream alive if ($time === -1) { return Observable::empty(); } return Observable::never() ->timeout($time) ->catch(function () use ($time) { // ping (do something that causes incoming stream to get a message) $this->send(Event::ping()); // this timeout will actually timeout with a TimeoutException - causing // everything above this to dispose return Observable::never()->timeout($time); }); }); }
Returns an observable of TimeoutException. The timeout observable will get cancelled every time a new event is received. @param Observable $events @return Observable
private function handleLowLevelError(Throwable $throwable): Observable { // Only allow certain, relevant, exceptions if (!($throwable instanceof WebsocketErrorException) && !($throwable instanceof RuntimeException) && !($throwable instanceof PusherErrorException) ) { return Observable::error($throwable); } $code = $throwable->getCode(); $pusherError = ($throwable instanceof WebsocketErrorException || $throwable instanceof PusherErrorException); // Errors 4000-4099, don't retry connecting if ($pusherError && $code >= 4000 && $code <= 4099) { return Observable::error($throwable); } // Errors 4100-4199 reconnect after 1 or more seconds, we do it after 1.001 second if ($pusherError && $code >= 4100 && $code <= 4199) { return Observable::timer(1001); } // Errors 4200-4299 connection closed by Pusher, reconnect immediately, we wait 0.001 second if ($pusherError && $code >= 4200 && $code <= 4299) { return Observable::timer(1); } // Double our delay each time we get here $this->delay *= 2; return Observable::timer($this->delay); }
Handle errors as described at https://pusher.com/docs/pusher_protocol#error-codes. @param Throwable $throwable @return Observable
public function buildDataGridForm( Action $action, Request $request, DataGrid $dataGrid = null, array $formOptions = [] ): DataGrid { $target = $this->getTarget($request); if (null !== $target) { $formOptions['attr']['data-target-element'] = $target; } $formOptions['attr']['data-admin-code'] = $action->getAdmin()->getCode(); return parent::buildDataGridForm($action, $request, $dataGrid, $formOptions); }
@param Action $action @param Request $request @param DataGrid|null $dataGrid @param array $formOptions @return DataGrid
public function removeFamilyPermission(FamilyPermission $familyPermission) { $this->familyPermissions->removeElement($familyPermission); $familyPermission->setGroup(null); return $this; }
@param FamilyPermission $familyPermission @return $this
public function create(string $resourceClass, array $options = []): PropertyNameCollection { $propertyNameCollection = $this->propertyNameCollectionFactory->create($resourceClass, $options); if (is_a($resourceClass, DataInterface::class, true)) { $resolvedProperties = []; foreach ($propertyNameCollection as $propertyName) { if (!\in_array($propertyName, $this->ignoredAttributes, true)) { $resolvedProperties[] = $propertyName; } } $propertyNameCollection = new PropertyNameCollection($resolvedProperties); } return $propertyNameCollection; }
Creates the property name collection for the given class and options. @param string $resourceClass @param array $options @throws ResourceClassNotFoundException @return PropertyNameCollection
public function buildForm(FormBuilderInterface $builder, array $options) { $hierarchy = $options['hierarchy']; $builder->addEventListener( FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($hierarchy) { $roles = $event->getData(); $form = $event->getForm(); if ($hierarchy instanceof LeafRole) { $options = [ 'label' => $hierarchy->getRole(), 'required' => false, 'widget_checkbox_label' => 'widget', ]; if (\is_array($roles)) { /** @var array $roles */ foreach ($roles as $role) { if ($role === $hierarchy->getRole()) { unset($roles[$role]); $options['data'] = true; } } } $form->add('hasRole', CheckboxType::class, $options); $hierarchy = $hierarchy->getChildren(); } /** @var Role[] $hierarchy */ foreach ($hierarchy as $subRole) { $form->add( $subRole->getRole(), self::class, [ 'hierarchy' => $subRole, 'label' => false, 'data' => $roles, ] ); } } ); $builder->addModelTransformer( new CallbackTransformer( function ($originalData) { // Delete original data: return null; }, function ($submittedData) use ($hierarchy) { if ($hierarchy instanceof LeafRole) { if ($submittedData['hasRole']) { $submittedData[] = $hierarchy->getRole(); } unset($submittedData['hasRole']); } /** @var array $submittedData */ foreach ($submittedData as $key => $items) { if (\is_array($items)) { unset($submittedData[$key]); /** @var array $items */ foreach ($items as $role) { $submittedData[] = $role; } } } return $submittedData; } ) ); }
@param FormBuilderInterface $builder @param array $options @throws AlreadySubmittedException @throws LogicException @throws UnexpectedTypeException @throws \InvalidArgumentException
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'hierarchy' => $this->roleHierarchy->getTreeHierarchy(), 'required' => false, ] ); $resolver->setNormalizer( 'hierarchy', function (Options $options, $value) { $error = "'hierarchy' option must be a LeafRole or an array of LeafRole"; if (!$value instanceof \Traversable && !$value instanceof LeafRole) { throw new \UnexpectedValueException($error); } if (\is_array($value) || $value instanceof \Traversable) { /** @var array $value */ foreach ($value as $item) { if (!$item instanceof LeafRole) { throw new \UnexpectedValueException($error); } } } return $value; } ); }
@param OptionsResolver $resolver @throws AccessException @throws UndefinedOptionsException @throws \UnexpectedValueException
public function jsonSerialize() { $json = parent::jsonSerialize(); $json['width'] = $this->getWidth(); $json['height'] = $this->getHeight(); return $json; }
Serialize automatically the entity when passed to json_encode. @return array
public function getViewParameters( Action $action, Request $request, FamilyInterface $family, FormInterface $form = null, $data = null, array $listRouteParameters = [] ): array { $listRouteParameters['familyCode'] = $family->getCode(); $parameters = $this->baseTemplatingHelper->getViewParameters( $action, $request, $form, $data, $listRouteParameters ); $parameters['family'] = $family; return $parameters; }
@param Action $action @param Request $request @param FamilyInterface $family @param FormInterface $form @param mixed $data @param array $listRouteParameters @return array
public function create(string $resourceClass, string $property, array $options = []): PropertyMetadata { $propertyMetadata = $this->propertyMetadata->create($resourceClass, $property, $options); if ('code' === $property && is_a($resourceClass, FamilyInterface::class, true)) { return $propertyMetadata->withIdentifier(true); } return $propertyMetadata; }
Creates a property metadata. @param string $resourceClass @param string $property @param array $options @throws PropertyNotFoundException @return PropertyMetadata
public static function createFromViolations(ConstraintViolationListInterface $constraintViolationList) { $messages = []; /** @var ConstraintViolationInterface $violation */ foreach ($constraintViolationList as $violation) { $messages[] = $violation->getMessage(); } return new self(implode("\n", $messages)); }
@param ConstraintViolationListInterface $constraintViolationList @return BadUsernameException
public function bindDataGridRequest( Action $action, Request $request, FamilyInterface $family, DataGrid $dataGrid = null, array $formOptions = [] ): DataGrid { if (null === $dataGrid) { $dataGrid = $this->getDataGrid($action, $family); } return $this->baseDataGridHelper->bindDataGridRequest( $action, $request, $dataGrid, $formOptions ); }
@param Action $action @param Request $request @param FamilyInterface $family @param DataGrid|null $dataGrid @param array $formOptions @return DataGrid
public function getDataGridConfigCode(Action $action, FamilyInterface $family): string { $familiesOptions = $action->getAdmin()->getOption('families', []); if (isset($familiesOptions[$family->getCode()]['datagrid'])) { return $familiesOptions[$family->getCode()]['datagrid']; } // Check if datagrid code is set in options $dataGridCode = $action->getOption( 'datagrid', $action->getAdmin()->getOption('datagrid') ); if (null !== $dataGridCode) { return $dataGridCode; } // Check if a datagrid corresponding to the current family exists foreach ([$family->getCode(), strtolower($family->getCode())] as $dataGridCode) { if ($this->dataGridRegistry->hasDataGrid($dataGridCode)) { return $dataGridCode; } } return $action->getAdmin()->getCode(); // Fallback to admin code }
@param Action $action @param FamilyInterface $family @return string