rollback() public method

Performs a rollback on the underlying database connection.
Deprecation: Use {@link getConnection}.rollback().
public rollback ( )
 /**
  * @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 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 #3
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);
 }
 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()]);
 }
 /**
  * @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;
 }
 /**
  * @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;
     }
 }
 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 #8
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 #9
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;
 }
 public static function rollback(EntityManager $entityManager)
 {
     if ($entityManager->getConnection()->isTransactionActive()) {
         //This place tried to commit without an active transaction
         $entityManager->rollback();
         $entityManager->beginTransaction();
     }
 }
 /**
  * {@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 #16
0
 /**
  * Comita as alterações/inserções para o banco de dados.
  *
  * Por padrão o Doctrine2 não comita
  *
  * @return bool
  */
 public function flush()
 {
     try {
         $this->manager->flush();
     } catch (\Exception $e) {
         $this->manager->rollback();
         Error::log($e);
         return false;
     }
     return true;
 }
Beispiel #17
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();
 }
 /**
  * {@inheritdoc}
  */
 public function write(array $items)
 {
     try {
         $this->em->beginTransaction();
         foreach ($items as $item) {
             $this->em->persist($item);
         }
         $this->em->flush();
         $this->em->commit();
         $configuration = $this->contextRegistry->getByStepExecution($this->stepExecution)->getConfiguration();
         if (empty($configuration[EntityWriter::SKIP_CLEAR])) {
             $this->em->clear();
         }
     } catch (\Exception $exception) {
         $this->em->rollback();
         $this->ensureEntityManagerReady();
         $jobName = $this->stepExecution->getJobExecution()->getJobInstance()->getAlias();
         $event = new WriterErrorEvent($items, $jobName, $exception);
         $this->eventDispatcher->dispatch(WriterErrorEvent::NAME, $event);
         if ($event->getCouldBeSkipped()) {
             $importContext = $this->contextRegistry->getByStepExecution($this->stepExecution);
             $importContext->setValue('error_entries_count', (int) $importContext->getValue('error_entries_count') + count($items));
             $importContext->addError($event->getWarning());
             if ($event->getException() === $exception) {
                 // exception are already handled and job can move forward
                 throw new InvalidItemException($event->getWarning(), []);
             } else {
                 // exception are already created and ready to be rethrown
                 throw $event->getException();
             }
         } else {
             throw $exception;
         }
     }
     $this->eventDispatcher->dispatch(WriterAfterFlushEvent::NAME, new WriterAfterFlushEvent($this->em));
 }
Beispiel #20
0
 public function insert(array $params)
 {
     try {
         $class = new $this->entity_name();
         $entity = $this->setData($class, $params);
         $this->_em->persist($entity);
         $this->_em->flush();
         $this->_em->clear();
         return $this->get($entity->getId());
     } catch (Exception $e) {
         ErrorModel::addError(array('code' => 'no_insert_this_data', 'message' => 'Not insert this data'));
         ErrorModel::addError(array('code' => $e->getCode(), 'message' => $e->getMessage()));
         $this->_em->rollback();
     }
 }
Beispiel #21
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 #22
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 #23
0
 /**
  * 
  * @param EntityManager $em
  * @throws Exception
  */
 public function install(EntityManager $em)
 {
     try {
         $grupo = $em->find('Novosga\\Model\\Grupo', 1);
         $em->beginTransaction();
         $em->persist($this->create(_('Unidade Padrão'), _('Novo SGA'), $grupo));
         $em->commit();
         $em->flush();
     } catch (Exception $e) {
         try {
             $em->rollback();
         } catch (Exception $ex) {
         }
         throw $e;
     }
 }
Beispiel #24
0
 /**
  * @param $id
  * @param $username
  * @return DBALException|\Exception|null|object
  */
 public function updateUser($id, $username)
 {
     $this->entityManager->beginTransaction();
     try {
         $user = $this->userRepository->find($id);
         $user->setUsername($username);
         $user->setEmail($username);
         $this->entityManager->persist($user);
         $this->entityManager->flush();
         $this->entityManager->commit();
         return $user;
     } catch (DBALException $e) {
         $this->entityManager->rollback();
         return $e;
     }
 }
Beispiel #25
0
 /**
  * @param Annee $annee
  * @param UploadedFile $fichier
  * @param array $erreurs
  * @return number
  */
 public function importAdherents($annee, $fichier, &$erreurs)
 {
     $this->em->beginTransaction();
     try {
         $nbLignes = 0;
         $handle = fopen($fichier->getRealPath(), "r");
         $headers = fgetcsv($handle);
         while ($data = fgetcsv($handle)) {
             if (count($data) != 10) {
                 array_push($erreurs, $this->translator->trans('patlenain_gas.adherent.import.erreur.nombreChampsIncorrect', array('%ligne%' => $nbLignes + 1)));
             } else {
                 $adherent = new Adherent();
                 $adherent->setNom($data[0]);
                 $adherent->setPrenom($data[1]);
                 $adherent->setEmail($data[2]);
                 $adherent->setAdresse($data[3]);
                 $adherent->setCodePostal($data[4]);
                 $adherent->setVille($data[5]);
                 $adherent->setNumeroFixe($data[6]);
                 $adherent->setNumeroPortable($data[7]);
                 $dateNaissance = DateTime::createFromFormat("d/m/Y", $data[8]);
                 $adherent->setDateNaissance($dateNaissance);
                 $dateAdhesion = null;
                 if ($data[9]) {
                     $dateAdhesion = DateTime::createFromFormat("d/m/Y", $data[9]);
                 }
                 $adherent->setDateNaissance($dateNaissance);
                 $adherent->setAnnee($annee);
                 $this->em->persist($adherent);
             }
             $nbLignes++;
         }
         if (count($erreurs) > 0) {
             $this->em->rollback();
         } else {
             $this->em->commit();
         }
         fclose($handle);
     } catch (\Exception $e) {
         $this->em->rollback();
         fclose($handle);
         throw $e;
     }
     return $nbLignes;
 }
 /**
  * {@inheritDoc}
  */
 public function update($id, $data)
 {
     $data = $this->convertData($data);
     $repository = $this->entityManager->getRepository($this->getEntityClass());
     $entity = $repository->find($id);
     $hydrator = new DoctrineObject($this->entityManager, true);
     $entity = $hydrator->hydrate((array) $data, $entity);
     $this->entityManager->beginTransaction();
     try {
         $this->entityManager->persist($entity);
         $this->entityManager->flush($entity);
         $this->entityManager->commit();
     } catch (Exception $e) {
         $this->entityManager->rollback();
         return new ApiProblem(500, $e);
     }
     return $entity;
 }
Beispiel #27
0
 /**
  * @param EntityManager $em
  *
  * @throws Exception
  */
 public function install(EntityManager $em)
 {
     try {
         $em->beginTransaction();
         $em->persist($this->create(_('Sem prioridade'), _('Atendimento normal'), 0));
         $em->persist($this->create(_('Portador de Deficiência'), _('Atendimento prioritáro para portadores de deficiência'), 1));
         $em->persist($this->create(_('Gestante'), _('Atendimento prioritáro para gestantes'), 1));
         $em->persist($this->create(_('Idoso'), _('Atendimento prioritáro para idosos'), 1));
         $em->persist($this->create(_('Outros'), _('Qualquer outra prioridade'), 1));
         $em->commit();
         $em->flush();
     } catch (Exception $e) {
         try {
             $em->rollback();
         } catch (Exception $ex) {
         }
         throw $e;
     }
 }
 /**
  * @param ConfigurationEntryInterface $entry
  */
 public function save(ConfigurationEntryInterface $entry)
 {
     if (!$entry instanceof ConfigurationEntry) {
         throw new InvalidArgumentException('$entry must be an instance of ' . ConfigurationEntry::clazz());
     }
     $this->em->beginTransaction();
     try {
         if ($this->uniquityValidator) {
             if (!$this->uniquityValidator->isValidForSaving($entry)) {
                 throw new ConfigurationEntryAlreadyExistsException(sprintf('Configuration property with name "%s" already exists.', $entry->getName()));
             }
         }
         $this->em->persist($entry);
         $this->em->flush($entry);
     } catch (\Exception $e) {
         $this->em->rollback();
         throw $e;
     }
     $this->em->commit();
 }
 /**
  * @inheritdoc
  */
 public function unsubscribeUser(User $user, $listId)
 {
     $driver = $this->getDriverByListId($listId);
     $this->checkDriverConfiguration($driver);
     $this->em->beginTransaction();
     try {
         $newsletter = $this->em->getRepository('NecktieNewsletterBundle:Newsletter');
         $row = $newsletter->findOneBy(['user' => $user, 'listID' => $listId]);
         if ($row) {
             $us = $driver->unsubscribe($row->getMemberID(), $listId);
             $this->em->remove($row);
             $this->em->flush();
             $this->em->commit();
             return $us;
         }
     } catch (\Exception $ex) {
         $this->em->rollback();
         $this->logger->addWarning($ex);
     }
     return null;
 }
Beispiel #30
0
 /**
  * рефанд всех показов с площадок заданного паблишера
  *
  * @param User $publisher
  */
 public function refundAllFromPublisher(User $publisher)
 {
     $platforms = $this->em->getRepository('VifeedPlatformBundle:Platform')->findByUserIndexed($publisher, true);
     $chargePublisherSum = 0;
     $payAdvertiserSum = 0;
     if ($platforms) {
         $userRepo = $this->em->getRepository('VifeedUserBundle:User');
         $filter = $this->em->getFilters()->getFilter('softdeleteable');
         $filter->disableForEntity('Vifeed\\CampaignBundle\\Entity\\Campaign');
         $refundGroups = $this->em->getRepository('VifeedPaymentBundle:VideoViewPayment')->createQueryBuilder('p')->select('IDENTITY(c.user) user_id, SUM(p.charged) charged, SUM(p.paid) paid, COUNT(v.id) paid_views')->innerJoin('p.videoView', 'v')->innerJoin('v.campaign', 'c')->where('v.platform IN (:platforms)')->groupBy('user_id')->setParameter('platforms', $platforms)->getQuery()->getResult();
         $filter->enableForEntity('Vifeed\\CampaignBundle\\Entity\\Campaign');
         $this->em->beginTransaction();
         try {
             foreach ($refundGroups as $refundGroup) {
                 $advertiser = $this->em->getReference('VifeedUserBundle:User', $refundGroup['user_id']);
                 $userRepo->updateBalance($advertiser, $refundGroup['charged']);
                 $chargePublisherSum += $refundGroup['paid'];
                 $payAdvertiserSum += $refundGroup['charged'];
             }
             $userRepo->updateBalance($publisher, -$chargePublisherSum);
             $this->em->getRepository('VifeedVideoViewBundle:VideoView')->createQueryBuilder('v')->update('VifeedVideoViewBundle:VideoView', 'v')->set('v.isPaid', ':isPaid')->set('v.isInStats', ':isInStats')->where('v.platform IN (:platforms)')->setParameters(['platforms' => $platforms, 'isPaid' => false, 'isInStats' => false])->getQuery()->execute();
             $this->em->getRepository('VifeedPaymentBundle:VideoViewPayment')->createQueryBuilder('p')->delete('VifeedPaymentBundle:VideoViewPayment', 'p')->where('p.videoView IN (select v from VifeedVideoViewBundle:VideoView v where v.platform IN (:platforms))')->setParameter('platforms', $platforms)->getQuery()->execute();
             // пересчитываем количество показов и просмотров
             // todo: можно оптимизировать - считать только кампании выбранных юзеров
             $sqlQuery = 'UPDATE campaign c
                  SET c.total_views = (SELECT COUNT(1) FROM video_views v WHERE v.campaign_id = c.id AND v.is_in_stats=1),
                      c.paid_views = (SELECT COUNT(1) FROM video_views v WHERE v.campaign_id = c.id AND v.is_in_stats=1 AND v.is_paid=1)';
             $this->em->getConnection()->executeQuery($sqlQuery);
             $this->em->commit();
         } catch (\Exception $e) {
             $this->em->rollback();
             throw $e;
         }
     }
     return ['charged' => $chargePublisherSum, 'paid' => $payAdvertiserSum];
 }