/**
  * @return ObjectRepository
  */
 protected function getLoginPageRepository()
 {
     if (!$this->loginPageRepository) {
         $this->loginPageRepository = $this->doctrine->getManagerForClass('OroB2BCMSBundle:LoginPage')->getRepository('OroB2BCMSBundle:LoginPage');
     }
     return $this->loginPageRepository;
 }
 /**
  * @param OrmFilterDatasourceAdapter $ds
  * @param string                     $fieldName
  *
  * @return array [entity, alias, field]
  *
  * @throws \RuntimeException
  */
 protected function getFilterParts(OrmFilterDatasourceAdapter $ds, $fieldName)
 {
     $fieldParts = explode('.', $fieldName);
     if (count($fieldParts) !== 2) {
         throw new \RuntimeException(sprintf('It is expected that $fieldName is in "alias.name" format, but "%s" given.', $fieldName));
     }
     $qb = $ds->getQueryBuilder();
     $entity = $this->getRootEntity($qb, $fieldParts[0]);
     if (empty($entity)) {
         $associations = [];
         $entity = $this->findEntityByAlias($qb, $fieldParts[0]);
         while (!empty($entity) && strpos($entity, ':') === false && strpos($entity, '\\') === false) {
             $parts = explode('.', $entity);
             array_unshift($associations, $parts[1]);
             $entity = $this->findEntityByAlias($qb, $parts[0]);
         }
         if (empty($entity)) {
             throw new \RuntimeException(sprintf('Cannot find root entity for "$s". It seems that a query is not valid.', $fieldName));
         }
         foreach ($associations as $assoc) {
             $entity = $this->doctrine->getManagerForClass($entity)->getClassMetadata($entity)->getAssociationTargetClass($assoc);
         }
     }
     if (empty($entity)) {
         throw new \RuntimeException(sprintf('Cannot find entity for "$s". It seems that a query is not valid.', $fieldName));
     }
     return [$entity, $fieldParts[0], $fieldParts[1]];
 }
 /**
  * @param int $segmentId
  *
  * @return MarketingList
  */
 public function getMarketingListBySegment($segmentId)
 {
     if (empty($this->marketingListsBySegment[$segmentId])) {
         $this->marketingListsBySegment[$segmentId] = $this->managerRegistry->getManagerForClass(self::MARKETING_LIST)->getRepository(self::MARKETING_LIST)->findOneBy(['segment' => $segmentId]);
     }
     return $this->marketingListsBySegment[$segmentId];
 }
 /**
  * Returns class metadata for a defined entity parameter
  *
  * @param string $entityParameter
  *
  * @return \Doctrine\Common\Persistence\Mapping\ClassMetadata
  */
 protected function getClassMetadata($entityParameter)
 {
     $entityClassName = $this->container->getParameter($entityParameter);
     $manager = $this->managerRegistry->getManagerForClass($entityClassName);
     $classMetadata = $manager->getClassMetadata($entityClassName);
     return $classMetadata;
 }
 public function runCrons()
 {
     $entityManager = $this->managerRegistry->getManagerForClass('DspSoftsCronManagerBundle:CronTask');
     $cronTaskRepo = $entityManager->getRepository('DspSoftsCronManagerBundle:CronTask');
     $cronTasks = $cronTaskRepo->findCronsToLaunch();
     foreach ($cronTasks as $cronTask) {
         $run = true;
         if (!$cronTask->getRelaunch()) {
             $run = $this->planificationChecker->isExecutionDue($cronTask->getPlanification());
         }
         if ($run) {
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Running Cron Task <info>%s</info>', $cronTask->getName()));
             }
             $cli = 'exec ' . $this->kernelRootDir . DIRECTORY_SEPARATOR . 'console dsp:cron:runjob -c ' . $cronTask->getId() . ' &';
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Command line : <info>%s</info>', $cli));
             }
             $process = new Process($cli);
             $process->setTimeout(0);
             $process->start();
         } else {
             if ($this->logger !== null) {
                 $this->logger->info(sprintf('Skipping Cron Task <info>%s</info>', $cronTask->getName()));
             }
         }
     }
 }
 /**
  * @param ConsoleTerminateEvent $event
  */
 public function onConsoleTerminate(ConsoleTerminateEvent $event)
 {
     if (!$this->isExceptionOccurred) {
         if ($event->getCommand() instanceof UpdateSchemaDoctrineCommand) {
             $output = $event->getOutput();
             $input = $event->getInput();
             if ($input->getOption('force')) {
                 $result = $this->fulltextIndexManager->createIndexes();
                 $output->writeln('Schema update and create index completed.');
                 if ($result) {
                     $output->writeln('Indexes were created.');
                 }
             }
         }
         if ($event->getCommand() instanceof UpdateSchemaCommand) {
             /** @var EntityManager $searchEntityManager */
             $searchEntityManager = $this->registry->getManagerForClass('OroSearchBundle:UpdateEntity');
             $entities = $searchEntityManager->getRepository('OroSearchBundle:UpdateEntity')->findAll();
             if (count($entities)) {
                 /** @var EntityManager $em */
                 $em = $this->registry->getManagerForClass('JMS\\JobQueueBundle\\Entity\\Job');
                 foreach ($entities as $entity) {
                     $job = new Job(ReindexCommand::COMMAND_NAME, ['class' => $entity->getEntity()]);
                     $em->persist($job);
                     $searchEntityManager->remove($entity);
                 }
                 $em->flush();
                 $searchEntityManager->flush();
             }
         }
     }
     $this->isExceptionOccurred = null;
 }
 /**
  * {@inheritdoc}
  */
 public function getSerializationConfig($className)
 {
     /** @var EntityManager $em */
     $em = $this->doctrine->getManagerForClass($className);
     $metadata = $em->getClassMetadata($className);
     $extendConfigProvider = $this->configManager->getProvider('extend');
     $fields = [];
     foreach ($metadata->getFieldNames() as $fieldName) {
         $extendFieldConfig = $extendConfigProvider->getConfig($className, $fieldName);
         if ($extendFieldConfig->is('is_extend')) {
             // skip extended fields
             continue;
         }
         $fields[$fieldName] = null;
     }
     foreach ($metadata->getAssociationNames() as $fieldName) {
         $extendFieldConfig = $extendConfigProvider->getConfig($className, $fieldName);
         if ($extendFieldConfig->is('is_extend')) {
             // skip extended fields
             continue;
         }
         $mapping = $metadata->getAssociationMapping($fieldName);
         if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) {
             $targetMetadata = $em->getClassMetadata($mapping['targetEntity']);
             $idFieldNames = $targetMetadata->getIdentifierFieldNames();
             if (count($idFieldNames) === 1) {
                 $fields[$fieldName] = ['fields' => $idFieldNames[0]];
             }
         }
     }
     return ['exclusion_policy' => 'all', 'hints' => ['HINT_TRANSLATABLE'], 'fields' => $fields];
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (!$this->installed) {
         return;
     }
     $request = $event->getRequest();
     if ($request->attributes->has('_controller') || $event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     $slugUrl = $request->getPathInfo();
     if ($slugUrl !== '/') {
         $slugUrl = rtrim($slugUrl, '/');
     }
     /** @var EntityManager $em */
     $em = $this->registry->getManagerForClass('OroB2BRedirectBundle:Slug');
     $slug = $em->getRepository('OroB2BRedirectBundle:Slug')->findOneBy(['url' => $slugUrl]);
     if ($slug) {
         $routeName = $slug->getRouteName();
         $controller = $this->router->getRouteCollection()->get($routeName)->getDefault('_controller');
         $parameters = [];
         $parameters['_route'] = $routeName;
         $parameters['_controller'] = $controller;
         $redirectRouteParameters = $slug->getRouteParameters();
         $parameters = array_merge($parameters, $redirectRouteParameters);
         $parameters['_route_params'] = $redirectRouteParameters;
         $request->attributes->add($parameters);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function loadClassMetadata(ClassMetadataInterface $classMetadata, array $normalizationGroups = null, array $denormalizationGroups = null, array $validationGroups = null)
 {
     $className = $classMetadata->getReflectionClass()->name;
     $manager = $this->managerRegistry->getManagerForClass($className);
     if (!$manager) {
         return $classMetadata;
     }
     $doctrineClassMetadata = $manager->getClassMetadata($className);
     if (!$doctrineClassMetadata) {
         return $classMetadata;
     }
     $identifiers = $doctrineClassMetadata->getIdentifier();
     if (1 !== count($identifiers)) {
         return $classMetadata;
     }
     $identifierName = $identifiers[0];
     if (!$classMetadata->hasAttributeMetadata($identifierName)) {
         $attributeMetadata = $this->attributeMetadataFactory->getAttributeMetadataFor($classMetadata, $identifierName, $normalizationGroups, $denormalizationGroups);
         if ($doctrineClassMetadata->isIdentifierNatural()) {
             $attributeMetadata = $attributeMetadata->withWritable(false);
         }
         $classMetadata = $classMetadata->withAttributeMetadata($identifierName, $attributeMetadata);
     }
     $classMetadata = $classMetadata->withIdentifierName($identifierName);
     return $classMetadata;
 }
 /**
  * @param string $entityName  Entity name to prepare search handler for
  * @param string $targetField Entity field to search by and include to search results
  */
 public function initForEntity($entityName, $targetField)
 {
     $this->entityName = str_replace('_', '\\', $entityName);
     $this->initDoctrinePropertiesByEntityManager($this->registry->getManagerForClass($this->entityName));
     $this->properties = array_unique(array_merge($this->defaultPropertySet, [$targetField]));
     $this->currentField = $targetField;
 }
Beispiel #11
0
 /**
  * @param string $type
  *
  * @return FilterIn|null
  */
 private function create($type)
 {
     $manager = $this->managerRegistry->getManagerForClass($type);
     if ($manager) {
         return new FilterIn($manager->getRepository($type));
     }
 }
 /**
  * {@inheritdoc}
  * @throws RuntimeException
  */
 public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
 {
     // Locate possible ObjectManager
     $objectManager = $this->managerRegistry->getManagerForClass($metadata->name);
     if (!$objectManager) {
         // No ObjectManager found, proceed with normal deserialization
         return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
     }
     // Locate possible ClassMetadata
     $classMetadataFactory = $objectManager->getMetadataFactory();
     if ($classMetadataFactory->isTransient($metadata->name)) {
         // No ClassMetadata found, proceed with normal deserialization
         return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
     }
     try {
         $id = $this->resolveIdentifier($metadata, $data, $objectManager);
     } catch (\Exception $e) {
         $id = null;
     }
     if ($id && ($entity = $objectManager->find($metadata->name, $id))) {
         /* @var $objectManager EntityManager */
         if ($this->isNewIdRegistered($metadata->name, $id)) {
             throw new RuntimeException("Not a unique entity '{$metadata->name}' with identifier '{$id}''");
         }
         $this->registerNewId($metadata->name, $id);
         return $entity;
     }
     // No ClassMetadata found, proceed with normal deserialization
     return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if ($options['em'] === null) {
         $em = $this->registry->getManagerForClass($options['class']);
     } else {
         $em = $this->registry->getManager($options['em']);
     }
     $repository = $em->getRepository($options['class']);
     $entities = $repository->findAll();
     /** @var ClassMetadataInfo $classMetadata */
     $classMetadata = $em->getClassMetadata($options['class']);
     $identifierField = $classMetadata->getSingleIdentifierFieldName();
     $choiceLabels = [];
     /** @var AddressType $entity */
     foreach ($entities as $entity) {
         $pkValue = $classMetadata->getReflectionProperty($identifierField)->getValue($entity);
         if ($options['property']) {
             $value = $classMetadata->getReflectionProperty($options['property'])->getValue($entity);
         } else {
             $value = (string) $entity;
         }
         $choiceLabels[$pkValue] = $this->translator->trans('orob2b.customer.customer_typed_address_with_default_type.choice.default_text', ['%type_name%' => $value]);
     }
     $builder->add('default', 'choice', ['choices' => $choiceLabels, 'multiple' => true, 'expanded' => true, 'label' => false])->addViewTransformer(new AddressTypeDefaultTransformer($em));
 }
 /**
  * @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);
     }
 }
 /**
  * @param string $entityClass
  * @return EntityManager
  * @throws LogicException
  */
 protected function getEntityManager($entityClass)
 {
     $entityManager = $this->managerRegistry->getManagerForClass($entityClass);
     if (!$entityManager) {
         throw new LogicException(sprintf('Can\'t find entity manager for %s', $entityClass));
     }
     return $entityManager;
 }
Beispiel #16
0
 /**
  * @return \Doctrine\Common\Persistence\ObjectManager
  * @throws \FSi\Bundle\AdminBundle\Exception\RuntimeException
  */
 public function getObjectManager()
 {
     $om = $this->registry->getManagerForClass($this->getClassName());
     if (is_null($om)) {
         throw new RuntimeException(sprintf('Registry manager does\'t have manager for class "%s".', $this->getClassName()));
     }
     return $om;
 }
Beispiel #17
0
 /**
  * @param string $entityClass
  *
  * @return EntityManager
  *
  * @throws \RuntimeException
  */
 public function getEntityManager($entityClass)
 {
     $em = $this->doctrine->getManagerForClass($entityClass);
     if (!$em) {
         throw new \RuntimeException(sprintf('Entity class "%s" is not manageable.', $entityClass));
     }
     return $em;
 }
 /**
  * @return ObjectManager
  */
 public function getObjectManager()
 {
     $manager = $this->registry->getManagerForClass($this->class);
     if (!$manager) {
         throw new \RuntimeException(sprintf("Unable to find the mapping information for the class %s." . " Please check the 'auto_mapping' option (http://symfony.com/doc/current/reference/configuration/doctrine.html#configuration-overview)" . " or add the bundle to the 'mappings' section in the doctrine configuration.", $this->class));
     }
     return $manager;
 }
 /**
  * Gets the manager if applicable.
  *
  * @param ResourceInterface $resourceType
  * @param mixed             $data
  *
  * @return ObjectManager|null
  */
 private function getManager(ResourceInterface $resourceType, $data)
 {
     $objectManager = $this->managerRegistry->getManagerForClass($resourceType->getEntityClass());
     if (null === $objectManager || !is_object($data)) {
         return;
     }
     return $objectManager;
 }
 /**
  * Get object manager for class
  *
  * @param string|object $source An class name or entity
  *
  * @return ObjectManager
  */
 public function getManager($source)
 {
     $source = $this->getClass($source);
     if (null === ($om = $this->registry->getManagerForClass($source))) {
         throw new \LogicException(sprintf('Could not get object manager for class %s', $source));
     }
     return $om;
 }
 /**
  * @param string $class
  * @return ClassMetadata|null
  */
 protected function getMetadataForClass($class)
 {
     $entityManager = $this->managerRegistry->getManagerForClass($class);
     if (!$entityManager) {
         return null;
     }
     return $entityManager->getClassMetadata($class);
 }
 /**
  * @param object $entity
  * @param Constraint $constraint
  */
 public function validate($entity, Constraint $constraint)
 {
     if (!is_array($constraint->fields) && !is_string($constraint->fields)) {
         throw new UnexpectedTypeException($constraint->fields, 'array');
     }
     $fields = (array) $constraint->fields;
     if (0 === count($fields)) {
         throw new ConstraintDefinitionException('At least one field has to be specified.');
     }
     if ($constraint->em) {
         $em = $this->registry->getManager($constraint->em);
     } else {
         $em = $this->registry->getManagerForClass(get_class($entity));
     }
     $className = $this->context->getCurrentClass();
     $class = $em->getClassMetadata($className);
     /* @var $class \Doctrine\Common\Persistence\Mapping\ClassMetadata */
     $criteria = array();
     foreach ($fields as $fieldName) {
         if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) {
             throw new ConstraintDefinitionException("Only field names mapped by Doctrine can be validated for uniqueness.");
         }
         $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity);
         if (null === $criteria[$fieldName]) {
             return;
         }
         if ($class->hasAssociation($fieldName)) {
             /* Ensure the Proxy is initialized before using reflection to
              * read its identifiers. This is necessary because the wrapped
              * getter methods in the Proxy are being bypassed.
              */
             $em->initializeObject($criteria[$fieldName]);
             $relatedClass = $em->getClassMetadata($class->getAssociationTargetClass($fieldName));
             $relatedId = $relatedClass->getIdentifierValues($criteria[$fieldName]);
             if (count($relatedId) > 1) {
                 throw new ConstraintDefinitionException("Associated entities are not allowed to have more than one identifier field to be " . "part of a unique constraint in: " . $class->getName() . "#" . $fieldName);
             }
             $criteria[$fieldName] = array_pop($relatedId);
         }
     }
     $repository = $em->getRepository($className);
     $result = $repository->findBy($criteria);
     /* If the result is a MongoCursor, it must be advanced to the first
      * element. Rewinding should have no ill effect if $result is another
      * iterator implementation.
      */
     if ($result instanceof \Iterator) {
         $result->rewind();
     }
     /* If no entity matched the query criteria or a single entity matched,
      * which is the same as the entity being validated, the criteria is
      * unique.
      */
     if (0 === count($result) || 1 === count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result))) {
         return;
     }
     $this->context->addViolationAtSubPath($fields[0], $constraint->message, array(), $criteria[$fields[0]]);
 }
 /**
  * Returns EntityManager for entity.
  *
  * @param Workflow $workflow
  * @param Attribute $attribute
  * @return EntityManager
  * @throws SerializerException
  */
 protected function getEntityManager(Workflow $workflow, Attribute $attribute)
 {
     $entityClass = $attribute->getOption('class');
     $result = $this->registry->getManagerForClass($entityClass);
     if (!$result) {
         throw new SerializerException(sprintf('Attribute "%s" of workflow "%s" contains object of "%s", but it\'s not managed entity class', $attribute->getName(), $workflow->getName(), $entityClass));
     }
     return $result;
 }
 /**
  * @param ConfigSettingsUpdateEvent $event
  */
 public function onFormPreSetData(ConfigSettingsUpdateEvent $event)
 {
     $settingsKey = $this->getSettingsKey();
     $settings = $event->getSettings();
     if (is_array($settings) && array_key_exists($settingsKey, $settings)) {
         $settings[$settingsKey]['value'] = $this->registry->getManagerForClass($this->ownerClass)->find($this->ownerClass, $settings[$settingsKey]['value']);
         $event->setSettings($settings);
     }
 }
 /**
  * Get choices list for unit field.
  *
  * @return array
  */
 protected function getUnitChoices()
 {
     $choices = [];
     $units = $this->registry->getManagerForClass('OroB2BProductBundle:ProductUnit')->getRepository('OroB2BProductBundle:ProductUnit')->findAll();
     foreach ($units as $unit) {
         $choices[$unit->getCode()] = $this->formatter->format($unit->getCode());
     }
     return $choices;
 }
Beispiel #26
0
 /**
  * @param string $entityClassName
  * @return EntityManager
  * @throws NotManageableEntityException
  */
 protected function getEntityManager($entityClassName)
 {
     /** @var EntityManager $entityManager */
     $entityManager = $this->registry->getManagerForClass($entityClassName);
     if (!$entityManager) {
         throw new NotManageableEntityException($entityClassName);
     }
     return $entityManager;
 }
 /**
  * {@inheritdoc}
  */
 public function filter($rawValue, $operator)
 {
     /** @var EntityManager $em */
     $em = $this->registry->getManagerForClass($this->entityFQCN);
     if (null === $this->field) {
         return $em->getReference($this->entityFQCN, $rawValue);
     } else {
         return $em->getRepository($this->entityFQCN)->findOneBy([$this->field => $rawValue]);
     }
 }
 private function tryLoadingDoctrineMetadata($className)
 {
     if (!($manager = $this->registry->getManagerForClass($className))) {
         return null;
     }
     if ($manager->getMetadataFactory()->isTransient($className)) {
         return null;
     }
     return $manager->getClassMetadata($className);
 }
 /**
  * Process onResponse event, updates user history information
  *
  * @param  FilterResponseEvent $event
  *
  * @return bool|null
  */
 public function onResponse(FilterResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         // Do not do anything
         return null;
     }
     /** @var EntityManager $em */
     $em = $this->registry->getManagerForClass($this->historyItemFQCN);
     $request = $event->getRequest();
     $response = $event->getResponse();
     $token = $this->securityContext->getToken();
     $user = $organization = null;
     if ($token instanceof TokenInterface) {
         $user = $token->getUser();
     }
     // check if a current request can be added to a history
     if (!$this->canAddToHistory($response, $request, $user)) {
         return false;
     }
     if ($token instanceof OrganizationContextTokenInterface) {
         $organization = $token->getOrganizationContext();
     }
     $postArray = ['url' => $request->getRequestUri(), 'user' => $user, 'organization' => $organization];
     /** @var $historyItem  NavigationHistoryItem */
     $historyItem = $em->getRepository($this->historyItemFQCN)->findOneBy($postArray);
     if (!$historyItem) {
         $routeParameters = $request->get('_route_params');
         unset($routeParameters['id']);
         $entityId = filter_var($request->get('id'), FILTER_VALIDATE_INT);
         if (false !== $entityId) {
             $entityId = (int) $entityId;
         } else {
             $entityId = null;
         }
         $postArray['route'] = $request->get('_route');
         $postArray['routeParameters'] = $routeParameters;
         $postArray['entityId'] = $entityId;
         /** @var $historyItem \Oro\Bundle\NavigationBundle\Entity\NavigationItemInterface */
         $historyItem = $this->navItemFactory->createItem($this->navigationHistoryItemType, $postArray);
     }
     $historyItem->setTitle($this->titleService->getSerialized());
     // force update
     $historyItem->doUpdate();
     // disable Doctrine events for history item processing
     $eventManager = $em->getEventManager();
     if ($eventManager instanceof OroEventManager) {
         $eventManager->disableListeners('^Oro');
     }
     $em->persist($historyItem);
     $em->flush($historyItem);
     if ($eventManager instanceof OroEventManager) {
         $eventManager->clearDisabledListeners();
     }
     return true;
 }
 /**
  * Transforms a string (id) to an object (object).
  *
  * @param string $id
  *
  * @throws TransformationFailedException if object (object) is not found.
  *
  * @return object|null
  */
 public function reverseTransform($id)
 {
     if (empty($id)) {
         return;
     }
     $object = $this->registry->getManagerForClass($this->class)->getRepository($this->class)->find($id);
     if (null === $object) {
         throw new TransformationFailedException(sprintf('Object from class %s with id "%s" not found', $this->class, $id));
     }
     return $object;
 }