beginTransaction() public method

Starts a transaction on the underlying database connection.
Deprecation: Use {@link getConnection}.beginTransaction().
public beginTransaction ( )
 /**
  * @param Channel $channel
  * @param string  $entity
  *
  * @throws \Exception
  */
 protected function fillChannelToEntity(Channel $channel, $entity)
 {
     $interfaces = class_implements($entity) ?: [];
     if (!in_array('OroCRM\\Bundle\\ChannelBundle\\Model\\ChannelAwareInterface', $interfaces)) {
         return;
     }
     /** @var QueryBuilder $qb */
     $qb = $this->em->getRepository($entity)->createQueryBuilder('e');
     $iterator = new BufferedQueryResultIterator($qb);
     $writeCount = 0;
     $toWrite = [];
     try {
         $this->em->beginTransaction();
         /** @var ChannelAwareInterface $data */
         foreach ($iterator as $data) {
             $writeCount++;
             if (!$data->getDataChannel()) {
                 $channelReference = $this->em->getReference(ClassUtils::getClass($channel), $channel->getId());
                 $data->setDataChannel($channelReference);
                 $toWrite[] = $data;
             }
             if (0 === $writeCount % static::BATCH_SIZE) {
                 $this->write($toWrite);
                 $toWrite = [];
             }
         }
         if (count($toWrite) > 0) {
             $this->write($toWrite);
         }
         $this->em->commit();
     } catch (\Exception $exception) {
         $this->em->rollback();
         throw $exception;
     }
 }
 public function groupMembershipAction()
 {
     /** @var AccountInterface $account */
     $account = $this->entityManager->getRepository(AccountInterface::class)->find($this->bodyParam('account'));
     if (!$account) {
         return new ApiProblem(404, 'The account could not be found.');
     }
     /** @var Group $group */
     $group = $this->entityManager->getRepository(Group::class)->find($this->bodyParam('group'));
     if (!$group) {
         return new ApiProblem(404, 'The group could not be found.');
     }
     if ($this->getRequest()->getMethod() === 'POST' && !$account->getGroups()->contains($group)) {
         $account->getGroups()->add($group);
     } elseif ($this->getRequest()->getMethod() === 'DELETE' && $account->getGroups()->contains($group)) {
         $account->getGroups()->removeElement($group);
     }
     try {
         $this->entityManager->beginTransaction();
         $this->entityManager->persist($account);
         $this->entityManager->flush();
         $this->entityManager->commit();
     } catch (Exception $e) {
         $this->entityManager->rollback();
         return new ApiProblemResponse(new ApiProblem(500, $e->getMessage(), null, null, ['exception' => $e]));
     }
     return new ViewModel(['group' => $group->getId(), 'account' => $account->getId()]);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->em = $this->container->getDoctrine()->getManager();
     /* @var $em EntityManager */
     $this->em->beginTransaction();
     $entities = array('CmsAuthentication:User', 'CmsAuthentication:Group', 'Cms:ApplicationLocalizationParameter', 'Cms:BlockPropertyMetadata', 'Cms:ReferencedElement\\ReferencedElementAbstract', 'Cms:BlockProperty', 'Cms:Abstraction\\Block', 'Cms:Abstraction\\PlaceHolder', 'Cms:LocalizationTag', 'Cms:Abstraction\\Localization', 'Cms:Abstraction\\RedirectTarget', 'Cms:PageLocalizationPath', 'Cms:Page', 'Cms:EditLock', 'Cms:TemplateLayout', 'Cms:Template', 'Cms:FileProperty', 'Cms:ImageSize', 'Cms:Image', 'Cms:File', 'Cms:Folder', 'Cms:FilePath');
     if ($input->getOption('clear')) {
         foreach ($entities as $entity) {
             //todo: also clean audit tables here
             $this->em->createQueryBuilder()->delete($entity)->getQuery()->execute();
         }
     }
     $dataFile = $this->container->getParameter('directories.project_root') . DIRECTORY_SEPARATOR . $input->getArgument('filename');
     if (!is_file($dataFile)) {
         throw new \RuntimeException(sprintf('The file [%s] does not exists.', $dataFile));
     }
     $this->dataDir = dirname($dataFile);
     //todo: validate it
     $data = Yaml::parse(file_get_contents($dataFile));
     //we need to maintain creation order
     $sections = array('group', 'user', 'image', 'template', 'page', 'pageLocalization');
     foreach ($sections as $section) {
         foreach ($data[$section] as $name => $definition) {
             $this->createEntity($section, $name, $definition);
         }
     }
     $this->em->flush();
     $this->em->commit();
 }
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Migrating translations...');
     $this->setEntityManager($this->getContainer()->get('doctrine.orm.entity_manager'));
     /* @var EntityRepository $repo */
     $repo = $this->em->getRepository('KunstmaanTranslatorBundle:Translation');
     /**
      * @var QueryBuilder $qb
      */
     $qb = $repo->createQueryBuilder('t');
     $uniqueTranslations = $qb->select('t.domain,t.keyword')->distinct()->where('t.translationId IS NULL')->getQuery()->getArrayResult();
     $this->em->beginTransaction();
     try {
         foreach ($uniqueTranslations as $uniqueTranslation) {
             // Fetch new unique translation ID & update records
             $newId = $repo->getUniqueTranslationId();
             // Update translations...
             $qb->update()->set('t.translationId', $newId)->where('t.domain = :domain')->andWhere('t.keyword = :keyword')->setParameter('domain', $uniqueTranslation['domain'])->setParameter('keyword', $uniqueTranslation['keyword'])->getQuery()->execute();
         }
         $this->em->commit();
         $output->writeln('<info>' . count($uniqueTranslations) . ' translations have been migrated.</info>');
     } catch (\Exception $e) {
         $this->em->rollback();
         $output->writeln('An error occured while migrating translations : <error>' . $e->getMessage() . '</error>');
     }
 }
Beispiel #5
0
 /**
  * Persists data into DB in single transaction
  *
  * @param string $locale
  * @param array  $data translations strings, format same as MassageCatalog::all() returns
  *
  * @throws \Exception
  */
 public function persist($locale, array $data)
 {
     $writeCount = 0;
     try {
         $this->em->beginTransaction();
         foreach ($data as $domain => $domainData) {
             foreach ($domainData as $key => $translation) {
                 if (strlen($key) > MySqlPlatform::LENGTH_LIMIT_TINYTEXT) {
                     continue;
                 }
                 $writeCount++;
                 $this->toWrite[] = $this->getTranslationObject($key, $locale, $domain, $translation);
                 if (0 === $writeCount % $this->batchSize) {
                     $this->write($this->toWrite);
                     $this->toWrite = [];
                 }
             }
         }
         if (count($this->toWrite) > 0) {
             $this->write($this->toWrite);
         }
         $this->em->commit();
     } catch (\Exception $exception) {
         $this->em->rollback();
         throw $exception;
     }
     // update timestamp in case when persist succeed
     $this->metadataCache->updateTimestamp($locale);
 }
 /**
  * {@inheritDoc}
  */
 protected function setUp()
 {
     self::bootKernel(array('environment' => 'test'));
     $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
     $this->em->beginTransaction();
     $this->repository = $this->em->getRepository("AppBundle:User");
 }
Beispiel #7
0
 public function stopLogEntry(User $user, LogEntry $logEntry)
 {
     $this->em->beginTransaction();
     $this->stopActiveLogEntriesByUser($user);
     $this->logEntryRepository->save($logEntry);
     $this->em->flush();
     $this->em->commit();
 }
 private function updateReferencesInTransaction()
 {
     $this->entityManager->beginTransaction();
     $this->retrieveCurrentReferencesIds();
     $this->updateBannersProbabilities();
     $this->removeUnusedReferences();
     $this->entityManager->commit();
 }
 public function setUp()
 {
     static::$kernel = static::createKernel();
     static::$kernel->boot();
     $this->em = static::$kernel->getContainer()->get('doctrine.orm.entity_manager');
     $this->em->beginTransaction();
     $this->repo = $this->em->getRepository("BdEWeiBundle:Config");
 }
 /**
  * настройки теста
  */
 protected function setUp()
 {
     $kernel = static::createKernel();
     $kernel->boot();
     $this->_em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
     $this->_em->beginTransaction();
     $this->root = dirname($kernel->getRootDir());
     $this->copyUnitTestEntity = $this->root . '/src/Acme/DemoBundle/Entity/UnitTestEntity.php';
 }
Beispiel #11
0
 /**
  * Sets task as users default task
  *
  * @param Task $task
  * @param User $user
  */
 public function setTaskAsDefault(Task $task, User $user)
 {
     $this->em->beginTransaction();
     $defaultTask = $this->taskRepository->findUserDefaultTask($user->getId());
     $defaultTask->setDefault(false);
     $task->setDefault(true);
     $this->taskRepository->update($task);
     $this->em->flush();
     $this->em->commit();
 }
 public function setUp()
 {
     parent::setUp();
     //HTTP client
     $this->client = static::createClient();
     //Service container
     $this->container = $this->client->getContainer();
     //Begin SQL transaction to rollback it
     $this->em = $this->container->get('doctrine.orm.default_entity_manager');
     $this->em->beginTransaction();
 }
 /**
  * @param string $jobType
  * @param string $jobName
  * @param array $configuration
  * @return JobResult
  */
 public function executeJob($jobType, $jobName, array $configuration = array())
 {
     // create and persist job instance and job execution
     $jobInstance = new JobInstance(self::CONNECTOR_NAME, $jobType, $jobName);
     $jobInstance->setCode($this->generateJobCode($jobName));
     $jobInstance->setLabel(sprintf('%s.%s', $jobType, $jobName));
     $jobInstance->setRawConfiguration($configuration);
     $jobExecution = new JobExecution();
     $jobExecution->setJobInstance($jobInstance);
     $jobResult = new JobResult();
     $jobResult->setSuccessful(false);
     $this->entityManager->beginTransaction();
     try {
         $job = $this->jobRegistry->getJob($jobInstance);
         if (!$job) {
             throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobName));
         }
         // TODO: Refactor whole logic of job execution to perform actions in transactions
         $job->execute($jobExecution);
         $failureExceptions = $this->collectFailureExceptions($jobExecution);
         if ($jobExecution->getStatus()->getValue() == BatchStatus::COMPLETED && !$failureExceptions) {
             $this->entityManager->commit();
             $jobResult->setSuccessful(true);
         } else {
             $this->entityManager->rollback();
             foreach ($failureExceptions as $failureException) {
                 $jobResult->addFailureException($failureException);
             }
         }
     } catch (\Exception $exception) {
         $this->entityManager->rollback();
         $jobExecution->addFailureException($exception);
         $jobResult->addFailureException($exception->getMessage());
     }
     // save job instance
     $this->entityManager->persist($jobInstance);
     $this->entityManager->flush($jobInstance);
     // set data to JobResult
     $jobResult->setJobId($jobInstance->getId());
     $jobResult->setJobCode($jobInstance->getCode());
     /** @var JobExecution $jobExecution */
     $jobExecution = $jobInstance->getJobExecutions()->first();
     if ($jobExecution) {
         $stepExecution = $jobExecution->getStepExecutions()->first();
         if ($stepExecution) {
             $context = $this->contextRegistry->getByStepExecution($stepExecution);
             $jobResult->setContext($context);
         }
     }
     return $jobResult;
 }
Beispiel #14
0
 /**
  * Runs all sample data providers.
  *
  * @param callable|null $callback A function that will be called with the name of each provider as a parameter.
  * @return void
  */
 public function run(callable $callback = null)
 {
     $this->em->beginTransaction();
     foreach ($this->providers as $provider) {
         $this->em->clear();
         /** @var $provider \Brick\Sample\SampleDataProvider */
         $provider = $this->injector->instantiate($provider);
         if ($callback) {
             $callback($provider->getName());
         }
         $provider->run();
         $this->em->flush();
     }
     $this->em->commit();
 }
 public function insertUpdateProcessing(EntityManager $em, $data, $id = null)
 {
     $update = !is_null($id);
     try {
         $em->beginTransaction();
         if ($update) {
             $language = $em->find('Model\\Language', $id);
         } else {
             $language = new Language();
         }
         $language->setCode($data['code']);
         $language->setDescription($data['description']);
         $language->setFlagImageURL($data['flagimageurl']);
         $menu = $em->find('Model\\Menu', $data['menuid']);
         $language->setMenu($menu);
         if ($update) {
             $em->merge($language);
         } else {
             $em->persist($language);
         }
         $em->flush();
         $em->commit();
     } catch (\Exception $e) {
         $em->rollback();
         throw $e;
     }
     return $language->getId();
 }
Beispiel #16
0
 /**
  * @param JobExecution $jobExecution
  * @param JobInstance $jobInstance
  * @return JobResult
  */
 protected function doJob(JobInstance $jobInstance, JobExecution $jobExecution)
 {
     $jobResult = new JobResult();
     $jobResult->setSuccessful(false);
     $isTransactionRunning = $this->isTransactionRunning();
     if (!$isTransactionRunning) {
         $this->entityManager->beginTransaction();
     }
     try {
         $job = $this->batchJobRegistry->getJob($jobInstance);
         if (!$job) {
             throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobInstance->getAlias()));
         }
         $job->execute($jobExecution);
         $isSuccessful = $this->handleJobResult($jobExecution, $jobResult);
         if (!$isTransactionRunning && $isSuccessful && !$this->validationMode) {
             $this->entityManager->commit();
         } elseif (!$isTransactionRunning) {
             $this->entityManager->rollback();
         }
         // trigger save of JobExecution and JobInstance
         $this->batchJobRepository->getJobManager()->flush();
         if (!$this->isClearSkipped($jobExecution)) {
             $this->batchJobRepository->getJobManager()->clear();
         }
     } catch (\Exception $exception) {
         if (!$isTransactionRunning) {
             $this->entityManager->rollback();
         }
         $jobExecution->addFailureException($exception);
         $jobResult->addFailureException($exception->getMessage());
         $this->saveFailedJobExecution($jobExecution);
     }
     return $jobResult;
 }
Beispiel #17
0
 /**
  * @param JobExecution $jobExecution
  * @param JobInstance $jobInstance
  * @return JobResult
  */
 protected function doJob(JobInstance $jobInstance, JobExecution $jobExecution)
 {
     $jobResult = new JobResult();
     $jobResult->setSuccessful(false);
     $this->entityManager->beginTransaction();
     try {
         $job = $this->batchJobRegistry->getJob($jobInstance);
         if (!$job) {
             throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobInstance->getAlias()));
         }
         $job->execute($jobExecution);
         $failureExceptions = $this->collectFailureExceptions($jobExecution);
         if ($jobExecution->getStatus()->getValue() == BatchStatus::COMPLETED && !$failureExceptions) {
             $this->entityManager->commit();
             $jobResult->setSuccessful(true);
         } else {
             $this->entityManager->rollback();
             foreach ($failureExceptions as $failureException) {
                 $jobResult->addFailureException($failureException);
             }
         }
     } catch (\Exception $exception) {
         $this->entityManager->rollback();
         $jobExecution->addFailureException($exception);
         $jobResult->addFailureException($exception->getMessage());
     }
     return $jobResult;
 }
 /**
  * @param EmailBodyAdded $event
  *
  * @throws \Exception
  */
 public function updateActivityDescription(EmailBodyAdded $event)
 {
     $this->entityManager->beginTransaction();
     try {
         $email = $event->getEmail();
         $activityList = $this->chainProvider->getUpdatedActivityList($email, $this->entityManager);
         if ($activityList) {
             $this->entityManager->persist($activityList);
             $this->entityManager->flush();
         }
         $this->entityManager->commit();
     } catch (\Exception $e) {
         $this->entityManager->rollback();
         throw $e;
     }
 }
 /**
  * {@inheritDoc}
  */
 public function handle(MassActionHandlerArgs $args)
 {
     $data = $args->getData();
     $massAction = $args->getMassAction();
     $options = $massAction->getOptions()->toArray();
     $this->entityManager->beginTransaction();
     try {
         set_time_limit(0);
         $iteration = $this->handleHeadEmails($options, $data);
         $this->handleThreadEmails($options);
         $this->entityManager->commit();
     } catch (\Exception $e) {
         $this->entityManager->rollback();
         throw $e;
     }
     return $this->getResponse($args, $iteration);
 }
 /**
  * {@inheritDoc}
  */
 public function handle(MassActionHandlerArgs $args)
 {
     $iteration = 0;
     $entityName = null;
     $entityIdentifiedField = null;
     $results = new DeletionIterableResult($args->getResults()->getSource());
     $results->setBufferSize(self::FLUSH_BATCH_SIZE);
     // batch remove should be processed in transaction
     $this->entityManager->beginTransaction();
     try {
         // if huge amount data must be deleted
         set_time_limit(0);
         foreach ($results as $result) {
             /** @var $result ResultRecordInterface */
             $entity = $result->getRootEntity();
             if (!$entity) {
                 // no entity in result record, it should be extracted from DB
                 if (!$entityName) {
                     $entityName = $this->getEntityName($args);
                 }
                 if (!$entityIdentifiedField) {
                     $entityIdentifiedField = $this->getEntityIdentifierField($args);
                 }
                 $entity = $this->getEntity($entityName, $result->getValue($entityIdentifiedField));
             }
             if ($entity) {
                 if ($this->securityFacade->isGranted('DELETE', $entity)) {
                     $this->entityManager->remove($entity);
                     $iteration++;
                 }
                 if ($iteration % self::FLUSH_BATCH_SIZE == 0) {
                     $this->finishBatch();
                 }
             }
         }
         if ($iteration % self::FLUSH_BATCH_SIZE > 0) {
             $this->finishBatch();
         }
         $this->entityManager->commit();
     } catch (\Exception $e) {
         $this->entityManager->rollback();
         throw $e;
     }
     return $this->getResponse($args, $iteration);
 }
 /**
  * {@inheritDoc}
  */
 public function handle(MassActionMediatorInterface $mediator)
 {
     $iteration = 0;
     $entityName = null;
     $entityIdentifiedField = null;
     $results = $this->prepareIterableResult($mediator->getResults());
     $results->setBufferSize(self::FLUSH_BATCH_SIZE);
     // batch remove should be processed in transaction
     $this->entityManager->beginTransaction();
     try {
         foreach ($results as $result) {
             /** @var $result ResultRecordInterface */
             $entity = $result->getRootEntity();
             if (!$entity) {
                 // no entity in result record, it should be extracted from DB
                 if (!$entityName) {
                     $entityName = $this->getEntityName($mediator);
                 }
                 if (!$entityIdentifiedField) {
                     $entityIdentifiedField = $this->getEntityIdentifierField($mediator);
                 }
                 $entity = $this->getEntity($entityName, $result->getValue($entityIdentifiedField));
             }
             if ($entity) {
                 $this->entityManager->remove($entity);
                 $iteration++;
                 if ($iteration % self::FLUSH_BATCH_SIZE == 0) {
                     $this->entityManager->flush();
                     $this->entityManager->clear();
                 }
             }
         }
         if ($iteration % self::FLUSH_BATCH_SIZE > 0) {
             $this->entityManager->flush();
             $this->entityManager->clear();
         }
         $this->entityManager->commit();
     } catch (\Exception $e) {
         $this->entityManager->rollback();
         throw $e;
     }
     return $this->getResponse($mediator, $iteration);
 }
 /**
  * Runs static repository restriction query and stores it state into snapshot entity
  * Doctrine does not supports insert in DQL. To increase the speed of query here uses plain sql query.
  *
  * @param Segment $segment
  *
  * @throws \LogicException
  * @throws \Exception
  */
 public function run(Segment $segment)
 {
     if ($segment->getType()->getName() !== SegmentType::TYPE_STATIC) {
         throw new \LogicException('Only static segments could have snapshots.');
     }
     $entityMetadata = $this->em->getClassMetadata($segment->getEntity());
     if (count($entityMetadata->getIdentifierFieldNames()) > 1) {
         throw new \LogicException('Only entities with single identifier supports.');
     }
     $this->em->getRepository('OroSegmentBundle:SegmentSnapshot')->removeBySegment($segment);
     try {
         $this->em->beginTransaction();
         $date = new \DateTime('now', new \DateTimeZone('UTC'));
         $dateString = '\'' . $date->format('Y-m-d H:i:s') . '\'';
         if ($this->em->getConnection()->getDriver()->getName() === DatabaseDriverInterface::DRIVER_POSTGRESQL) {
             $dateString = sprintf('TIMESTAMP %s', $dateString);
         }
         $insertString = sprintf(', %d, %s ', $segment->getId(), $dateString);
         $qb = $this->dynamicSegmentQB->getQueryBuilder($segment);
         $this->applyOrganizationLimit($segment, $qb);
         $query = $qb->getQuery();
         $segmentQuery = $query->getSQL();
         $segmentQuery = substr_replace($segmentQuery, $insertString, stripos($segmentQuery, 'from'), 0);
         $fieldToSelect = 'entity_id';
         if ($entityMetadata->getTypeOfField($entityMetadata->getSingleIdentifierFieldName()) === 'integer') {
             $fieldToSelect = 'integer_entity_id';
         }
         $dbQuery = 'INSERT INTO oro_segment_snapshot (' . $fieldToSelect . ', segment_id, createdat) (%s)';
         $dbQuery = sprintf($dbQuery, $segmentQuery);
         $statement = $this->em->getConnection()->prepare($dbQuery);
         $this->bindParameters($statement, $query->getParameters());
         $statement->execute();
         $this->em->commit();
     } catch (\Exception $exception) {
         $this->em->rollback();
         throw $exception;
     }
     $segment = $this->em->merge($segment);
     $segment->setLastRun(new \DateTime('now', new \DateTimeZone('UTC')));
     $this->em->persist($segment);
     $this->em->flush();
 }
 /**
  * @param ImageResourceInterface $resource
  * @param ImageBindInterface $binder
  * @throws \Exception
  */
 public function bind(ImageResourceInterface $resource, ImageBindInterface $binder)
 {
     try {
         $this->entityManager->beginTransaction();
         $imageEntity = $resource->getEntity();
         $this->entityManager->persist($imageEntity);
         $this->entityManager->persist($binder);
         if (is_null($resource->getEntity())) {
             throw new DomainException("Could not get entity from resource,\n                                           resource not loaded correctly");
         }
         $imageEntity->setTemporary(false);
         $binder->addImage($imageEntity);
         $this->entityManager->flush($binder);
         $this->entityManager->flush($imageEntity);
         $this->entityManager->commit();
     } catch (\Exception $e) {
         $this->entityManager->rollback();
         throw $e;
     }
 }
Beispiel #24
0
 /**
  * вывести деньги
  *
  * @ApiDoc(
  *     section="Billing API",
  *     input="Vifeed\PaymentBundle\Form\WithdrawalType",
  *     output={
  *          "class"="Vifeed\PaymentBundle\Entity\Withdrawal",
  *          "groups"={"default"}
  *     },
  *     resource=true,
  *     statusCodes={
  *         201="Returned when successful",
  *         400="Returned when something is wrong",
  *         403="Returned when the user is not authorized to use this method"
  *     }
  * )
  *
  * @return Response
  */
 public function putWithdrawalAction()
 {
     $form = $this->createForm(new WithdrawalType());
     $form->submit($this->get('request'));
     if ($form->isValid()) {
         /** @var Withdrawal $withdrawal */
         $withdrawal = $form->getData();
         if ($withdrawal->getWallet()->getUser() != $this->getUser()) {
             throw new AccessDeniedHttpException('Можно вывести только на свой кошелёк');
         }
         if ($withdrawal->getAmount() > $this->getUser()->getBalance()) {
             $form->get('amount')->addError(new FormError('Недостаточно денег на балансе'));
         } else {
             $userRepo = $this->em->getRepository('VifeedUserBundle:User');
             $this->em->beginTransaction();
             $this->em->lock($this->getUser(), LockMode::PESSIMISTIC_WRITE);
             try {
                 $withdrawal->setUser($this->getUser())->setStatus(Withdrawal::STATUS_CREATED);
                 $this->em->persist($withdrawal);
                 $userRepo->updateBalance($this->getUser(), -$withdrawal->getAmount());
                 $this->em->flush();
                 $this->em->commit();
             } catch (\Exception $e) {
                 $this->em->rollback();
                 $this->em->close();
                 throw $e;
             }
             $mailer = $this->get('vifeed.mailer');
             $message = $mailer->renderMessage('VifeedPaymentBundle:Email:withdrawal.html.twig', ['withdrawal' => $withdrawal]);
             $mailer->sendMessage('Запрос на вывод средств', $message, $this->container->getParameter('withdrawal.notification.email'));
             $context = new SerializationContext();
             $context->setGroups(array('default'));
             $view = new View($withdrawal, 201);
             $view->setSerializationContext($context);
         }
     }
     if (!$form->isValid()) {
         $view = new View($form, 400);
     }
     return $this->handleView($view);
 }
 /**
  * Runs static repository restriction query and stores it state into snapshot entity
  *
  * @param Segment $segment
  *
  * @throws \LogicException
  * @throws \Exception
  */
 public function run(Segment $segment)
 {
     if ($segment->getType()->getName() !== SegmentType::TYPE_STATIC) {
         throw new \LogicException('Only static segments could have snapshots.');
     }
     $this->em->getRepository('OroSegmentBundle:SegmentSnapshot')->removeBySegment($segment);
     $qb = $this->dynamicSegmentQB->build($segment);
     $iterator = new BufferedQueryResultIterator($qb);
     $writeCount = 0;
     try {
         $this->em->beginTransaction();
         $this->em->clear(ClassUtils::getClass($segment));
         foreach ($iterator as $data) {
             // only not composite identifiers are supported
             $id = reset($data);
             $writeCount++;
             /** @var Segment $reference */
             $reference = $this->em->getReference(ClassUtils::getClass($segment), $segment->getId());
             $snapshot = new SegmentSnapshot($reference);
             $snapshot->setEntityId($id);
             $this->toWrite[] = $snapshot;
             if (0 === $writeCount % $this->batchSize) {
                 $this->write($this->toWrite);
                 $this->toWrite = [];
             }
         }
         if (count($this->toWrite) > 0) {
             $this->write($this->toWrite);
         }
         $this->em->commit();
     } catch (\Exception $exception) {
         $this->em->rollback();
         throw $exception;
     }
     $segment = $this->em->merge($segment);
     $segment->setLastRun(new \DateTime('now', new \DateTimeZone('UTC')));
     $this->em->persist($segment);
     $this->em->flush();
 }
Beispiel #26
0
 public function setUp()
 {
     $kernel = static::createKernel();
     $kernel->boot();
     set_time_limit(600);
     self::$kernel = $kernel;
     $this->em = $kernel->getContainer()->get('entity_manager');
     $this->personRepo = $kernel->getContainer()->get('person_repository');
     $this->personCategoryRepo = $kernel->getContainer()->get('personcategory_repository');
     $this->driverRepo = $kernel->getContainer()->get('driver_repository');
     $this->custodianRepo = $kernel->getContainer()->get('custodian_repository');
     $this->passengerRepo = $kernel->getContainer()->get('passenger_repository');
     $this->driverCategoryRepo = $kernel->getContainer()->get('drivercategory_repository');
     $this->absentRepo = $kernel->getContainer()->get('absent_repository');
     $this->handicapRepo = $kernel->getContainer()->get('handicap_repository');
     $this->insuranceRepo = $kernel->getContainer()->get('insurance_repository');
     $this->vehicleRepo = $kernel->getContainer()->get('vehicle_repository');
     $this->vehicleCategoryRepo = $kernel->getContainer()->get('vehiclecategory_repository');
     $this->servicePlanRepo = $kernel->getContainer()->get('serviceplan_repository');
     $this->addressRepo = $kernel->getContainer()->get('address_repository');
     $this->poiRepo = $kernel->getContainer()->get('poi_repository');
     $this->poiKeywordRepo = $kernel->getContainer()->get('poikeyword_repository');
     $this->routeRepo = $kernel->getContainer()->get('route_repository');
     $this->shiftRepo = $kernel->getContainer()->get('shift_repository');
     $this->shiftTypeRepo = $kernel->getContainer()->get('shifttype_repository');
     $this->bankHolidayRepo = $kernel->getContainer()->get('bankholiday_repository');
     $this->repeatedDrivingAssertionRepo = $kernel->getContainer()->get('repeateddrivingassertion_repository');
     $this->repeatedDrivingAssertionPlanRepo = $kernel->getContainer()->get('repeateddrivingassertionplan_repository');
     $this->zoneRepo = $kernel->getContainer()->get('zone_repository');
     $this->zonePlanRepo = $kernel->getContainer()->get('zoneplan_repository');
     $this->drivingOrderRepo = $kernel->getContainer()->get('drivingorder_repository');
     $this->repeatedDrivingOrderRepo = $kernel->getContainer()->get('repeateddrivingorder_repository');
     $this->repeatedDrivingOrderPlanRepo = $kernel->getContainer()->get('repeateddrivingorderplan_repository');
     $this->drivingMissionRepo = $kernel->getContainer()->get('drivingmission_repository');
     $this->drivingPoolRepo = $kernel->getContainer()->get('drivingpool_repository');
     $this->workingDayRepo = $kernel->getContainer()->get('workingday_repository');
     $this->workingMonthRepo = $kernel->getContainer()->get('workingmonth_repository');
     $this->userRepo = $kernel->getContainer()->get('tixi_user_repository');
     $this->roleRepo = $kernel->getContainer()->get('tixi_role_repository');
     $this->encFactory = $kernel->getContainer()->get('security.encoder_factory');
     $this->zonePlanManagement = $kernel->getContainer()->get('tixi_app.zoneplanmanagement');
     $this->dateTimeService = $kernel->getContainer()->get('tixi_api.datetimeservice');
     $this->routingMachine = $kernel->getContainer()->get('tixi_app.routingmachine');
     $this->routeManagement = $kernel->getContainer()->get('tixi_app.routemanagement');
     $this->addressManagement = $kernel->getContainer()->get('tixi_app.addressmanagement');
     $this->dispoManagement = $kernel->getContainer()->get('tixi_app.dispomanagement');
     $this->rideManagement = $kernel->getContainer()->get('tixi_app.ridemanagement');
     $this->documentManagement = $kernel->getContainer()->get('tixi_app.documentmanagement');
     $this->mailService = $kernel->getContainer()->get('tixi_app.mailservice');
     $this->em->beginTransaction();
 }
Beispiel #27
0
 /**
  * Find user with OAuth2 account or create new one and update OAuth2 tokens.
  * Persist only. Do not flush!
  *
  * @param $service
  * @param AccessToken $token
  * @param User $userData
  *
  * @return UserAggregate
  * @throws \Doctrine\ORM\NonUniqueResultException
  */
 public function persistOAuthAccount($service, AccessToken $token, User $userData)
 {
     $uid = $userData->uid;
     try {
         $user = $this->entityManager->createQueryBuilder()->select('ua')->from('Facilis\\Users\\UserAggregate', 'ua')->innerJoin('ua.oauthAccounts', 'oaa')->where('oaa.service = :service')->andWhere('oaa.uid = :uid')->setParameter('service', $service)->setParameter('uid', $uid)->setMaxResults(1)->getQuery()->getSingleResult();
     } catch (NoResultException $e) {
         $user = new UserAggregate();
     }
     $user->addOAuthAccount($service, $uid, $token->accessToken, $token->refreshToken, new \DateTime('@' . $token->expires));
     // Start the "circus"
     $this->entityManager->beginTransaction();
     // Assign identity
     $this->entityManager->persist($user);
     $this->entityManager->flush();
     // Callback must have identity assigned
     $this->onPersistOAuthAccount($user, $userData);
     // Update again
     $this->entityManager->persist($user);
     $this->entityManager->flush();
     // Commit the whole "circus"
     $this->entityManager->commit();
     return $user;
 }
Beispiel #28
0
 /**
  * @param EntityManager $em
  *
  * @throws Exception
  */
 public function install(EntityManager $em)
 {
     try {
         $em->beginTransaction();
         $em->persist($this->create(_('Administrador'), _('Administrador geral do sistema')));
         $em->commit();
         $em->flush();
     } catch (Exception $e) {
         try {
             $em->rollback();
         } catch (Exception $ex) {
         }
         throw $e;
     }
 }
Beispiel #29
0
 /**
  * 
  * @param EntityManager $em
  * @throws Exception
  */
 public function install(EntityManager $em)
 {
     try {
         $em->beginTransaction();
         $em->persist($this->create(_('Raíz'), _('Grupo Raíz')));
         $em->commit();
         $em->flush();
     } catch (Exception $e) {
         try {
             $em->rollback();
         } catch (Exception $ex) {
         }
         throw $e;
     }
 }
Beispiel #30
0
 public function formCode(Request $request = null)
 {
     return $this->formbuilder->processForm(['object' => new UserCode(), 'caption' => 'Ввести код', 'cancel_caption' => 'Отмена', 'action' => $this->action], function (Form $form) {
         $user = $this->user->getUserObject();
         $code = $form->getData()->code;
         $repo = $this->em->getRepository('AppBundle:BizAction');
         $biz_action = $repo->findOneBy(['code' => $code, 'active' => true]);
         if (is_null($biz_action)) {
             throw new \Exception('Неверный код');
         }
         $this->em->beginTransaction();
         $already_activated = !is_null($this->em->getRepository('AppBundle:UserClientActivatedAction')->findOneBy(['user' => $user, 'action' => $biz_action]));
         if ($already_activated) {
             throw new \Exception('Акция уже была активирована');
         }
         $object = new UserClientActivatedAction();
         $object->setUser($user);
         $object->setAction($biz_action);
         $object->setPrice($biz_action->getBonusBuy());
         $this->em->persist($object);
         $this->em->flush();
         $this->em->commit();
     }, $request);
 }