/**
  * 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);
 }
 /**
  * {@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();
     }
 }
 /**
  * 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);
 }
 /**
  * {@inheritdoc}
  */
 public function order(OrderInterface $order)
 {
     if (!$order->getId()) {
         throw new \RuntimeException('The order is not persisted into the database');
     }
     $this->generateReference($order, $this->registry->getManager()->getClassMetadata(get_class($order))->table['name']);
 }
 /**
  * @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));
 }
 /**
  * @inheritDoc
  */
 public function __invoke(UserActivateCommand $command)
 {
     $user = $command->getUser();
     $user->setEnabled(true);
     $em = $this->registry->getManager();
     $em->persist($user);
     $em->flush();
 }
 /**
  * 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();
 }
 /**
  * {@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);
 }
Example #9
0
 /**
  * @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}
  *
  * @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();
 }
 /**
  * @inheritDoc
  */
 public function __invoke(UserRegisterCommand $command)
 {
     $user = $command->getUser();
     $user->setUsername($user->getEmail());
     $em = $this->registry->getManager();
     $em->persist($user);
     $em->flush();
     $hash = password_hash($user->getSalt(), PASSWORD_DEFAULT);
     $message = \Swift_Message::newInstance()->setSubject('Brökkes Account validation')->setFrom('*****@*****.**')->setTo($user->getEmail())->setBody($this->templating->render(':Email:registration.html.twig', ['hash' => urlencode($hash), 'user' => $user]), 'text/html')->addPart($this->templating->render(':Email:registration.txt.twig', ['hash' => urlencode($hash), 'user' => $user]), 'text/plain');
     $this->mailer->send($message);
 }
 protected function trainContainer()
 {
     $this->request->getSession()->willReturn($this->session);
     $this->request->getLocale()->willReturn('fr_FR');
     $this->doctrine->getManager()->willReturn($this->manager);
     $this->doctrine->getManager()->willReturn($this->manager);
     $this->doctrine->getRepository('DonateCoreBundle:Intent')->willReturn($this->intentRepository);
     $this->container->has('doctrine')->willReturn(true);
     $this->container->get('doctrine')->willReturn($this->doctrine);
     $this->container->get('request')->willReturn($this->request);
     $this->container->get('donate_core.payment_method_discovery')->willReturn($this->discovery);
     $this->container->get('event_dispatcher')->willReturn($this->dispatcher);
     $this->container->get('logger')->willReturn($this->logger);
 }
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var NotifyRequest $request */
     $notification = new NotificationDetails();
     if ($request instanceof SecuredNotifyRequest) {
         $notification->setPaymentName($request->getToken()->getPaymentName());
     } else {
         $notification->setPaymentName('unknown');
     }
     $notification->setDetails($request->getNotification());
     $notification->setCreatedAt(new \DateTime());
     $this->doctrine->getManager()->persist($notification);
     $this->doctrine->getManager()->flush();
 }
Example #14
0
 /**
  * Rotates imported feeds
  *
  * @param Feed    $feed The feed to rotate imports for
  * @param integer $max  The number of imports to keep
  */
 public function rotate(Feed $feed, $max = 4)
 {
     /** @var ImportRepository $repo */
     $repo = $this->doctrine->getRepository('FMIoBundle:Import');
     $imports = $repo->findCompletedByFeed($feed);
     if (sizeof($imports) <= $max) {
         return;
     }
     $manager = $this->doctrine->getManager();
     foreach (array_slice($imports, $max) as $import) {
         $this->eventDispatcher->dispatch(IoEvents::IMPORT_ROTATE, new ImportEvent($import));
         $manager->remove($import);
         $manager->flush();
     }
 }
 /**
  * @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);
 }
Example #16
0
 /**
  * @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();
 }
Example #17
0
 /**
  * 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));
 }
 /**
  * @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);
 }
Example #19
0
 /**
  * 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;
 }
 /**
  * Prepares EntityManager, reset it if closed with error
  */
 protected function ensureEntityManagerReady()
 {
     $this->em = $this->registry->getManager();
     if (!$this->em->isOpen()) {
         $this->registry->resetManager();
         $this->ensureEntityManagerReady();
     }
 }
 /**
  * @param LifecycleEventArgs
  */
 public function prePersist(LifecycleEventArgs $args)
 {
     $build = $args->getEntity();
     if (!$build instanceof Build || $build->isPullRequest()) {
         return;
     }
     $em = $this->doctrine->getManager();
     $branch = $this->doctrine->getRepository('Model:Branch')->findOneByProjectAndName($build->getProject(), $build->getRef());
     if (!$branch) {
         $this->logger->info('creating non-existing branch', ['project' => $build->getProject()->getId(), 'branch' => $build->getRef()]);
         $branch = new Branch();
         $branch->setName($build->getRef());
         $branch->setProject($build->getProject());
         $em->persist($branch);
     }
     $build->setBranch($branch);
 }
 /**
  * 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;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (empty($options['locales'])) {
         throw new \LogicException('The translation editor requires at least a single locale specified.');
     }
     $prototype = $builder->create($options['prototype_name'], $options['type'], $options['options']);
     // Translation data sort listener is used to sort and add missing entities in the list based on the locales.
     $translationDataSorter = new \Nercury\TranslationEditorBundle\Form\Listener\TranslationDataSortListener($options['locale_field_name'], $prototype->getDataClass(), $options['locales'], $options['null_locale_enabled'], $this->doctrine->getManager(), $options['auto_remove_ignore_fields']);
     $builder->addEventSubscriber($translationDataSorter);
     // Resize form listener is used to create forms for each collection entity.
     if (defined('Symfony\\Component\\Form\\FormEvents::POST_SUBMIT')) {
         $resizeListener = new ResizeFormListener($options['type'], $options['options'], false, false);
     } else {
         $resizeListener = new ResizeFormListener($builder->getFormFactory(), $options['type'], $options['options'], false, false);
     }
     $builder->addEventSubscriber($resizeListener);
 }
Example #24
0
 /**
  * @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;
 }
 /**
  * {@inheritDoc}
  */
 public function onPreExecute(Context $context)
 {
     /** @var Notify $request */
     $request = $context->getRequest();
     if (false == $request instanceof Notify) {
         return;
     }
     if (in_array($request, $this->processedRequests)) {
         return;
     }
     $this->processedRequests[] = $request;
     $notification = new NotificationDetails();
     $request->getToken() ? $notification->setGatewayName($request->getToken()->getGatewayName()) : $notification->setGatewayName('unknown');
     $notification->setDetails($_REQUEST);
     $notification->setCreatedAt(new \DateTime());
     $this->doctrine->getManager()->persist($notification);
     $this->doctrine->getManager()->flush();
 }
Example #26
0
 /**
  * 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;
 }
 /**
  * createQueryBuilder.
  *
  * @param AutocompleteContextInterface $context
  *
  * @return \Doctrine\ORM\QueryBuilder
  */
 protected function createQueryBuilder(AutocompleteContextInterface $context)
 {
     $dqlParts = $context->getParameter('dql_parts');
     $qb = $this->doctrine->getManager()->createQueryBuilder();
     if (!empty($dqlParts)) {
         foreach ($dqlParts as $name => $parts) {
             if (!empty($parts)) {
                 if (is_object($parts)) {
                     $parts = clone $parts;
                 }
                 $qb->add($name, $parts);
             }
         }
     } else {
         $qb->select('s')->from($context->getParameter('class'), 's');
     }
     return $qb;
 }
 /**
  * @return \Gedmo\Translatable\TranslatableListener
  */
 protected function getTranslatableListener()
 {
     foreach ($this->doctrine->getManager()->getEventManager()->getListeners() as $event => $listeners) {
         foreach ($listeners as $hash => $listener) {
             if ($listener instanceof TranslatableListener) {
                 return $this->listener = $listener;
             }
         }
     }
 }
 /**
  * @param string $entity
  *
  * @return DatatableData A DatatableData instance
  */
 public function getDatatable($entity)
 {
     /**
      * Get all GET params
      *
      * @var \Symfony\Component\HttpFoundation\ParameterBag $parameterBag
      */
     $parameterBag = $this->request->query;
     $params = $parameterBag->all();
     /**
      * @var \Doctrine\ORM\Mapping\ClassMetadata $metadata
      */
     $metadata = $this->doctrine->getManager()->getClassMetadata($entity);
     /**
      * @var \Doctrine\ORM\EntityManager $em
      */
     $em = $this->doctrine->getManager();
     return new DatatableData($params, $metadata, $em, $this->serializer, $this->logger);
 }
 /**
  * {@inheritDoc}
  */
 public function onPreExecute($request)
 {
     if (false == $request instanceof NotifyRequest) {
         return;
     }
     if (in_array($request, $this->processedRequests)) {
         return;
     }
     /** @var NotifyRequest $request */
     $notification = new NotificationDetails();
     if ($request instanceof SecuredNotifyRequest) {
         $notification->setPaymentName($request->getToken()->getPaymentName());
     } else {
         $notification->setPaymentName('unknown');
     }
     $notification->setDetails($request->getNotification());
     $notification->setCreatedAt(new \DateTime());
     $this->doctrine->getManager()->persist($notification);
     $this->doctrine->getManager()->flush();
 }