Example #1
0
 public function loadUserByOAuthUserResponse(UserResponseInterface $response)
 {
     $name = $response->getRealName();
     $email = $response->getEmail();
     $clientId = $response->getUsername();
     $token = $response->getAccessToken();
     $user = $this->doctrine->getRepository('UserUserBundle:Users')->findOneByOAuthUser($clientId);
     /** @var Users $user */
     if (!$user) {
         $service = $response->getResourceOwner()->getName();
         $setter = 'set' . ucfirst($service);
         $setterId = $setter . "Id";
         $setterToken = $setter . 'AccessToken';
         $user = new Users();
         $user->setRealname($name);
         $user->setUsername($email);
         $user->{$setterId}($clientId);
         $user->{$setterToken}($token);
         $user->setPassword(sha1($clientId));
         $roles = $this->doctrine->getRepository('UserUserBundle:Roles')->findOneBy(['role' => 'ROLE_USER']);
         $user->addRole($roles);
         $this->doctrine->getManager()->persist($user);
         $this->doctrine->getManager()->flush();
         $userId = $user->getId();
     } else {
         $userId = $user->getId();
     }
     if (!$userId) {
         throw new UsernameNotFoundException('Возникла проблема добавления или определения пользователя');
     }
     return $this->loadUserByUsername($userId);
 }
Example #2
0
 public function update(Worker $worker)
 {
     /** @var EntityManager $em */
     $em = $this->doctrine->getManager();
     $exception = null;
     $i = 0;
     while ($i < 5) {
         try {
             $worker = $this->getWorker(['queue' => $worker->getQueue(), 'instance' => $worker->getInstance(), 'host' => $worker->getHost()]);
             $em->persist($worker);
             $em->flush();
             return;
         } catch (\Exception $e) {
             // the connection might have "gone away"
             $this->logger->warning("Error while updating worker entity", ['message' => $e->getMessage()]);
             $exception = $e;
             $this->doctrine->resetManager();
             $em = $this->doctrine->getManager();
             $em->getConnection()->close();
             $em->getConnection()->connect();
         }
         $i++;
     }
     throw new ApplicationException("Unable to update worker entity", $exception);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->doctrine = $this->getContainer()->get('doctrine');
     // get all cities
     $qb = $this->doctrine->getManager()->createQueryBuilder();
     $qb->select('ct')->from('HelperBundle:City', 'ct')->where('ct.geoCityId IS NOT NULL')->orderBy('ct.id', 'ASC');
     $cities = $qb->getQuery()->getResult();
     $connection = $this->doctrine->getConnection();
     foreach ($cities as $city) {
         $output->write('Updating data of old city #' . $city->getId());
         $sql = "SELECT cg_gct.* FROM `chromedia_global`.`geo_cities` cg_gct WHERE cg_gct.`id` = ?";
         $statement = $connection->prepare($sql);
         $statement->bindValue(1, $city->getGeoCityId());
         $statement->execute();
         $globalCityData = $statement->fetch();
         if ($globalCityData) {
             $updateSql = "UPDATE `cities` SET `id` = :geoCityId, `name` = :geoCityName, `slug` = :geoCitySlug WHERE `old_id` = :oldId";
             $updateStatement = $connection->prepare($updateSql);
             $updateStatement->bindValue('geoCityId', $globalCityData['id']);
             $updateStatement->bindValue('geoCityName', $globalCityData['name']);
             $updateStatement->bindValue('geoCitySlug', $globalCityData['slug']);
             $updateStatement->bindValue('oldId', $city->getOldId());
             $updateStatement->execute();
             $output->writeln(' OK');
         } else {
             $output->writeln(' Not found');
         }
     }
 }
 /**
  * @return EntityManager
  */
 private function getEntityManager()
 {
     if (!$this->doctrine) {
         $this->doctrine = $this->container->get('doctrine');
     }
     return $this->doctrine->getManager($this->entityManagerName);
 }
 /**
  * Dispatch a covoit using database alerts.
  * Find matching alerts, create notifications and send them.
  *
  * @param Covoit $covoit
  */
 public function dispatch(Covoit $covoit)
 {
     /** @var EntityManager $em */
     $em = $this->doctrine->getManager();
     /*
      * We find all the alerts and try to match these objects with the covoit. However, as the number of result could
      * be big, we use some simple conditions to limit results : he startCity, the endCity and the price. Matching
      * date is difficult directly in SQL as the condition depends of which fields are filled.
      */
     /** @var CovoitAlert[] $alerts */
     $alerts = $em->createQueryBuilder()->select('a, s, e, u')->from('EtuModuleCovoitBundle:CovoitAlert', 'a')->leftJoin('a.startCity', 's')->leftJoin('a.endCity', 'e')->leftJoin('a.user', 'u')->where('a.startCity = :startCiy OR a.startCity IS NULL')->andWhere('a.endCity = :endCity OR a.endCity IS NULL')->andWhere('a.priceMax <= :price OR a.priceMax IS NULL')->setParameters(['startCiy' => $covoit->getStartCity()->getId(), 'endCity' => $covoit->getEndCity()->getId(), 'price' => $covoit->getPrice()])->getQuery()->getResult();
     // Notifications - Send only one notification per user, even if covoit match several alerts
     $notifications = [];
     foreach ($alerts as $alert) {
         if ($this->match($alert, $covoit)) {
             $notif = $this->createNotification($covoit);
             $notif->setEntityId($alert->getId());
             $notif->setAuthorId($covoit->getAuthor()->getId());
             $notifications[$alert->getUser()->getId()] = $notif;
         }
     }
     // Send the notifications
     foreach ($notifications as $notification) {
         $this->sender->send($notification);
     }
 }
 /**
  * @param string $entityType
  * @param integer $entityId
  * @param User $user
  * @return bool
  */
 public function unsubscribe(User $user, $entityType, $entityId)
 {
     /** @var $em EntityManager */
     $em = $this->doctrine->getManager();
     $em->createQueryBuilder()->delete('EtuCoreBundle:Subscription', 's')->andWhere('s.entityId = :entityId')->andWhere('s.entityType = :entityType')->andWhere('s.user = :user')->setParameter('entityType', $entityType)->setParameter('entityId', $entityId)->setParameter('user', $user->getId())->getQuery()->execute();
     return true;
 }
 private function getInstitutionsWithNoState()
 {
     $qb = $this->doctrine->getManager()->createQueryBuilder();
     $qb->select('inst')->from('InstitutionBundle:Institution', 'inst')->where('inst.state IS NULL');
     $result = $qb->getQuery()->getResult();
     return $result;
 }
 /**
  * @param string $blockName
  * @param array  $options
  * @param string $default
  * @return string
  */
 public function contentBlock($blockName, $options = array(), $default = null)
 {
     $em = $this->doctrine->getManager();
     $repository = $em->getRepository('GlavwebContentBlockBundle:ContentBlock');
     $contentBlock = $repository->findOneByName($blockName);
     $tag = isset($options['tag']) ? $options['tag'] : 'div';
     $attr = isset($options['attr']) ? $options['attr'] : array();
     if (isset($options['class'])) {
         $attr['class'] = $options['class'];
     }
     if (isset($options['href'])) {
         $attr['href'] = $options['href'];
     }
     if (!$contentBlock) {
         $contentBlock = new ContentBlock();
         $contentBlock->setName($blockName);
         $contentBlock->setBody($default ? $default : $blockName);
         $em->persist($contentBlock);
         $em->flush();
     }
     $contentEditable = '';
     $dataBlockName = '';
     $isEditable = $this->request && $this->request->get('contenteditable') && $this->securityContext->isGranted('ROLE_ADMIN');
     if ($isEditable) {
         $contentEditable = ' contenteditable="true"';
         $dataBlockName = ' data-block-name="' . $blockName . '"';
         $attr['class'] = isset($attr['class']) ? $attr['class'] . ' js-content-block' : 'js-content-block';
     }
     $attrParts = array();
     foreach ($attr as $attrName => $value) {
         $attrParts[] = sprintf('%s="%s"', $attrName, $value);
     }
     return '<' . $tag . ' ' . implode(' ', $attrParts) . ' ' . $contentEditable . $dataBlockName . '>' . $contentBlock->getBody() . '</' . $tag . '>';
 }
Example #9
0
 public function __construct(Registry $doctrine, Session $session, Logger $logger, Parameters $parameters)
 {
     $this->doctrine = $doctrine;
     $this->session = $session;
     $this->logger = $logger;
     $this->parameters = $parameters;
     $this->emFrom = $this->doctrine->getManager($this->parameters->getManagerFrom());
     $this->emTo = $this->doctrine->getManager($this->parameters->getManagerTo());
     $fromRetriever = new PgRetriever($doctrine, $this->logger, $this->parameters->getManagerFrom());
     $fromRetriever->setIndexType(PgRetriever::INDEX_TYPE_NAME);
     //$toRetriever = new PgRetriever($doctrine, $this->logger, $this->parameters->getManagerTo() );
     //$toRetriever->setIndexType(PgRetriever::INDEX_TYPE_NAME);
     $this->fromAnalyzer = new PgAnalyzer($this->logger, $fromRetriever);
     //$this->toAnalyzer = new PgAnalyzer($this->logger, $toRetriever);
     if ($this->session->has(CompareStructure::SESSION_FROM_KEY)) {
         $this->fromAnalyzer->setSchemas($this->session->get(CompareStructure::SESSION_FROM_KEY));
         $this->fromAnalyzer->initTables();
     } else {
         throw new SyncException('No source data');
     }
     /*if($this->session->has(CompareStructure::SESSION_TO_KEY)){
           $this->toAnalyzer->setSchemas($this->session->get(CompareStructure::SESSION_TO_KEY));
           $this->toAnalyzer->initTables();
       }else{
           throw new SyncException('No targeted data');
       }*/
 }
 private function expireRegistrationApplication(RegistrationApplication $registrationApplication)
 {
     $registrationApplication->setExpireAt(null);
     $em = $this->doctrine->getManager();
     $em->persist($registrationApplication);
     $em->flush();
 }
 /**
  * @param Ticket $ticket
  */
 protected function startAutoReply(Ticket $ticket)
 {
     $ticketText = $ticket->getSubject() . ' ' . $ticket->getDescription();
     $repository = $this->registry->getManager()->getRepository('DiamanteDeskBundle:Article');
     $results = [];
     /** @var Article $article */
     foreach ($repository->findByStatus(1) as $article) {
         $articleText = $article->getTitle() . ' ' . $article->getContent();
         $results[$article->getId()] = $this->compare($ticketText, $articleText);
     }
     $maxResult = max($results);
     /**
      * TODO: should be configured by admin
      */
     if ($maxResult < 3) {
         return;
     }
     $articleId = array_search(max($results), $results);
     /**
      * TODO: should be extracted from previous call of $repository->getAll()
      */
     $article = $repository->find($articleId);
     /**
      * TODO: should be extracted from configuration???
      */
     $user = User::fromString('oro_1');
     $content = $this->getAutoReplayNoticeHtml() . $article->getContent();
     $comment = new Comment($content, $ticket, $user, false);
     $this->registry->getManager()->persist($comment);
     $this->uow->computeChangeSet($this->em->getClassMetadata($comment->getClassName()), $comment);
     /**
      * TODO: should be executed workflowEven?
      */
 }
 /**
  * @param UserEmailOrigin $origin
  *
  * @return string
  */
 public function getAccessTokenWithCheckingExpiration(UserEmailOrigin $origin)
 {
     $expiresAt = $origin->getAccessTokenExpiresAt();
     $utcTimeZone = new \DateTimeZone('UTC');
     $now = new \DateTime('now', $utcTimeZone);
     $token = $origin->getAccessToken();
     //if token had been expired, the new one must be generated and saved to DB
     if ($now > $expiresAt && $this->configManager->get('oro_imap.enable_google_imap')) {
         $parameters = ['refresh_token' => $origin->getRefreshToken(), 'grant_type' => 'refresh_token'];
         $attemptNumber = 0;
         do {
             $attemptNumber++;
             $response = $this->doHttpRequest($parameters);
             if (!empty($response['access_token'])) {
                 $token = $response['access_token'];
                 $origin->setAccessToken($token);
                 $newExpireDate = new \DateTime('+' . $response['expires_in'] . ' seconds', $utcTimeZone);
                 $origin->setAccessTokenExpiresAt($newExpireDate);
                 $this->doctrine->getManager()->persist($origin);
                 $this->doctrine->getManager()->flush();
             }
         } while ($attemptNumber <= self::RETRY_TIMES && empty($response['access_token']));
     }
     return $token;
 }
 public function postTask(Worker $worker, array $options = null)
 {
     if ($worker instanceof DoctrineAwareWorker) {
         if ($this->doctrine) {
             $this->doctrine->getManager()->clear();
         }
     }
 }
 private static function initKernel()
 {
     static::$kernel = static::createKernel();
     static::$kernel->boot();
     static::$container = static::$kernel->getContainer();
     static::$doctrine = static::$container->get('doctrine');
     static::$om = static::$doctrine->getManager();
 }
 /**
  * @param object $entity
  *
  * @return string|null
  */
 public function getEntityIdentifier($entity)
 {
     if (!$this->doctrine instanceof Registry) {
         return null;
     }
     $ids = $this->doctrine->getManager()->getClassMetadata(get_class($entity))->getIdentifierValues($entity);
     return $ids ? self::IDENTIFIER_PREFIX . implode(self::IDENTIFIER_SEPARATOR, $ids) : null;
 }
 /**
  * @param object|null $owner
  *
  * @return RecipientEntity|null
  */
 protected function createRecipientEntity($owner = null)
 {
     if (!$owner) {
         return null;
     }
     $metadata = $this->registry->getManager()->getClassMetadata(ClassUtils::getClass($owner));
     return $this->emailRecipientsHelper->createRecipientEntity($owner, $metadata);
 }
 private function clearServers()
 {
     // clear all dockercloud servers in database
     $allServers = $this->doctrine->getManager()->getRepository('KeboolaProvisioningBundle:Server\\Docker')->findAll();
     foreach ($allServers as $server) {
         $this->doctrine->getManager()->remove($server);
     }
     $this->doctrine->getManager()->flush();
 }
Example #18
0
 /**
  * Create Entities
  * @param $object
  * @param $amount number of entities
  */
 public function createEntities($object, $amount)
 {
     $em = $this->doctrine->getManager();
     for ($i = 0; $i < $amount; $i++) {
         $tmpObj = $this->cloneService->cloneObject($object);
         $em->persist($tmpObj);
         $em->flush();
     }
 }
Example #19
0
 /**
  * @param User $user
  * @return int
  */
 public function getUnseen(User $user)
 {
     if (!$user->getLastSeenAction()) {
         return 0;
     }
     $em = $this->registry->getManager();
     $count = $em->createQuery('SELECT COUNT(a) FROM AppBundle:Action a WHERE a.budget IN (:budgets) AND a.user != :user AND a.id > :last')->setParameter('budgets', $user->getBudgets())->setParameter('user', $user)->setParameter('last', $user->getLastSeenAction()->getId())->getSingleScalarResult();
     return $count;
 }
 /**
  * {@inheritdoc}
  */
 public function iterate(IterateEvent $event)
 {
     if (!method_exists($event->getIterator(), 'isBufferEmpty')) {
         throw new \LogicException('You can\'t use DoctrineOptimizeListener with this iterator');
     }
     if ($event->getIterator()->isBufferEmpty()) {
         $this->doctrine->getManager()->getUnitOfWork()->clear();
     }
 }
 /**
  * @param Ticket $ticket
  * @param User $user
  */
 public function addWatcher(Ticket $ticket, User $user)
 {
     $watcher = $this->watcherListRepository->findOne($ticket, $user);
     if (!$watcher) {
         $this->doctrineRegistry->getManager()->merge($ticket);
         $watcher = new WatcherList($ticket, $user);
         $this->watcherListRepository->store($watcher);
     }
 }
Example #22
0
 /**
  * @dataProvider autoCompleteHandlerProvider
  * @param boolean $active
  * @param string $handlerName
  */
 public function testAutoCompleteHandler($active, $handlerName, $query)
 {
     $user = $this->registry->getRepository('OroUserBundle:User')->findOneBy(['username' => 'simple_user2']);
     $user->setEnabled($active);
     $this->registry->getManager()->flush();
     $this->client->request('GET', $this->getUrl('oro_email_mailbox_users_search', ['organizationId' => $user->getOrganization()->getId()]), array('page' => 1, 'per_page' => 10, 'name' => $handlerName, 'query' => $query));
     $result = $this->client->getResponse();
     $arr = $this->getJsonResponseContent($result, 200);
     $this->assertCount((int) $active, $arr['results']);
 }
 /**
  * Fill template engine context with informations about current page.
  *
  * @param GenericEvent $event
  */
 public function onRoutePage(GenericEvent $event)
 {
     $em = $this->registryManager->getManager();
     $page = $em->getRepository('SWP\\ContentBundle\\Model\\Page')->getById($event->getArguments()['pageId'])->getArrayResult();
     if (count($page)) {
         $page[0]['route_name'] = $event->getArguments()['route_name'];
         $this->context->setCurrentPage($page[0]);
     }
     return;
 }
Example #24
0
 /**
  * @param mixed $context
  */
 protected function executeAction($context)
 {
     /** @var Job $job */
     $job = $this->contextAccessor->getValue($context, $this->job);
     /** @var Job $dependency */
     $dependency = $this->contextAccessor->getValue($context, $this->dependency);
     $job->addDependency($dependency);
     $job->setState(Job::STATE_PENDING);
     $this->doctrine->getManager()->persist($job);
     $this->doctrine->getManager()->flush();
 }
 /**
  * @return array
  */
 public function getList()
 {
     $response = [];
     $qb = $this->registry->getManager()->getRepository('OroUserBundle:User')->createQueryBuilder('u');
     $users = $this->aclHelper->apply($qb)->getResult();
     /** @var User $user */
     foreach ($users as $user) {
         $response[] = ['id' => $user->getId(), 'name' => $user->getFullName()];
     }
     return $response;
 }
Example #26
0
 /**
  * Indexes single bundle.
  *
  * @param Bundle $bundle
  */
 public function indexBundle(Bundle $bundle)
 {
     $update = $this->solarium->createUpdate();
     $document = $update->createDocument();
     $this->updateDocumentFromBundle($document, $bundle, $update->getHelper());
     $update->addDocument($document);
     $update->addCommit();
     $this->solarium->update($update);
     $bundle->setIndexedAt(new \DateTime());
     $this->doctrine->getManager()->flush();
 }
 /**
  * Processes email bodies using processes provided in MailboxProcessProviders.
  * Processes are triggered using this listener instead of normal triggers.
  * Processes are triggered for new email bodies and email bodies of emails newly bound to some mailbox.
  *
  * @param PostFlushEventArgs $args
  */
 public function postFlush(PostFlushEventArgs $args)
 {
     if (empty($this->emailBodies)) {
         return;
     }
     $emailBodies = $this->emailBodies;
     $this->emailBodies = [];
     foreach ($emailBodies as $emailBody) {
         $this->scheduleProcess($emailBody);
     }
     $this->doctrine->getManager()->flush();
 }
Example #28
0
 /**
  * @param FormInterface $form
  * @param Request       $request
  *
  * @return mixed|FormInterface
  */
 public function handle(FormInterface $form, Request $request)
 {
     $method = $request->getMethod();
     $form->submit($request, 'PATCH' !== $method);
     if ($form->isSubmitted() && $form->isValid()) {
         $entity = $form->getData();
         $this->registry->getManager()->persist($entity);
         $this->registry->getManager()->flush();
         return $entity;
     }
     return $form;
 }
Example #29
0
 /**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('title')->add('description')->add('query', new QueryForm(), ["label" => false])->add("config", new ChartConfig($this->doctrine, $this->options), ["label" => false])->add('cronExpression', 'hidden')->add('directory', "hidden")->add('Save', 'submit', array('label' => 'Save Query', 'attr' => ['class' => 'btn-save btn btn-sm']));
     $builder->get('directory')->addModelTransformer(new DirectoryTransformer($this->doctrine->getManager()));
     $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $formEvent) {
         $form = $formEvent->getForm();
         /** @var QueryRequest $qr */
         $qr = $formEvent->getData();
         if (isset($qr)) {
             $form->add('delete', 'button', ['label' => 'Delete', 'attr' => ['class' => 'btn btn-delete btn-sm']]);
         }
     });
 }
 /**
  * Set options from configuration
  *
  * @param array $options Options
  */
 public function setOptions($options)
 {
     $this->options = $options;
     if (isset($this->options['dsn'])) {
         $this->pdoDriver = new DsnQuery($this->options);
     } else {
         if (isset($this->options['connection'])) {
             $this->pdoDriver = new DefaultQuery($this->doctrine->getManager($this->options['connection']));
         } else {
             $this->pdoDriver = new DefaultQuery($this->doctrine->getManager());
         }
     }
 }