/** * The actual listener, will store the objects in the database * * @param IndexUpdateEvent $event */ public function onIndexUpdate(IndexUpdateEvent $event) { $objects = $event->getObjects(); foreach ($objects as $indexItem) { $this->em->merge($indexItem); } $this->em->flush(); }
/** * @param string $id * @param string|int|float $value * @return void */ public function merge($id, $value) { $entity = $this->createEntity(); $entity->setId($id); $entity->setContent(is_array($value) ? serialize($value) : $value); $entity->setIsSerialized(is_array($value)); $this->em->merge($entity); }
/** * @param Ticket $ticket * @param User $user */ public function addWatcher(Ticket $ticket, User $user) { $watcher = $this->watcherListRepository->findOne($ticket, $user); if (!$watcher) { $ticket = $this->em->merge($ticket); $watcher = new WatcherList($ticket, $user); $this->watcherListRepository->store($watcher); } }
/** * Get the currently logged in user * * @throws AccessDeniedHttpException When no currently logged in user exists in the session * * @return User */ public function getUser() { $user = $this->tokenStorage->getToken()->getUser(); if (!$user instanceof User) { $this->session->getFlashBag()->add(self::ERROR_TYPE, self::ERROR_MESSAGE); throw new AccessDeniedHttpException(self::ERROR_MESSAGE); } return $this->entityManager->merge($user); }
/** * @param string $key * @param mixed $value */ public function set($key, $value) { $config = $this->getConfig($key); $object = new \stdClass(); $object->Value = $value; $config->setValue($object); $this->em->merge($config); $this->em->flush(); }
/** * * @param Hanking $entity * @return boolean|Hanking */ public function update(Hanking $entity) { try { $this->manager->merge($entity); $this->manager->flush(); return $entity; } catch (Exception $ex) { return false; } }
/** * @return Comunidad|mixed|null|object * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException */ public function get() { if ($this->comunidad instanceof Comunidad) { return $this->comunidad; } if ($this->session->has('comunidad')) { $comunidad = $this->session->get('comunidad'); $this->comunidad = $this->em->merge($comunidad); return $this->comunidad; } return null; }
/** * @Template * * @param Request $request * @param Question $question * @param string $answer * @return array */ public function detailAction(Request $request, Question $question, $answer = null) { /** @var User $currentUser */ $currentUser = $this->entityManager->merge($this->loginUser->getUser()); if ($answer) { $correct = $answer == $question->getCorrectAnswer(); $consumption = new QuestionAnswer($currentUser, $question, $correct); $this->entityManager->persist($consumption); $this->entityManager->flush(); return new RedirectResponse($this->urlGenerator->generate('home')); } return ['question' => $question]; }
/** * @Template * * @param Request $request * @return array */ public function consumptionAction(Request $request) { /** @var User $currentUser */ $currentUser = $this->entityManager->merge($this->loginUser->getUser()); $users = $this->userRepository->findAllExceptUser($currentUser); $receiverId = $request->query->get('receiver_id'); $receiver = $this->userRepository->findOneById($receiverId); if ($receiver) { $consumption = new Consumption($currentUser, $receiver); $this->entityManager->persist($consumption); $this->entityManager->flush(); return new RedirectResponse($this->urlGenerator->generate('question_detail', ['id' => $this->questionRepository->findOneRandom()->getId()])); } return ['users' => $users]; }
/** * @param \Scribe\Doctrine\ORM\Mapping\Entity|mixed $entity * @param mixed $index * * @throws \Exception * * @return $this */ protected function loadAndMergeEntity($index, $entity) { try { $entityMetadata = $this->getClassMetadata($this->getEntityFQCN()); $this->identLog[] = $identity = $entityMetadata->getIdentifierValues($entity); if (count($identity) > 0) { $identity = [key($identity) => current($identity)]; } elseif (!$entity->hasIdentity()) { OutBuffer::stat('+y/b-preload +y/i-[warns]+w/- import could not begin for "%s:%d"', basename($this->metadata->getName()), $index); OutBuffer::stat('+y/b-preload +y/i-[warns]+w/- import strategy "merge" unavailable due to failed identifier map resolution'); } $repository = $this->manager->getRepository($this->getEntityFQCN()); $entitySearched = $repository->findOneBy($identity); $this->manager->initializeObject($entitySearched); if ($entitySearched && !$entity->isEqualTo($entitySearched)) { $mapper = new HydratorManager(new HydratorMapping(true)); $entity = $mapper->getMappedObject($entity, $entitySearched); $this->manager->remove($entitySearched); $this->manager->merge($entity); $this->manager->persist($entity); $this->manager->flush(); $this->manager->clear(); ++$this->countUpdate; return $this; } elseif ($entitySearched && $entity->isEqualTo($entitySearched)) { $entity = $entitySearched; ++$this->countSkip; return $this; } $this->loadAndPersistEntity($entity); } catch (\Exception $e) { throw $e; } return $this; }
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(); }
/** * Add unsigned parameters, such as: * - databases (this list is also signed but presented here for listing to unauthenticated clients) * - parameters, extra info you may attach to object as necessary * * @param AuthenticationSuccessEvent $event */ public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event) { $data = $event->getData(); $AuthUser = $event->getUser(); if (!$AuthUser instanceof AuthUser) { throw new AccessDeniedException('AuthUser object not found'); } if (!in_array('ROLE_USER', $AuthUser->getRoles())) { throw new AccessDeniedException('User lacks necessary role'); } $AuthUser->setLastToken($data['token']); $AuthUser = $this->entityManager->merge($AuthUser); $this->entityManager->persist($AuthUser); $this->entityManager->flush(); $data['databases'] = $this->getDatabaseArray($event->getUser()); $data['parameters'] = $this->getParametersArray($event->getUser()); $event->setData($data); }
/** * @param mixed $entity * @param bool $flush */ public function merge($entity, $flush = null) { if ($entity !== null) { $this->entityManager->merge($entity); } if ($flush) { $this->entityManager->flush(); } }
public function update(\Entity\Usuario $usuario) { try { $this->em->merge($usuario); $this->em->flush(); } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage() . ' - usuario_dao::update '); } }
/** * Efetua o merge do model atual com o banco de dados persistindo os dados editados. * * @param Model $model */ public function merge(Model $model) { try { $this->manager->merge($model); } catch (\Exception $e) { Error::log($e); return false; } return true; }
/** * 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(); }
private function save(&$obj) { //Because we cascade all operations, we need //to do the correct operations based on detached or not. $state = $this->entityManager->getUnitOfWork()->getEntityState($obj); if ($state == UnitOfWork::STATE_DETACHED) { $this->entityManager->merge($obj); } else { $this->entityManager->persist($obj); } $this->entityManager->flush(); }
/** * @param $stack_id * @param $collection_id * @param $collection_version_id * @param $block_id */ private function persist($stack_id, $collection_id, $collection_version_id, $block_id) { $search = ['block_id' => $block_id]; if (!($record = $this->repository->findOneBy($search))) { $record = new StackUsageRecord(); } $record->setCollectionId($collection_id); $record->setCollectionVersionId($collection_version_id); $record->setBlockId($block_id); $record->setStackId($stack_id); $this->manager->merge($record); }
/** * Пересчитываем итоговую сумму платежа по всем билетам * с учетом скидки * * @param Payment $payment * @param Event $event */ public function checkTicketsPricesInPayment($payment, $event) { // Вытягиваем скидку из конфига $paymentsConfig = $this->container->getParameter('stfalcon_event.config'); $discount = (double) $paymentsConfig['discount']; $eventCost = $event->getCost(); /** @var Ticket $ticket */ foreach ($payment->getTickets() as $ticket) { // получаем оплаченые платежи пользователя $paidPayments = $this->repository->findPaidPaymentsForUser($ticket->getUser()); //правильно ли установлен флаг наличия скидки // @todo с расчетом скидки у нас явно проблемы. ниже почти такой же код идет. плюс ещё в нескольких // местах по коду делаем подобные расчеты. плюс в самой модели билета есть логика расчета цены со скидкой... $isCorrectDiscount = $ticket->getHasDiscount() == (count($paidPayments) > 0 && $event->getUseDiscounts() || $ticket->hasPromoCode()); // если цена билета без скидки не ровна новой цене на ивент // или неверно указан флаг наличия скидки if ($ticket->getAmountWithoutDiscount() != $eventCost || !$isCorrectDiscount) { // если не правильно установлен флаг наличия скидки, тогда устанавливаем его заново if (!$isCorrectDiscount) { // @todo для реализации возможности отключения скидки постоянных участников мне пришлось // использовать метод $event->getUseDiscounts() в трех разных местах. а нужно, чтобы // это можно было сделать в одном месте $ticket->setHasDiscount(count($paidPayments) > 0 && $event->getUseDiscounts() || $ticket->hasPromoCode()); } $ticket->setAmountWithoutDiscount($eventCost); if ($ticket->getHasDiscount()) { $ticket->setAmountWithDiscount($discount); } else { $ticket->setAmount($eventCost); } $this->entityManager->merge($ticket); } } $payment->recalculateAmount(); //set base price $payment->setBaseAmount($payment->getAmount()); $this->entityManager->merge($payment); $this->flush(); }
/** * 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(); }
/** * @param $file_id * @param $collection_id * @param $collection_version_id * @param $block_id * @return bool */ private function persist($file_id, $collection_id, $collection_version_id, $block_id) { $search = ['collection_id' => $collection_id, 'collection_version_id' => $collection_version_id, 'block_id' => $block_id, 'file_id' => $file_id]; if ($this->repository->findOneBy($search)) { return false; } $record = new FileUsageRecord(); $record->setCollectionId($collection_id); $record->setCollectionVersionId($collection_version_id); $record->setBlockId($block_id); $record->setFileId($file_id); $this->manager->merge($record); }
/** * @param AbstractType $type * @return \Symfony\Component\Form\Form */ public function getFiltersForm($type) { if ($this->getRequest()->request->get('reset')) { $this->getRequest()->getSession()->set($type->getName() . '.filters', array()); } $filters = $this->getRequest()->getSession()->get($type->getName() . '.filters', array()); if (is_array($filters)) { foreach ($filters as $key => $filter) { if (is_object($filter)) { $filters[$key] = $this->entityManager->merge($filter); } } } $filters_form = $this->formFactory->create($type, $filters); if (!$this->getRequest()->request->get('reset')) { $filters_form->handleRequest($this->getRequest()); if ($filters_form->isValid()) { $filters = $filters_form->getData(); $this->getRequest()->getSession()->set($type->getName() . '.filters', $filters); } } return $filters_form; }
private function getAccessToken(User $user) { $currentTime = new \DateTime(); $accessToken = $user->getAccessToken(); if ($currentTime >= $user->getExpireTime()) { $accessTokenData = json_decode($user->getAccessTokenData()); $tokenResponse = $this->refreshToken($accessTokenData->refresh_token); $accessToken = $tokenResponse->access_token; $currentTime->add(new \DateInterval("PT3600S")); $user->setAccessToken($accessToken); $user->setExpireTime($currentTime); $user->setAccessTokenData(json_encode($tokenResponse)); $this->entityManager->merge($user); $this->entityManager->flush(); } return $accessToken; }
/** * @param ScheduledCommand $scheduledCommand * @param OutputInterface $output * @param InputInterface $input */ private function executeCommand(ScheduledCommand $scheduledCommand, OutputInterface $output, InputInterface $input) { $scheduledCommand = $this->em->merge($scheduledCommand); $scheduledCommand->setLastExecution(new \DateTime()); $scheduledCommand->setLocked(true); $this->em->flush(); try { $command = $this->getApplication()->find($scheduledCommand->getCommand()); } catch (\InvalidArgumentException $e) { $scheduledCommand->setLastReturnCode(-1); $output->writeln('<error>Cannot find ' . $scheduledCommand->getCommand() . '</error>'); return; } $input = new ArrayInput(array_merge(array('command' => $scheduledCommand->getCommand(), '--env' => $input->getOption('env')), $scheduledCommand->getArguments(true))); // Use a StreamOutput or NullOutput to redirect write() and writeln() in a log file if (false === $this->logPath && "" != $scheduledCommand->getLogFile()) { $logOutput = new NullOutput(); } else { $logOutput = new StreamOutput(fopen($this->logPath . $scheduledCommand->getLogFile(), 'a', false), $this->commandsVerbosity); } // Execute command and get return code try { $output->writeln('<info>Execute</info> : <comment>' . $scheduledCommand->getCommand() . ' ' . $scheduledCommand->getArguments() . '</comment>'); $result = $command->run($input, $logOutput); } catch (\Exception $e) { $logOutput->writeln($e->getMessage()); $logOutput->writeln($e->getTraceAsString()); $result = -1; } if (false === $this->em->isOpen()) { $output->writeln('<comment>Entity manager closed by the last command.</comment>'); $this->em = $this->em->create($this->em->getConnection(), $this->em->getConfiguration()); } $scheduledCommand = $this->em->merge($scheduledCommand); $scheduledCommand->setLastReturnCode($result); $scheduledCommand->setLocked(false); $scheduledCommand->setExecuteImmediately(false); $this->em->flush(); /* * This clear() is necessary to avoid conflict between commands and to be sure that none entity are managed * before entering in a new command */ $this->em->clear(); unset($command); gc_collect_cycles(); }
public function save(\Doctrine\ORM\EntityManager $entityManager) { $data = $this->getData(); $type = $entityManager->find('Admin\\Entity\\TemplateType', $data['type']); $template = $entityManager->getRepository('Admin\\Entity\\EmailTemplates')->findOneBy(array('type' => $type, 'language' => $data['language'])); // If template exist update content, if not create new one if ($template) { $template->setData($data); $template->setTemplateType($type); $entityManager->merge($template); } else { $data['createdTime'] = new \DateTime('now'); $newTemplate = new EmailTemplates(); $newTemplate->setData($data); $newTemplate->setTemplateType($type); $entityManager->persist($newTemplate); } $entityManager->flush(); }
/** * @param object $target * @param bool $flush * @return object * @throws \DomainException */ public function save($target, $flush = false) { if (!$target instanceof $this->entityClass) { throw new \DomainException(sprintf('Entity must be instance of `%s`.', $this->entityClass)); } if ($target instanceof IdProviderInterface && $target->getId()) { $target = $this->entityManager->merge($target); } else { if (isset($target->id) && $target->id) { $this->entityManager->merge($target); } else { $this->entityManager->persist($target); } } if ($flush) { $this->flush(); } return $target; }
public function insertUpdateProcessing(EntityManager $em, $data, $blockid = null) { $update = !is_null($blockid); //If insert mode, creates new instance if ($update) { $block = $em->find('Model\\ContentBlock', $blockid); } else { $block = new ContentBlock(); } //Update instance values $block->setName($data['name']); $block->setDescription($data['description']); $block->setBlockStyleClassName($_POST['blockStyleClassName']); $block->setBgurl($data['bgurl']); $block->setBgred(intval($data['bgred'])); $block->setBggreen(intval($data['bggreen'])); $block->setBgblue(intval($data['bgblue'])); $block->setBgopacity(floatval($data['bgopacity'])); $bgrepeatx = isset($data['bckrepeatx']) && !(strlen($data['bckrepeatx']) <= 0 || $data['bckrepeatx'] == 'false'); $bgrepeaty = isset($data['bckrepeaty']) && !(strlen($data['bckrepeaty']) <= 0 || $data['bckrepeaty'] == 'false'); $block->setBgrepeatx($bgrepeatx); $block->setBgrepeaty($bgrepeaty); $block->setBgsize($data['bgsize']); if (strlen($data['content']) > 0) { $block->setContent($data['content']); } try { $em->beginTransaction(); if ($update) { $em->merge($block); } else { $em->persist($block); } $em->flush(); $em->commit(); } catch (\Exception $e) { $em->rollback(); throw $e; } return $block->getId(); }
/** * @param User $user * @param PageEleveur $commitingPageEleveur * @return PageEleveur * @throws HistoryException */ public function commit(User $user, PageEleveur $commitingPageEleveur) { /** @var PageEleveurCommit $clientHead */ $clientHead = $this->pageEleveurCommitRepository->find($commitingPageEleveur->getHead()); /** @var PageEleveurBranch $pageEleveurBranch */ $pageEleveurBranch = $this->pageEleveurBranchRepository->find($commitingPageEleveur->getId()); if (!$pageEleveurBranch || !$clientHead) { throw new HistoryException(HistoryException::BRANCHE_INCONNUE); } if ($pageEleveurBranch->getOwner()->getId() !== $user->getId()) { throw new HistoryException(HistoryException::DROIT_REFUSE); } if ($clientHead->getId() !== $pageEleveurBranch->getCommit()->getId()) { throw new HistoryException(HistoryException::NON_FAST_FORWARD); } $managedActialites = []; if ($commitingPageEleveur->getActualites() !== null) { foreach ($commitingPageEleveur->getActualites() as $actualite) { if ($actualite->hashCode() !== $actualite->getId()) { // l'actualité a été modifiée, on doit persister la nouvelle version $this->doctrine->persist($actualite); } else { // L'actualité n'a pas changé $actualite = $this->doctrine->merge($actualite); } array_push($managedActialites, $actualite); } } $newCommit = new PageEleveurCommit($clientHead, $commitingPageEleveur->getNom(), $commitingPageEleveur->getDescription(), $commitingPageEleveur->getEspeces(), $commitingPageEleveur->getRaces(), $commitingPageEleveur->getLieu(), $commitingPageEleveur->getAnimaux() !== null ? array_map(function (PageAnimal $pageAnimal) use($user) { if ($pageAnimal->getOwner()->getId() !== $user->getId()) { throw new HistoryException(HistoryException::DROIT_REFUSE); } return $this->pageAnimalBranchRepository->find($pageAnimal->getId()); }, $commitingPageEleveur->getAnimaux()) : [], $managedActialites); $this->doctrine->persist($newCommit); $pageEleveurBranch->setCommit($newCommit); $this->doctrine->flush([$newCommit, $pageEleveurBranch]); $pageEleveur = $this->fromBranch($this->findAtCommit($commitingPageEleveur->getId(), $newCommit->getId())); return $pageEleveur; }
private function insertUpdateProcessing(EntityManager $em, $data, $id = null) { $update = !is_null($id); try { $em->beginTransaction(); if ($update) { $gallery = $em->getRepository('Plugin\\Gallery\\Model\\Gallery')->find($id); } else { $gallery = new Gallery(); } if ($update) { foreach ($gallery->getPhotos()->toArray() as $item) { $em->remove($item); } } $gallery->setName($data['name']); $gallery->setDescription($data['description']); $gallery->setDataGallery($data['dataGallery']); $gallery->setThumbImage($data['thumbImage']); if ($update) { $em->merge($gallery); } else { $em->persist($gallery); } $em->flush(); for ($i = 0; $i < count($data['photos']['imageUrl']); $i++) { $photo = new GalleryItem(); $photo->setImageUrl($data['photos']['imageUrl'][$i]); $photo->setPhotoOrder($data['photos']['order'][$i]); $gallery->addPhoto($photo); } $em->merge($gallery); $em->flush(); $em->commit(); } catch (\Exception $e) { $em->rollback(); throw $e; } return $gallery->getId(); }
private function insertUpdateProcessing(EntityManager $em, $data, $id = null) { $update = !is_null($id); try { $em->beginTransaction(); //Create or retrive entity if ($update) { $menu = $em->find('Model\\Menu', $id); } else { $menu = new Menu(); } //If update mode delete all items on db if ($update) { foreach ($menu->getChildren() as $child) { $em->remove($child); } } $menu->setName($data['menu_name']); $menu->setDescription($data['menu_description']); if ($update) { $em->merge($menu); } else { $em->persist($menu); } $em->flush(); $items = $this->processMenu($data, $menu->getId(), array()); foreach ($items as $item) { $menu->addMenuItem($item); } $em->merge($menu); $em->flush(); $em->commit(); } catch (\Exception $e) { $em->rollback(); throw $e; } return $menu->getId(); }