/**
  * Modifies the Request object to apply configuration information found in
  * controllers annotations like the template to render or HTTP caching
  * configuration.
  *
  * @param FilterControllerEvent $event A FilterControllerEvent instance
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
     $object = new \ReflectionClass($className);
     $method = $object->getMethod($controller[1]);
     $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object));
     $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method));
     $configurations = array();
     foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) {
         if (!array_key_exists($key, $classConfigurations)) {
             $configurations[$key] = $methodConfigurations[$key];
         } elseif (!array_key_exists($key, $methodConfigurations)) {
             $configurations[$key] = $classConfigurations[$key];
         } else {
             if (is_array($classConfigurations[$key])) {
                 if (!is_array($methodConfigurations[$key])) {
                     throw new \UnexpectedValueException('Configurations should both be an array or both not be an array');
                 }
                 $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]);
             } else {
                 // method configuration overrides class configuration
                 $configurations[$key] = $methodConfigurations[$key];
             }
         }
     }
     $request = $event->getRequest();
     foreach ($configurations as $key => $attributes) {
         $request->attributes->set($key, $attributes);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function supports(PuliResource $resource)
 {
     if (false === $resource instanceof CmfResource) {
         return false;
     }
     return $this->metadataFactory->hasMetadataFor(ClassUtils::getRealClass($resource->getPayloadType()));
 }
 /**
  * Move element
  *
  * @param string $position
  */
 public function moveAction($position)
 {
     $translator = $this->get('translator');
     if (!$this->admin->isGranted('EDIT')) {
         $this->addFlash('sonata_flash_error', $translator->trans('flash_error_no_rights_update_position'));
         return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
     }
     $object = $this->admin->getSubject();
     /** @var PositionHandler $positionService */
     $positionService = $this->get('pix_sortable_behavior.position');
     $entity = \Doctrine\Common\Util\ClassUtils::getClass($object);
     $lastPosition = $positionService->getLastPosition($entity);
     $position = $positionService->getPosition($object, $position, $lastPosition);
     $setter = sprintf('set%s', ucfirst($positionService->getPositionFieldByEntity($entity)));
     if (!method_exists($object, $setter)) {
         throw new \LogicException(sprintf('%s does not implement ->%s() to set the desired position.', $object, $setter));
     }
     $object->{$setter}($position);
     $this->admin->update($object);
     if ($this->isXmlHttpRequest()) {
         return $this->renderJson(array('result' => 'ok', 'objectId' => $this->admin->getNormalizedIdentifier($object)));
     }
     $this->addFlash('sonata_flash_success', $translator->trans('flash_success_position_updated'));
     return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
 }
 /**
  * {@inheritDoc}
  */
 public function boot()
 {
     // Register an autoloader for proxies to avoid issues when unserializing them
     // when the ORM is used.
     if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) {
         $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace');
         $dir = $this->container->getParameter('doctrine.orm.proxy_dir');
         $proxyGenerator = null;
         if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes')) {
             // See https://github.com/symfony/symfony/pull/3419 for usage of references
             $container =& $this->container;
             $proxyGenerator = function ($proxyDir, $proxyNamespace, $class) use(&$container) {
                 $originalClassName = ClassUtils::getRealClass($class);
                 /** @var $registry Registry */
                 $registry = $container->get('doctrine');
                 // Tries to auto-generate the proxy file
                 /** @var $em \Doctrine\ORM\EntityManager */
                 foreach ($registry->getManagers() as $em) {
                     if (!$em->getConfiguration()->getAutoGenerateProxyClasses()) {
                         continue;
                     }
                     $metadataFactory = $em->getMetadataFactory();
                     if ($metadataFactory->isTransient($originalClassName)) {
                         continue;
                     }
                     $classMetadata = $metadataFactory->getMetadataFor($originalClassName);
                     $em->getProxyFactory()->generateProxyClasses(array($classMetadata));
                     clearstatcache(true, Autoloader::resolveFile($proxyDir, $proxyNamespace, $class));
                     break;
                 }
             };
         }
         $this->autoloader = Autoloader::register($dir, $namespace, $proxyGenerator);
     }
 }
 /**
  * Checks if the entity can has notes
  *
  * @param object $entity
  * @return bool
  */
 public function isNoteAssociationEnabled($entity)
 {
     if (!is_object($entity) || !$this->doctrineHelper->isManageableEntity($entity) || $this->doctrineHelper->isNewEntity($entity)) {
         return false;
     }
     return $this->noteAssociationHelper->isNoteAssociationEnabled(ClassUtils::getClass($entity));
 }
 /**
  * Gets class name for the object, taking doctrine proxies into account.
  *
  * @param object $object The object.
  *
  * @return string The FQCN of the given object.
  */
 public static function getClass($object)
 {
     if (class_exists('\\Doctrine\\Common\\Util\\ClassUtils')) {
         return \Doctrine\Common\Util\ClassUtils::getClass($object);
     }
     return get_class($object);
 }
Beispiel #7
0
 /**
  * {@inheritDoc}
  */
 public function vote(TokenInterface $token, $object, array $attributes)
 {
     if (!$object || !is_object($object)) {
         return self::ACCESS_ABSTAIN;
     }
     $objectClass = ClassUtils::getClass($object);
     if (!$this->supportsClass($objectClass)) {
         return self::ACCESS_ABSTAIN;
     }
     foreach ($attributes as $attribute) {
         if (!$this->supportsAttribute($attribute)) {
             return self::ACCESS_ABSTAIN;
         }
     }
     $object = $this->convertToSupportedObject($object, $objectClass);
     /** @var EmailUser[] $emailUsers */
     $emailUsers = $object->getEmailUsers();
     foreach ($attributes as $attribute) {
         foreach ($emailUsers as $emailUser) {
             if ($this->container->get('oro_security.security_facade')->isGranted($attribute, $emailUser)) {
                 return self::ACCESS_GRANTED;
             }
             if ($mailbox = $emailUser->getMailboxOwner() !== null && $token instanceof UsernamePasswordOrganizationToken) {
                 $repo = $this->container->get('doctrine')->getRepository('OroEmailBundle:Mailbox');
                 $mailboxes = $repo->findAvailableMailboxes($token->getUser(), $token->getOrganizationContext());
                 if (in_array($mailbox, $mailboxes)) {
                     return self::ACCESS_GRANTED;
                 }
             }
         }
     }
     return self::ACCESS_DENIED;
 }
 /**
  * @param object $object
  * @param int $depth
  * @param bool $ignoreAcl
  * @param Organization|null $organization
  *
  * @return Recipient[]
  */
 public function getRecipients($object, $depth = 1, $ignoreAcl = false, Organization $organization = null)
 {
     $recipients = [];
     if ($this->isAccessDenyForOrganization($object, $ignoreAcl, $organization)) {
         return $recipients;
     }
     if (!$depth || ($ignoreAcl || !$this->securityFacade->isGranted('VIEW', $object))) {
         if (!$depth || $this->securityFacade->getLoggedUser() !== $object) {
             return $recipients;
         }
     }
     $className = ClassUtils::getClass($object);
     $metadata = $this->getMetadata($className);
     $attributes = $this->initAttributes($className, $metadata);
     foreach ($metadata->associationMappings as $name => $assoc) {
         if (in_array('Oro\\Bundle\\EmailBundle\\Entity\\EmailInterface', class_implements($assoc['targetEntity']), true)) {
             $attributes[] = new EmailAttribute($name, true);
         } else {
             if ($depth > 1) {
                 $assocObject = $this->getPropertyAccessor()->getValue($object, $name);
                 if (!$assocObject instanceof \Traversable && !is_array($assocObject)) {
                     if ($assocObject) {
                         $assocObject = [$assocObject];
                     } else {
                         $assocObject = [];
                     }
                 }
                 foreach ($assocObject as $obj) {
                     $recipients = array_merge($recipients, $this->getRecipients($obj, $depth - 1, false, $organization));
                 }
             }
         }
     }
     return array_merge($recipients, $this->createRecipientsFromEmails($this->createEmailsFromAttributes($attributes, $object), $object, $metadata));
 }
 /**
  * @param $entity
  */
 public function invalidateProcess($entity)
 {
     $handler = $this->getHandlerByClass(ClassUtils::getClass($entity));
     if ($handler) {
         $handler->invalidateProcess($entity);
     }
 }
 /**
  * @param OnFlushEventArgs $args
  */
 public function onFlush(OnFlushEventArgs $args)
 {
     $this->initializeFromEventArgs($args);
     $entities = array_merge($this->uow->getScheduledEntityInsertions(), $this->uow->getScheduledEntityDeletions(), $this->uow->getScheduledEntityUpdates());
     /** @var Opportunity[] $entities */
     $entities = array_filter($entities, function ($entity) {
         return 'OroCRM\\Bundle\\SalesBundle\\Entity\\Opportunity' === ClassUtils::getClass($entity);
     });
     foreach ($entities as $entity) {
         if (!$entity->getId() && $this->isValuable($entity)) {
             // handle creation, just add to prev lifetime value and recalculate change set
             $b2bCustomer = $entity->getCustomer();
             $b2bCustomer->setLifetime($b2bCustomer->getLifetime() + $entity->getCloseRevenue());
             $this->scheduleUpdate($b2bCustomer);
             $this->uow->computeChangeSet($this->em->getClassMetadata(ClassUtils::getClass($b2bCustomer)), $b2bCustomer);
         } elseif ($this->uow->isScheduledForDelete($entity) && $this->isValuable($entity)) {
             $this->scheduleUpdate($entity->getCustomer());
         } elseif ($this->uow->isScheduledForUpdate($entity)) {
             // handle update
             $changeSet = $this->uow->getEntityChangeSet($entity);
             if ($this->isChangeSetValuable($changeSet)) {
                 if (!empty($changeSet['customer']) && $changeSet['customer'][0] instanceof B2bCustomer && B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet)) {
                     // handle change of b2b customer
                     $this->scheduleUpdate($changeSet['customer'][0]);
                 }
                 if ($this->isValuable($entity, isset($changeSet['closeRevenue'])) || B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet) && $entity->getCustomer()) {
                     $this->scheduleUpdate($entity->getCustomer());
                 }
             }
         }
     }
 }
 /**
  * Collect changes that were done
  * Generates tags and store in protected variable
  *
  * @param OnFlushEventArgs $event
  */
 public function onFlush(OnFlushEventArgs $event)
 {
     if (!$this->isApplicationInstalled) {
         return;
     }
     $em = $event->getEntityManager();
     $uow = $em->getUnitOfWork();
     $entities = array_merge($uow->getScheduledEntityDeletions(), $uow->getScheduledEntityInsertions(), $uow->getScheduledEntityUpdates());
     $collections = array_merge($uow->getScheduledCollectionUpdates(), $uow->getScheduledCollectionDeletions());
     foreach ($collections as $collection) {
         $owner = $collection->getOwner();
         if (!in_array($owner, $entities, true)) {
             $entities[] = $owner;
         }
     }
     $generator = $this->sender->getGenerator();
     foreach ($entities as $entity) {
         if (!in_array(ClassUtils::getClass($entity), $this->skipTrackingFor)) {
             // invalidate collection view pages only when entity has been added or removed
             $includeCollectionTag = $uow->isScheduledForInsert($entity) || $uow->isScheduledForDelete($entity);
             $this->collectedTags = array_merge($this->collectedTags, $generator->generate($entity, $includeCollectionTag));
         }
     }
     $this->collectedTags = array_unique($this->collectedTags);
 }
 /**
  * {@inheritdoc}
  */
 public function name($objectOrClass)
 {
     $class = is_object($objectOrClass) ? ClassUtils::getClass($objectOrClass) : $objectOrClass;
     if (!isset($this->names[$class])) {
         $nsParts = array_map(function ($nsPart) {
             return explode('_', StringsUtil::toUnderscore($nsPart));
         }, explode('\\', $class));
         $offset = array_search(['entity'], $nsParts);
         if ($offset) {
             $nsParts = array_slice($nsParts, $offset + 1);
         }
         $nsPartsCount = count($nsParts);
         for ($i = 0; $i < $nsPartsCount - 1; $i++) {
             if (array_intersect($nsParts[$i], $nsParts[$i + 1]) === $nsParts[$i]) {
                 unset($nsParts[$i]);
             }
         }
         $parts = [];
         foreach ($nsParts as $nsPart) {
             $parts = array_merge($parts, $nsPart);
         }
         $this->names[$class] = implode('_', $parts);
     }
     return $this->names[$class];
 }
 /**
  * Checks if the entity can have comments
  *
  * @param object|null $entity
  *
  * @return bool
  */
 public function isApplicable($entity)
 {
     if (!is_object($entity) || !$this->doctrineHelper->isManageableEntity($entity) || !$this->securityFacade->isGranted('oro_comment_view')) {
         return false;
     }
     return $this->commentAssociationHelper->isCommentAssociationEnabled(ClassUtils::getClass($entity));
 }
 /**
  * Returns DELETE query builder with conditions for deleting from snapshot table by entity
  *
  * @param array $entities
  * @throws \InvalidArgumentException
  * @return QueryBuilder|null
  */
 protected function getSnapshotDeleteQueryBuilderByEntities(array $entities)
 {
     if (empty($entities)) {
         throw new \InvalidArgumentException('List of entity can not be empty');
     }
     $deleteParams = array();
     $entityManager = $this->getEntityManager();
     $segmentQB = $entityManager->createQueryBuilder();
     $segmentQB->select('s.id, s.entity')->from('OroSegmentBundle:Segment', 's');
     foreach ($entities as $key => $entity) {
         if (is_array($entity) && array_key_exists('id', $entity)) {
             $entityId = $entity['id'];
             $className = ClassUtils::getClass($entity['entity']);
         } else {
             /** @var object $entity */
             $className = ClassUtils::getClass($entity);
             $metadata = $entityManager->getClassMetadata($className);
             $entityIds = $metadata->getIdentifierValues($entity);
             $entityId = reset($entityIds);
         }
         if (!$entityId) {
             continue;
         }
         if (!isset($deleteParams[$className])) {
             $segmentQB->orWhere('s.entity = :className' . $key)->setParameter('className' . $key, $className);
         }
         $deleteParams[$className]['entityIds'][] = (string) $entityId;
     }
     $segments = $segmentQB->getQuery()->getResult();
     foreach ($segments as $segment) {
         $deleteParams[$segment['entity']]['segmentIds'][] = (string) $segment['id'];
     }
     return $this->getDeleteQueryBuilderByParameters($deleteParams);
 }
 /**
  * {@inheritdoc}
  */
 public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $entity)
 {
     $data = $this->uow->getOriginalEntityData($entity);
     $data = array_merge($data, $key->identifier);
     // why update has no identifier values ?
     foreach ($metadata->associationMappings as $name => $assoc) {
         if (!isset($data[$name])) {
             continue;
         }
         if (!isset($assoc['cache']) || !($assoc['type'] & ClassMetadata::TO_ONE)) {
             unset($data[$name]);
             continue;
         }
         if (!isset($assoc['id'])) {
             $targetClass = ClassUtils::getClass($data[$name]);
             $targetId = $this->uow->getEntityIdentifier($data[$name]);
             $data[$name] = new AssociationCacheEntry($targetClass, $targetId);
             continue;
         }
         // handle association identifier
         $targetId = is_object($data[$name]) && $this->uow->isInIdentityMap($data[$name]) ? $this->uow->getEntityIdentifier($data[$name]) : $data[$name];
         // @TODO - fix it !
         // handle UnitOfWork#createEntity hash generation
         if (!is_array($targetId)) {
             $data[reset($assoc['joinColumnFieldNames'])] = $targetId;
             $targetEntity = $this->em->getClassMetadata($assoc['targetEntity']);
             $targetId = array($targetEntity->identifier[0] => $targetId);
         }
         $data[$name] = new AssociationCacheEntry($assoc['targetEntity'], $targetId);
     }
     return new EntityCacheEntry($metadata->name, $data);
 }
Beispiel #16
0
 /**
  * Check object status is enity
  *
  * @param object|string $entity
  * @return bool
  */
 protected function isEntity($entity)
 {
     if (is_object($entity)) {
         $entity = ClassUtils::getClass($entity);
     }
     return !$this->entityManager->getMetadataFactory()->isTransient($entity);
 }
 /**
  * Modifies the Request object to apply configuration information found in
  * controllers annotations like the template to render or HTTP caching
  * configuration.
  *
  * @param FilterControllerEvent $event A FilterControllerEvent instance
  *
  * @return void
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
     $object = new \ReflectionClass($className);
     $transactional = $this->reader->getClassAnnotation($object, Transactional::NAME);
     if (!$transactional instanceof Transactional) {
         return;
     }
     $avoidTransaction = $this->reader->getMethodAnnotation($object->getMethod($controller[1]), AvoidTransaction::NAME);
     if (!is_null($avoidTransaction)) {
         return;
     }
     $request = $event->getRequest();
     $modelName = $transactional->model;
     $model = new $modelName();
     $this->transactionBuilder->setRequestMethod($request->getRealMethod());
     $this->transactionBuilder->setRequestSource(Transaction::SOURCE_REST);
     $this->transactionBuilder->setRelatedRoute($transactional->relatedRoute);
     $ids = [];
     foreach ($model->getIds() as $field => $value) {
         $ids[$field] = $request->attributes->get($field);
     }
     $this->transactionBuilder->setRelatedIds($ids);
     $this->transactionBuilder->setModel($transactional->model);
     $transaction = $this->transactionBuilder->build();
     $request->attributes->set('transaction', $transaction);
 }
Beispiel #18
0
 /**
  * Add owner field to forms
  *
  * @param BeforeFormRenderEvent $event
  */
 public function addOwnerField(BeforeFormRenderEvent $event)
 {
     $environment = $event->getTwigEnvironment();
     $data = $event->getFormData();
     $form = $event->getForm();
     $label = false;
     $entityProvider = $this->configManager->getProvider('entity');
     if (is_object($form->vars['value'])) {
         $className = ClassUtils::getClass($form->vars['value']);
         if (class_exists($className) && $entityProvider->hasConfig($className, 'owner')) {
             $config = $entityProvider->getConfig($className, 'owner');
             $label = $config->get('label');
         }
     }
     $ownerField = $environment->render("OroOrganizationBundle::owner.html.twig", array('form' => $form, 'label' => $label));
     /**
      * Setting owner field as first field in first data block
      */
     if (!empty($data['dataBlocks'])) {
         if (isset($data['dataBlocks'][0]['subblocks'])) {
             if (!isset($data['dataBlocks'][0]['subblocks'][0])) {
                 $data['dataBlocks'][0]['subblocks'][0] = ['data' => []];
             }
             array_unshift($data['dataBlocks'][0]['subblocks'][0]['data'], $ownerField);
         }
     }
     $event->setFormData($data);
 }
 /**
  * Get the last available version for the provided document
  *
  * @param VersionableInterface $versionable
  *
  * @return Version|null
  */
 protected function getPreviousVersion(VersionableInterface $versionable)
 {
     $resourceName = ClassUtils::getClass($versionable);
     $resourceId = $versionable->getId();
     $version = $this->documentManager->createQueryBuilder($this->versionClass)->field('resourceName')->equals($resourceName)->field('resourceId')->equals($resourceId)->limit(1)->sort('loggedAt', 'desc')->getQuery()->getSingleResult();
     return $version;
 }
 /**
  * Returns the context for the given activity class and id
  *
  * @param string $class The FQCN of the activity entity
  * @param        $id
  *
  * @return array
  */
 public function getActivityContext($class, $id)
 {
     $currentUser = $this->securityTokenStorage->getToken()->getUser();
     $userClass = ClassUtils::getClass($currentUser);
     $entity = $this->doctrineHelper->getEntity($class, $id);
     $result = [];
     if (!$entity || !$entity instanceof ActivityInterface) {
         return $result;
     }
     $targets = $entity->getActivityTargetEntities();
     $entityProvider = $this->configManager->getProvider('entity');
     foreach ($targets as $target) {
         $targetClass = ClassUtils::getClass($target);
         $targetId = $target->getId();
         if ($userClass === $targetClass && $currentUser->getId() === $targetId) {
             continue;
         }
         $item = [];
         $config = $entityProvider->getConfig($targetClass);
         $safeClassName = $this->entityClassNameHelper->getUrlSafeClassName($targetClass);
         $item = $this->prepareItemTitle($item, $targetClass, $target, $targetId);
         $item['activityClassAlias'] = $this->entityAliasResolver->getPluralAlias($class);
         $item['entityId'] = $id;
         $item['targetId'] = $targetId;
         $item['targetClassName'] = $safeClassName;
         $item['icon'] = $config->get('icon');
         $item['link'] = $this->getContextLink($targetClass, $targetId);
         $item = $this->dispatchContextTitle($item, $targetClass);
         $result[] = $item;
     }
     return $result;
 }
 /**
  * @param EmailTemplate                  $value
  * @param Constraint|EmailTemplateSyntax $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     // prepare templates to be validated
     $itemsToValidate = [['field' => 'subject', 'locale' => null, 'template' => $value->getSubject()], ['field' => 'content', 'locale' => null, 'template' => $value->getContent()]];
     $translations = $value->getTranslations();
     foreach ($translations as $trans) {
         if (in_array($trans->getField(), ['subject', 'content'])) {
             $itemsToValidate[] = ['field' => $trans->getField(), 'locale' => $trans->getLocale(), 'template' => $trans->getContent()];
         }
     }
     /** @var \Twig_Extension_Sandbox $sandbox */
     $sandbox = $this->twig->getExtension('sandbox');
     $sandbox->enableSandbox();
     // validate templates' syntax
     $errors = [];
     foreach ($itemsToValidate as &$item) {
         try {
             $this->twig->parse($this->twig->tokenize($item['template']));
         } catch (\Twig_Error_Syntax $e) {
             $errors[] = ['field' => $item['field'], 'locale' => $item['locale'], 'error' => $e->getMessage()];
         }
     }
     $sandbox->disableSandbox();
     // add violations for found errors
     if (!empty($errors)) {
         foreach ($errors as $error) {
             $this->context->addViolation($constraint->message, ['{{ field }}' => $this->getFieldLabel(ClassUtils::getClass($value), $error['field']), '{{ locale }}' => $this->getLocaleName($error['locale']), '{{ error }}' => $error['error']]);
         }
     }
 }
Beispiel #22
0
 /**
  * Handle onFlush event
  *
  * @param OnFlushEventArgs $event
  */
 public function handleOnFlush(OnFlushEventArgs $event)
 {
     $em = $event->getEntityManager();
     $uow = $em->getUnitOfWork();
     $newEntities = $uow->getScheduledEntityInsertions();
     foreach ($newEntities as $entity) {
         if ($entity instanceof Call) {
             $hasChanges = $this->activityManager->addActivityTarget($entity, $entity->getOwner());
             // recompute change set if needed
             if ($hasChanges) {
                 $uow->computeChangeSet($em->getClassMetadata(ClassUtils::getClass($entity)), $entity);
             }
         }
     }
     $changedEntities = $uow->getScheduledEntityUpdates();
     foreach ($changedEntities as $entity) {
         if ($entity instanceof Call) {
             $hasChanges = false;
             $changeSet = $uow->getEntityChangeSet($entity);
             foreach ($changeSet as $field => $values) {
                 if ($field === 'owner') {
                     list($oldValue, $newValue) = $values;
                     if ($oldValue !== $newValue) {
                         $hasChanges |= $this->activityManager->replaceActivityTarget($entity, $oldValue, $newValue);
                     }
                     break;
                 }
             }
             // recompute change set if needed
             if ($hasChanges) {
                 $uow->computeChangeSet($em->getClassMetadata(ClassUtils::getClass($entity)), $entity);
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function update(PersistentCollection $collection)
 {
     if ($collection->isDirty() && $collection->getSnapshot()) {
         throw CacheException::updateReadOnlyCollection(ClassUtils::getClass($collection->getOwner()), $this->association['fieldName']);
     }
     parent::update($collection);
 }
 /**
  * {@inheritdoc}
  */
 public function transform($value)
 {
     if (!$value) {
         return '';
     }
     if (is_array($value)) {
         $result = [];
         $user = $this->securityFacade->getToken()->getUser();
         foreach ($value as $target) {
             if (ClassUtils::getClass($user) === ClassUtils::getClass($target) && $user->getId() === $target->getId()) {
                 continue;
             }
             if ($fields = $this->mapper->getEntityMapParameter(ClassUtils::getClass($target), 'title_fields')) {
                 $text = [];
                 foreach ($fields as $field) {
                     $text[] = $this->mapper->getFieldValue($target, $field);
                 }
             } else {
                 $text = [(string) $target];
             }
             $text = implode(' ', $text);
             if ($label = $this->getClassLabel(ClassUtils::getClass($target))) {
                 $text .= ' (' . $label . ')';
             }
             $result[] = json_encode(['text' => $text, 'id' => json_encode(['entityClass' => ClassUtils::getClass($target), 'entityId' => $target->getId()])]);
         }
         $value = implode(';', $result);
     }
     return $value;
 }
 /**
  * @Route("/newPagePart", name="KunstmaanPagePartBundle_admin_newpagepart")
  * @Template("KunstmaanPagePartBundle:PagePartAdminTwigExtension:pagepart.html.twig")
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return array
  */
 public function newPagePartAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $pageId = $request->get('pageid');
     $pageClassName = $request->get('pageclassname');
     $context = $request->get('context');
     $pagePartClass = $request->get('type');
     $page = $em->getRepository($pageClassName)->findOneById($pageId);
     $pagePartConfigurationReader = new PagePartConfigurationReader($this->container->get('kernel'));
     $pagePartAdminConfigurators = $pagePartConfigurationReader->getPagePartAdminConfigurators($page);
     $pagePartAdminConfigurator = null;
     foreach ($pagePartAdminConfigurators as $ppac) {
         if ($context == $ppac->getContext()) {
             $pagePartAdminConfigurator = $ppac;
         }
     }
     if (is_null($pagePartAdminConfigurator)) {
         throw new \RuntimeException(sprintf('No page part admin configurator found for context "%s".', $context));
     }
     $pagePartAdmin = new PagePartAdmin($pagePartAdminConfigurator, $em, $page, $context, $this->container);
     $pagePart = new $pagePartClass();
     $formFactory = $this->container->get('form.factory');
     $formBuilder = $formFactory->createBuilder(FormType::class);
     $pagePartAdmin->adaptForm($formBuilder);
     $id = 'newpp_' . time();
     $data = $formBuilder->getData();
     $data['pagepartadmin_' . $id] = $pagePart;
     $adminType = $pagePart->getDefaultAdminType();
     $adminTypeFqn = ClassUtils::getClass($adminType);
     $formBuilder->add('pagepartadmin_' . $id, $adminTypeFqn);
     $formBuilder->setData($data);
     $form = $formBuilder->getForm();
     $formview = $form->createView();
     return array('id' => $id, 'form' => $formview, 'pagepart' => $pagePart, 'pagepartadmin' => $pagePartAdmin, 'editmode' => true);
 }
 /**
  * @param FormEvent $event
  */
 public function postSetData(FormEvent $event)
 {
     $form = $event->getForm();
     if ($form->getParent()) {
         return;
     }
     if (!$form->has($this->fieldName)) {
         return;
     }
     $isEntityExists = false;
     $entity = $event->getData();
     if ($entity) {
         if (!is_object($entity)) {
             return;
         }
         $entityClass = ClassUtils::getClass($entity);
         $entityManager = $this->managerRegistry->getManagerForClass($entityClass);
         if (!$entityManager) {
             return;
         }
         $entityIdentifier = $entityManager->getClassMetadata($entityClass)->getIdentifierValues($entity);
         $isEntityExists = !empty($entityIdentifier);
     }
     // if entity exists and assign is not granted - replace field with disabled text field,
     // otherwise - set default owner value
     if ($isEntityExists) {
         $this->replaceOwnerField($form);
     } else {
         $this->setPredefinedOwner($form);
     }
 }
 /**
  * Returns the context for the given email
  *
  * @param Email $email
  *
  * @return array
  */
 public function getEmailContext(Email $email)
 {
     $criteria = Criteria::create();
     $criteria->andWhere(Criteria::expr()->eq('id', $email->getId()));
     $qb = $this->activityManager->getActivityTargetsQueryBuilder($this->class, $criteria);
     if (null === $qb) {
         return [];
     }
     $result = $qb->getQuery()->getResult();
     if (empty($result)) {
         return $result;
     }
     $currentUser = $this->securityFacade->getLoggedUser();
     $currentUserClass = ClassUtils::getClass($currentUser);
     $currentUserId = $currentUser->getId();
     $result = array_values(array_filter($result, function ($item) use($currentUserClass, $currentUserId) {
         return !($item['entity'] === $currentUserClass && $item['id'] == $currentUserId);
     }));
     foreach ($result as &$item) {
         $route = $this->configManager->getEntityMetadata($item['entity'])->getRoute();
         $item['entityId'] = $email->getId();
         $item['targetId'] = $item['id'];
         $item['targetClassName'] = $this->entityClassNameHelper->getUrlSafeClassName($item['entity']);
         $item['icon'] = $this->configManager->getProvider('entity')->getConfig($item['entity'])->get('icon');
         $item['link'] = $route ? $this->router->generate($route, ['id' => $item['id']]) : null;
         unset($item['id'], $item['entity']);
     }
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function save($group, array $options = [])
 {
     /* @var GroupInterface */
     if (!$group instanceof GroupInterface) {
         throw new \InvalidArgumentException(sprintf('Expects a "Pim\\Bundle\\CatalogBundle\\Model\\GroupInterface", "%s" provided.', ClassUtils::getClass($group)));
     }
     $this->eventDispatcher->dispatch(GroupEvents::PRE_SAVE, new GenericEvent($group));
     $options = $this->optionsResolver->resolveSaveOptions($options);
     $this->versionContext->addContextInfo(sprintf('Comes from variant group %s', $group->getCode()), $this->productClassName);
     if ($group->getType()->isVariant()) {
         $template = $group->getProductTemplate();
         if (null !== $template) {
             $this->templateMediaManager->handleProductTemplateMedia($template);
         }
     }
     $this->objectManager->persist($group);
     if (true === $options['flush']) {
         $this->objectManager->flush();
     }
     if (count($options['add_products']) > 0) {
         $this->addProducts($options['add_products']);
     }
     if (count($options['remove_products']) > 0) {
         $this->removeProducts($options['remove_products']);
     }
     if ($group->getType()->isVariant() && true === $options['copy_values_to_products']) {
         $this->copyVariantGroupValues($group);
     }
     $this->eventDispatcher->dispatch(GroupEvents::POST_SAVE, new GenericEvent($group));
 }
 /**
  * Create a pending version for a versionable entity
  *
  * @param object      $versionable
  * @param string      $author
  * @param array       $changeset
  * @param string|null $context
  *
  * @return Version
  */
 public function createPendingVersion($versionable, $author, array $changeset, $context = null)
 {
     $resourceName = ClassUtils::getClass($versionable);
     $version = new Version($resourceName, $versionable->getId(), $author, $context);
     $version->setChangeset($changeset);
     return $version;
 }
Beispiel #30
0
 /**
  * {@inheritdoc}
  */
 public function setDefaults(MediaInterface $media, $parentPath = null)
 {
     $class = ClassUtils::getClass($media);
     // check and add name if possible
     if (!$media->getName()) {
         if ($media->getId()) {
             $media->setName(PathHelper::getNodeName($media->getId()));
         } else {
             throw new \RuntimeException(sprintf('Unable to set defaults, Media of type "%s" does not have a name or id.', $class));
         }
     }
     $rootPath = is_null($parentPath) ? $this->rootPath : $parentPath;
     $path = ($rootPath === '/' ? $rootPath : $rootPath . '/') . $media->getName();
     /** @var DocumentManager $dm */
     $dm = $this->getObjectManager();
     // TODO use PHPCR autoname once this is done: http://www.doctrine-project.org/jira/browse/PHPCR-103
     if ($dm->find($class, $path)) {
         // path already exists
         $media->setName($media->getName() . '_' . time() . '_' . rand());
     }
     if (!$media->getParent()) {
         $parent = $dm->find(null, PathHelper::getParentPath($path));
         $media->setParent($parent);
     }
 }