private function getColumnName($field, $entity) { if (is_object($entity)) { $entity = get_class($entity); } return $this->doctrine->getEntityManagerForClass($entity)->getClassMetadata($entity)->getColumnName($field); }
/** * @param array $context * * @return Integration * @throws \LogicException */ public function getIntegrationFromContext(array $context) { if (!isset($context['channel'])) { throw new \LogicException('Context should contain reference to channel'); } return $this->registry->getRepository('OroIntegrationBundle:Channel')->getOrLoadById($context['channel']); }
/** * AbstractJournalItemMailer constructor. * @param OjsMailer $ojsMailer * @param RegistryInterface $registry * @param TokenStorageInterface $tokenStorage * @param RouterInterface $router */ public function __construct(OjsMailer $ojsMailer, RegistryInterface $registry, TokenStorageInterface $tokenStorage, RouterInterface $router) { $this->ojsMailer = $ojsMailer; $this->em = $registry->getManager(); $this->user = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null; $this->router = $router; }
/** * @param object $entity * @param Constraint $constraint * @return bool */ public function isValid($entity, Constraint $constraint) { if (!is_array($constraint->fields) && !is_string($constraint->fields)) { throw new UnexpectedTypeException($constraint->fields, 'array'); } $fields = (array) $constraint->fields; if (count($fields) == 0) { throw new ConstraintDefinitionException("At least one field has to be specified."); } $em = $this->registry->getEntityManager($constraint->em); $className = $this->context->getCurrentClass(); $class = $em->getClassMetadata($className); $criteria = array(); foreach ($fields as $fieldName) { if (!isset($class->reflFields[$fieldName])) { throw new ConstraintDefinitionException("Only field names mapped by Doctrine can be validated for uniqueness."); } $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity); } $repository = $em->getRepository($className); $result = $repository->findBy($criteria); if (count($result) > 0 && $result[0] !== $entity) { $oldPath = $this->context->getPropertyPath(); $this->context->setPropertyPath(empty($oldPath) ? $fields[0] : $oldPath . "." . $fields[0]); $this->context->addViolation($constraint->message, array(), $criteria[$fields[0]]); $this->context->setPropertyPath($oldPath); } return true; // all true, we added the violation already! }
/** * @param string $name * @param EngineInterface $templating * @param RegistryInterface $registry * @param CurrencyDetectorInterface $currencyDetector * @param ProductFinderInterface $productFinder * @param string $productClass */ public function __construct($name, EngineInterface $templating, RegistryInterface $registry, CurrencyDetectorInterface $currencyDetector, ProductFinderInterface $productFinder, $productClass) { $this->productRepository = $registry->getManager()->getRepository($productClass); $this->currencyDetector = $currencyDetector; $this->productFinder = $productFinder; parent::__construct($name, $templating); }
/** * Returns a JSON response containing options * * @param Request $request * * @return JsonResponse */ public function listAction(Request $request) { $query = $request->query; $search = $query->get('search'); $referenceDataName = $query->get('referenceDataName'); $class = $query->get('class'); if (null !== $referenceDataName) { $class = $this->registry->get($referenceDataName)->getClass(); } $repository = $this->doctrine->getRepository($class); if ($repository instanceof OptionRepositoryInterface) { $choices = $repository->getOptions($query->get('dataLocale'), $query->get('collectionId'), $search, $query->get('options', [])); } elseif ($repository instanceof ReferenceDataRepositoryInterface) { $choices['results'] = $repository->findBySearch($search, $query->get('options', [])); } elseif ($repository instanceof SearchableRepositoryInterface) { $choices['results'] = $repository->findBySearch($search, $query->get('options', [])); } elseif (method_exists($repository, 'getOptions')) { $choices = $repository->getOptions($query->get('dataLocale'), $query->get('collectionId'), $search, $query->get('options', [])); } else { throw new \LogicException(sprintf('The repository of the class "%s" can not retrieve options via Ajax.', $query->get('class'))); } if ($query->get('isCreatable') && 0 === count($choices['results'])) { $choices['results'] = [['id' => $search, 'text' => $search]]; } return new JsonResponse($choices); }
/** * @param FormInterface $form * @param Request $request * @param RegistryInterface $registry * @param SecurityContextInterface $security */ public function __construct(FormInterface $form, Request $request, RegistryInterface $registry, SecurityContextInterface $security) { $this->form = $form; $this->request = $request; $this->manager = $registry->getManager(); $this->organization = $security->getToken()->getOrganizationContext(); }
/** * @param string $name * @param EngineInterface $templating * @param RegistryInterface $registry * @param CurrencyDetectorInterface $currencyDetector * @param ProductFinderInterface $productFinder */ public function __construct($name, EngineInterface $templating, RegistryInterface $registry, CurrencyDetectorInterface $currencyDetector, ProductFinderInterface $productFinder) { $this->productRepository = $registry->getManager()->getRepository('Application\\Sonata\\ProductBundle\\Entity\\Product'); $this->currencyDetector = $currencyDetector; $this->productFinder = $productFinder; parent::__construct($name, $templating); }
/** * @param User $user * @param array $actualRepositories */ protected function updateUserRepositories(User $user, array $actualRepositories) { // Reindex array by GH repository ids $actualRepositories = array_column($actualRepositories, null, 'id'); $userRepositoryIds = []; /** @var Repository $repository */ foreach ($user->getRepositories() as $repository) { // Repository was removed from github if (!array_key_exists($repository->getGithubId(), $actualRepositories)) { $user->getRepositories()->removeElement($repository); continue; } // Collect ids of user repositories $userRepositoryIds[] = $repository->getGithubId(); } $repositoryManager = $this->doctrine->getManagerForClass(Repository::class); // Create repository entities for new repositories from github array_map(function ($repository) use($userRepositoryIds, $user, $repositoryManager) { if (!in_array($repository['id'], $userRepositoryIds)) { $repository = (new Repository())->setGithubId($repository['id'])->setFullName($repository['full_name'])->setName($repository['name'])->setOwner($user); $repositoryManager->persist($repository); $user->addRepository($repository); } }, $actualRepositories); $repositoryManager->flush(); }
/** * @inheritdoc */ public function finishView(FormView $view, FormInterface $form, array $options) { /** @var ChoiceView $choice */ foreach ($view->vars['choices'] as $choice) { if ($options['select2_template_result']) { $object = $choice->value; if ($this->doctrine && $options['class']) { $object = $this->doctrine->getRepository($options['class'])->find($object); } if (is_string($options['select2_template_result'])) { $choice->attr['data-template-result'] = $this->templating->render($options['select2_template_result'], ['choice' => $choice, 'object' => $object]); } else { $choice->attr['data-template-result'] = call_user_func_array($options['select2_template_result'], [$choice, $object]); } } if ($options['select2_template_selection']) { $object = $choice->value; if ($this->doctrine && $options['class']) { $object = $this->doctrine->getRepository($options['class'])->find($object); } if (is_string($options['select2_template_selection'])) { $choice->attr['data-template-selection'] = $this->templating->render($options['select2_template_selection'], ['choice' => $choice, 'object' => $object]); } else { $choice->attr['data-template-selection'] = call_user_func_array($options['select2_template_selection'], [$choice, $object]); } } } if ($options['select2'] === true) { $options['select2_options'] = array_merge($this->select2DefaultOptions, $options['select2_options']); $view->vars['select2_options'] = json_encode($options['select2_options']); } }
/** * Generate the entity PHP code. * * @param BundleInterface $bundle * @param string $name * @param array $fields * @param string $namePrefix * @param string $dbPrefix * @param string|null $extendClass * * @return array * @throws \RuntimeException */ protected function generateEntity(BundleInterface $bundle, $name, $fields, $namePrefix, $dbPrefix, $extendClass = null) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity\\' . $namePrefix), $config->getEntityNamespaces())); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $namePrefix . '\\' . $name; $entityPath = $bundle->getPath() . '/Entity/' . $namePrefix . '/' . str_replace('\\', '/', $name) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass)); } $class = new ClassMetadataInfo($entityClass, new UnderscoreNamingStrategy()); foreach ($fields as $fieldSet) { foreach ($fieldSet as $fieldArray) { foreach ($fieldArray as $field) { if (array_key_exists('joinColumn', $field)) { $class->mapManyToOne($field); } elseif (array_key_exists('joinTable', $field)) { $class->mapManyToMany($field); } else { $class->mapField($field); } } } } $class->setPrimaryTable(array('name' => strtolower($dbPrefix . strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $name))) . 's')); $entityCode = $this->getEntityGenerator($extendClass)->generateEntityClass($class); return array($entityCode, $entityPath); }
/** * Generate Fixture from bundle name, entity name, fixture name and ids * * @param BundleInterface $bundle * @param string $entity * @param string $name * @param array $ids * @param string|null $connectionName */ public function generate(BundleInterface $bundle, $entity, $name, array $ids, $order, $connectionName = null) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager($connectionName)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $fixtureFileName = $this->getFixtureFileName($entity, $name, $ids); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $fixturePath = $bundle->getPath() . '/DataFixtures/ORM/' . $fixtureFileName . '.php'; $bundleNameSpace = $bundle->getNamespace(); if (file_exists($fixturePath)) { throw new \RuntimeException(sprintf('Fixture "%s" already exists.', $fixtureFileName)); } $class = new ClassMetadataInfo($entityClass); $fixtureGenerator = $this->getFixtureGenerator(); $fixtureGenerator->setFixtureName($fixtureFileName); $fixtureGenerator->setBundleNameSpace($bundleNameSpace); $fixtureGenerator->setMetadata($class); $fixtureGenerator->setFixtureOrder($order); /** @var EntityManager $em */ $em = $this->registry->getManager($connectionName); $repo = $em->getRepository($class->rootEntityName); if (empty($ids)) { $items = $repo->findAll(); } else { $items = $repo->findById($ids); } $fixtureGenerator->setItems($items); $fixtureCode = $fixtureGenerator->generateFixtureClass($class); $this->filesystem->mkdir(dirname($fixturePath)); file_put_contents($fixturePath, $fixtureCode); }
public function packageExistsTest($package) { if (!preg_match('/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/', $package)) { return false; } return $this->doctrine->getRepository('PackagistWebBundle:Package')->packageExists($package); }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$this->context instanceof ExecutionContext) { throw new UnexpectedTypeException($this->context, ExecutionContext::class); } if (!$constraint instanceof UniqueUser) { throw new UnexpectedTypeException($constraint, UniqueUser::class); } // just return null if the value is empty // since an empty value cannot exist in the database // and should be validated using the NotBlank constraint if (null === $value) { return; } if (!is_string($value) && !is_object($value) && !method_exists($constraint, '__toString')) { throw new UnexpectedTypeException($value, 'string'); } $entityManager = $this->registry->getManager($constraint->entityManager); if (!$entityManager) { throw new RuntimeException(sprintf('Invalid manager "%s"!', $constraint->entityManager)); } $repository = $entityManager->getRepository($constraint->entity); $result = $repository->findOneBy([$constraint->property => $value]); if (null !== $result) { $this->context->buildViolation($constraint->message)->setInvalidValue($value)->setParameter('%prop%', $constraint->property)->addViolation(); } }
/** * Constructor * * @param RegistryInterface $registry * @param string $class * @param RouterInterface $router * @param string $routeName */ public function __construct(RegistryInterface $registry, $class, RouterInterface $router, $routeName) { $tableName = $registry->getManager()->getClassMetadata($class)->table['name']; $dql = "SELECT p.id as productId, p.slug as slug, p.updated_at as lastmod, 'weekly' as changefreq, '0.5' as priority " . "FROM " . $tableName . " p " . "WHERE p.enabled = 1"; $source = new DoctrineDBALConnectionSourceIterator($registry->getConnection(), $dql); $this->iterator = new SymfonySitemapSourceIterator($source, $router, $routeName, array('productId' => null, 'slug' => null)); }
/** * Mass updates entities * * @param string $class * @param array $data * @param array $ids */ public function updateEntities($class, array $data, array $ids) { $qb = $this->doctrine->getManager()->createQueryBuilder()->update($class, 'o')->where('o.id IN (:ids)')->setParameter('ids', $ids); foreach ($data as $key => $value) { $qb->set("o.{$key}", ":{$key}")->setParameter(":{$key}", $value); } $qb->getQuery()->execute(); }
/** * ContainerService constructor. * * @param RegistryInterface $registry * @param EventDispatcherInterface $eventDispatcher * @param ContainerInterface $serviceContainer * @param string $cacheDir * @param bool $debug */ public function __construct(RegistryInterface $registry, EventDispatcherInterface $eventDispatcher, ContainerInterface $serviceContainer, $cacheDir, $debug = false) { $this->objectManager = $registry->getManager(); $this->cacheDir = $cacheDir . '/twig'; $this->debug = $debug; $this->eventDispatcher = $eventDispatcher; $this->serviceContainer = $serviceContainer; }
/** * @param FormInterface $form * @param Request $request * @param RegistryInterface $doctrine * @param ValidatorInterface $validator * @param TranslatorInterface $translator */ public function __construct(FormInterface $form, Request $request, RegistryInterface $doctrine, ValidatorInterface $validator, TranslatorInterface $translator) { $this->form = $form; $this->request = $request; $this->manager = $doctrine->getManager(); $this->validator = $validator; $this->translator = $translator; }
protected function findPattern(FormBuilderInterface $builder) { $pattern = $this->registry->getRepository('ClasticAliasBundle:AliasPattern')->findOneBy(array('moduleIdentifier' => $builder->getData()->getNode()->getType())); if ($pattern) { return $pattern->getPattern(); } return '{title}'; }
/** * @inheritDoc */ public function __invoke(UserActivateCommand $command) { $user = $command->getUser(); $user->setEnabled(true); $em = $this->registry->getManager(); $em->persist($user); $em->flush(); }
/** * @param \Twig_Environment $twig * @return string */ public function getSideBar(\Twig_Environment $twig) { $em = $this->doctrine->getManager(); $posts = $em->getRepository('AppBundle:Post')->showMostPopularPost(); $comments = $em->getRepository('AppBundle:Comment')->showLastFiveComment(); $tags = $em->getRepository('AppBundle:Tag')->showNotNullTags(); return $twig->render('@App/sidebar.html.twig', array('posts' => $posts, 'comments' => $comments, 'tags' => $tags)); }
/** * DeleteService constructor. * @param RegistryInterface $registry * @param Reader $reader * @param TranslatorInterface $translator */ public function __construct(RegistryInterface $registry, Reader $reader, TranslatorInterface $translator, $rootDir, $bundles) { $this->em = $registry->getManager(); $this->reader = $reader; $this->translator = $translator; $this->yaml = new Parser(); $this->rootDir = $rootDir; $this->bundles = $bundles; }
/** * {@inheritdoc} */ public function hydrate($document, MetaInformationInterface $metaInformation) { $entityId = $metaInformation->getEntityId(); $doctrineEntity = $this->doctrine->getManager()->getRepository($metaInformation->getClassName())->find($entityId); if ($doctrineEntity !== null) { $metaInformation->setEntity($doctrineEntity); } return $this->valueHydrator->hydrate($document, $metaInformation); }
protected function prepareEvent() { $this->entity->setEntities(['OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1', 'OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2']); $this->event->expects($this->atLeastOnce())->method('getChannel')->will($this->returnValue($this->entity)); $this->settingProvider->expects($this->at(0))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1')->will($this->returnValue('TestConnector1')); $this->settingProvider->expects($this->at(1))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2')->will($this->returnValue('TestConnector2')); $this->registry->expects($this->any())->method('getManager')->will($this->returnValue($this->em)); $this->em->expects($this->once())->method('persist')->with($this->integration); $this->em->expects($this->once())->method('flush'); }
public function testProcess() { $this->form->expects($this->once())->method('setData')->with($this->entity); $this->request->expects($this->once())->method('getMethod')->will($this->returnValue('POST')); $this->form->expects($this->once())->method('submit'); $this->form->expects($this->once())->method('isValid')->will($this->returnValue(true)); $this->manager->expects($this->once())->method('persist')->with($this->entity); $this->manager->expects($this->once())->method('flush'); $this->assertTrue($this->handler->process($this->entity)); }
/** * {@inheritdoc} */ public function addManager(ManagerInterface $manager) { $class = $manager->getClass(); $em = $this->doctrine->getManagerForClass($class); $manager->setObjectManager($em); $manager->setRepository($em->getRepository($class)); $manager->setEventDispatcher($this->eventDispatcher); $manager->setFactory($this); $this->managers[$class] = $manager; }
/** * {@inheritDoc} * * @param Notify $request */ public function execute($request) { $notification = new NotificationDetails(); $request->getToken() ? $notification->setGatewayName($request->getToken()->getGatewayName()) : $notification->setGatewayName('unknown'); $this->gateway->execute($getHttpRequest = new GetHttpRequest()); $notification->setDetails($getHttpRequest->query); $notification->setCreatedAt(new \DateTime()); $this->doctrine->getManager()->persist($notification); $this->doctrine->getManager()->flush(); }
/** * Get marketing list types choices. * * @return array */ public function getListTypeChoices() { /** @var MarketingListType[] $types */ $types = $this->registry->getManagerForClass(self::MARKETING_LIST_TYPE)->getRepository(self::MARKETING_LIST_TYPE)->findBy(array(), array('name' => 'ASC')); $results = array(); foreach ($types as $type) { $results[$type->getName()] = $type->getLabel(); } return $results; }
/** * @return Channel|bool */ protected function getChannelReference() { $channelId = $this->request->query->get('channelId'); if (!empty($channelId)) { /** @var EntityManager $em */ $em = $this->registry->getManager(); return $em->getReference('OroCRMChannelBundle:Channel', $channelId); } return false; }
/** * {@inheritdoc} */ public function getEntityManager() { if ($this->entityManager instanceof ObjectManager) { return $this->entityManager; } $em = $this->registry->getManagerForClass(self::TRANSACTION_CLASS); if (!$em) { throw new \RuntimeException(sprintf('No entity manager defined for class %s', self::TRANSACTION_CLASS)); } return $em; }