/** * @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()]); }
/** * 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); }
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>'); } }
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(); }
/** * 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(); }
/** * @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; }
public function testReset() { $randomConfigElement = new Config(); $randomConfigElement->setValue("AnValueWhichNotExists"); $randomConfigElement->setName("ThisNameIsUsedForTesting!"); $this->em->persist($randomConfigElement); $this->em->commit(); // $this->em->beginTransaction(); // $this->repo->resetConfiguration(); // $q=$this->repo->createQueryBuilder('c')->where("c.name = ?1")->setParameter(1,$randomConfigElement->getName())->getQuery(); // $q->useResultCache(false); // $r = $q->getArrayResult(); // $this->assertEmpty($r); }
/** * 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(); }
/** * End system, included in benchmark. */ public function end() { if ($this->requiresFlush) { $this->em->flush(); } $this->em->commit(); }
/** * @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; }
/** * @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); }
/** * @param EntityManager $em * @param array $buf * @param int $size * * @return array */ protected function processBuff(EntityManager $em, $buf, $size = self::BATCH_SIZE) { if (count($buf) > $size) { $this->flushBatch($em->getConnection(), $buf); $em->commit(); $em->beginTransaction(); $buf = []; } return $buf; }
/** * 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; } }
/** * вывести деньги * * @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(); }
/** * 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; }
/** * @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; } }
/** * {@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)); }
/** * * @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; } }
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); }
/** * Create location tables. * * @param \Doctrine\ORM\EntityManager $manager */ private function createLocationTables($manager) { // Check if tables already exist $schemaManager = $manager->getConnection()->getSchemaManager(); // Skip if location table already exist if ($schemaManager->tablesExist(['webburza_sylius_location'])) { return; } $queries = ['CREATE TABLE webburza_sylius_location (id INT AUTO_INCREMENT NOT NULL, location_type INT DEFAULT NULL, published TINYINT(1) NOT NULL, internal_name VARCHAR(255) NOT NULL, phone VARCHAR(255) DEFAULT NULL, email VARCHAR(255) DEFAULT NULL, latitude DECIMAL (10,8) DEFAULT NULL, longitude DECIMAL(10,8) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_B50D566DCDAE269 (location_type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', 'CREATE TABLE webburza_sylius_location_image (id INT AUTO_INCREMENT NOT NULL, location_id INT NOT NULL, path VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_7DC32A0A64D218E (location_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', 'CREATE TABLE webburza_sylius_location_translation (id INT AUTO_INCREMENT NOT NULL, translatable_id INT NOT NULL, name VARCHAR(255) DEFAULT NULL, slug VARCHAR(255) DEFAULT NULL, street_name VARCHAR(255) DEFAULT NULL, street_number VARCHAR(255) DEFAULT NULL, city VARCHAR(255) DEFAULT NULL, zip VARCHAR(20) DEFAULT NULL, state VARCHAR(255) DEFAULT NULL, country VARCHAR(255) DEFAULT NULL, working_hours LONGTEXT DEFAULT NULL, description LONGTEXT DEFAULT NULL, meta_keywords LONGTEXT DEFAULT NULL, meta_description LONGTEXT DEFAULT NULL, locale VARCHAR(255) NOT NULL, INDEX IDX_3B2F83722C2AC5D3 (translatable_id), UNIQUE INDEX webburza_sylius_location_translation_uniq_trans (translatable_id, locale), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', 'CREATE TABLE webburza_sylius_location_type (id INT AUTO_INCREMENT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', 'CREATE TABLE webburza_sylius_location_type_translation (id INT AUTO_INCREMENT NOT NULL, translatable_id INT NOT NULL, name VARCHAR(255) DEFAULT NULL, slug VARCHAR(255) DEFAULT NULL, locale VARCHAR(255) NOT NULL, INDEX IDX_FC2A05E12C2AC5D3 (translatable_id), UNIQUE INDEX webburza_sylius_location_type_translation_uniq_trans (translatable_id, locale), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB', 'ALTER TABLE webburza_sylius_location ADD CONSTRAINT FK_B50D566DCDAE269 FOREIGN KEY (location_type) REFERENCES webburza_sylius_location_type (id)', 'ALTER TABLE webburza_sylius_location_image ADD CONSTRAINT FK_7DC32A0A64D218E FOREIGN KEY (location_id) REFERENCES webburza_sylius_location (id) ON DELETE CASCADE', 'ALTER TABLE webburza_sylius_location_translation ADD CONSTRAINT FK_3B2F83722C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES webburza_sylius_location (id) ON DELETE CASCADE', 'ALTER TABLE webburza_sylius_location_type_translation ADD CONSTRAINT FK_FC2A05E12C2AC5D3 FOREIGN KEY (translatable_id) REFERENCES webburza_sylius_location_type (id) ON DELETE CASCADE']; $manager->beginTransaction(); foreach ($queries as $query) { $statement = $manager->getConnection()->prepare($query); $statement->execute(); } $manager->commit(); }