/** * @param array $values * @return Comment * @throws ActionFailedException */ public function save(array $values) { $numberOfComments = $this->getNumberOfComments($values['page']); $repliesReferences = $this->findRepliesReferences($values['text']); try { $this->em->beginTransaction(); // no replies references found if (empty($repliesReferences)) { $comment = new Comment($values['author'], $this->texy->process($values['text']), $values['page'], $numberOfComments + 1, $this->request->getRemoteAddress()); $this->em->persist($comment)->flush(); $this->em->commit(); return $comment; } $commentsToReply = $this->findCommentsToReply($values['page'], $repliesReferences); $values['text'] = $this->replaceReplyReferencesByAuthors($values['text'], $commentsToReply); $comment = new Comment($values['author'], $this->texy->process($values['text']), $values['page'], $numberOfComments + 1); $this->em->persist($comment); /** @var Comment $comment */ foreach ($commentsToReply as $commentToReply) { $commentToReply->addReaction($comment); $this->em->persist($commentToReply); } $this->em->flush(); $this->em->commit(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); throw new ActionFailedException(); } return $comment; }
/** * @param Url $oldUrl * @param Url $newUrl * @return void * @throws \Exception */ public function linkUrls(Url $oldUrl, Url $newUrl) { if ($oldUrl->getId() === null or $newUrl->getId() === null) { throw new UrlNotPersistedException(); } try { $this->em->beginTransaction(); $alreadyRedirectedUrls = $this->findByActualUrl($oldUrl->getId()); /** @var Url $url */ foreach ($alreadyRedirectedUrls as $url) { $url->setRedirectTo($newUrl); $this->em->persist($url); $this->cache->clean([Cache::TAGS => [$url->getCacheKey()]]); } $oldUrl->setRedirectTo($newUrl); $this->em->persist($oldUrl); $this->cache->clean([Cache::TAGS => [$oldUrl->getCacheKey()]]); $this->em->flush(); $this->em->commit(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); throw $e; } }
/** * @param SentMessage $message * @param array $recipients * @return ReceivedMessage[] * @throws \Exception */ public function sendMessage(SentMessage $message, array $recipients) { $receivedMessages = []; try { $this->em->beginTransaction(); $this->em->persist($message); foreach ($recipients as $recipient) { if (!$recipient instanceof User) { throw new InvalidArgumentException('Argument $recipients can only contains instances of ' . User::class); } $m = $receivedMessages[$recipient->getId()] = new ReceivedMessage($message, $recipient); $this->em->persist($m); //if (count($receivedMessages) % 5 === 0) { // todo // $this->em->flush(); // $this->em->clear(); //} } $this->em->flush(); $this->em->commit(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); $this->onError('Message sending failed.', $e, self::class); throw $e; } return $receivedMessages; }
/** * @param $entity1 * @param $entity2 */ private function switchEntities($entity1, $entity2) { $x = $entity1->priority; $entity1->priority = $entity2->priority; $entity2->priority = $x; $this->entityManager->persist($entity1, $entity2); $this->entityManager->flush(); }
public function addGenre(string $name) { if ($this->genreExists($name)) { return; } $genre = new Genre($name); $this->entityManager->persist($genre); $this->entityManager->flush($genre); }
private function logDb($message, $status = NULL, $consumerTitle = NULL) { $log = new RmqLogConsumer(); $log->consumerTitle = $consumerTitle; $log->message = $message; $log->status = $status; $this->em->persist($log); $this->em->flush(); }
/** * @param $albumId */ public function delete($albumId) { /** * @var Album $album */ $album = $this->albumDao->find($albumId); $album->delete(); $this->em->persist($album); $this->em->flush(); }
/** * @param string $searchString * @return Search */ public function saveSearch($searchString) { if ($search = $this->search(Strings::webalize($searchString))) { return $search; } $search = new Search($searchString); $this->entityManager->persist($search); $this->entityManager->flush($search); return $search; }
public function update($entityClass, array $items) { $position = 1; foreach ($items as $id) { $entity = $this->em->find($entityClass, $id); $entity->setPosition($position * 10); $this->em->persist($entity); $position++; } $this->em->flush(); }
/** * Save entity into DB * * @param BaseEntity $baseEntity * @return BaseEntity * @throws \Exception */ protected function saveEntity(BaseEntity $baseEntity) { $isPersisted = UnitOfWork::STATE_MANAGED === $this->entityManager->getUnitOfWork()->getEntityState($baseEntity); if ($isPersisted) { $this->entityManager->merge($baseEntity); } else { $this->entityManager->persist($baseEntity); } $this->entityManager->flush(); return $baseEntity; }
/** * Odstraneni konkretniho tagu * @param \App\Model\Entities\Tag $tag * @return boolean */ public function deleteTag(Entities\Tag $tag) { try { $this->em->remove($tag); $result = $this->em->flush(); } catch (\Doctrine\ORM\ORMException $e) { Debugger::log($e, Debugger::INFO); $result = FALSE; } return $result; }
/** * @param Entity\Event $event */ public function delete(Entity\Event $event) { foreach ($event->performances as $performance) { foreach ($performance->children as $child) { $this->em->remove($child); } $this->em->remove($performance); } $this->em->remove($event); $this->em->flush(); }
/** * @param Role $role * @throws ForeignKeyConstraintViolationException */ public function remove(Role $role) { try { $roleID = $role->getId(); $this->em->remove($role); $this->em->flush(); $this->onSuccessRoleRemoval($role, $roleID); } catch (ForeignKeyConstraintViolationException $e) { throw $e; } }
/** * @param FileEntityInterface $entity */ public function removeFile(FileEntityInterface $entity) { --$entity->joints; if ($entity->joints === 0) { $this->em->remove($entity); $this->em->flush(); $this->unlinkFile($this->uploadDir . '/' . $entity->year . '/' . $entity->month . '/' . $entity->name . '.' . $entity->extension); } else { $this->em->persist($entity); $this->em->flush(); } }
public function orderGenre(string $genreId, float $price, Address $address) { $songEntities = []; //genre order is order of random song from given genre and setting of given genre as genre to be played when queue is empty //current genre is saved as genreId in file, because it is simple and fast $genre = $this->genresManager->getGenre($genreId); $order = new Order($price, $address, $genre); $this->entityManager->persist($order); $songEntities[] = $order; $song = $this->songsManager->getRandomSong($genre); $songEntities[] = $this->orderSong($song, $order); $this->entityManager->flush($songEntities); }
private function generateAndPersistNewAddresses(int $count) { $qb = $this->entityManager->createQueryBuilder(); $qb->select('MAX(address.bip32index)')->from(Address::getClassName(), 'address'); $index = (int) $qb->getQuery()->getSingleScalarResult(); for ($i = 0; $i < $count; $i++) { list($address, $index) = $this->generateNewAddress($index); $addressEntity = new Address($address, $index); $this->entityManager->persist($addressEntity); } $this->entityManager->flush(); file_put_contents($this->newAddressesFile, true); }
/** * @param Page $page * @throws DBALException * @throws \Exception */ public function remove(Page $page) { try { $this->em->beginTransaction(); $this->removePageUrl($page); $this->em->remove($page); $this->em->flush(); $this->em->commit(); } catch (DBALException $e) { $this->closeEntityManager(); $this->logger->addError(sprintf('Article Removal Error: %s | article ID: %d | url ID: %s | exception: %s', date('Y-m-d H:i:s'), $page->getId(), isset($url) ? $url->getId() : 'NO URL', $e->getMessage())); throw $e; } }
/** * @param User $user * @throws ForeignKeyConstraintViolationException */ public function remove(User $user) { try { $this->cache->remove($user); // will be recreated if an error occur $userID = $user->getId(); $this->em->remove($user); $this->em->flush(); $this->onSuccessUserRemoval($user, $userID); } catch (ForeignKeyConstraintViolationException $e) { // todo log throw $e; } }
private function doInsert($entity) { // get entity metadata $meta = $this->em->getClassMetadata(get_class($entity)); // fields that have to be inserted $fields = $this->getUniqueAndRequiredFields($meta, $entity); // associations that have to be inserted $associations = $this->getUniqueAndRequiredAssociations($meta, $entity); // discriminator column $discriminator = $this->getDiscriminatorColumn($meta); // prepare statement && execute $this->prepareInsert($meta, array_merge($fields, $associations, $discriminator))->execute(); // assign ID to entity if ($idGen = $meta->idGenerator) { if ($idGen->isPostInsertGenerator()) { $id = $idGen->generate($this->em, $entity); $identifierFields = $meta->getIdentifierFieldNames(); $meta->setFieldValue($entity, reset($identifierFields), $id); } } // entity is now safely inserted to database, merge now $merged = $this->em->merge($entity); $this->em->flush(array($merged)); // when you merge entity, you get a new reference return $merged; }
function saveSetList($setList, $event) { $oldSetlists = $event->getSetListGroups(); foreach ($oldSetlists as $group) { $oldSetListItems = $group->getSetListItems(); $this->em->remove($oldSetListItems); } $this->em->remove($oldSetlists); $this->em->flush(); $setListGroup = new \App\Model\Entity\SetListGroup(); $setListGroup->setName('Program'); $setListGroup->setEvent($event); foreach ($setList as $day) { foreach ($day->times as $dayItem) { $setListItem = new \App\Model\Entity\setListItem(); $setListItem->setDateTime(\DateTime::createFromFormat('Y-m-d H:i', $day->day . ' ' . $dayItem->time)); $setListItem->setName($dayItem->name); $setListItem->setDescription($dayItem->description); $setListItem->setType('item'); $setListItem->setSetListGroup($setListGroup); $this->em->persist($setListItem); $setListGroup->addSetListItem($setListItem); } } $this->em->persist($setListGroup); $event->addSetListGroup($setListGroup); return $this->saveEvent($event); }
/** * @param Listing $baseListing * @param Listing $listingToMerge * @param array $selectedCollisionItems * @param User $ownerOfOutputListing * @return Listing * @throws NoCollisionListingItemSelectedException * @throws \Exception */ public function mergeListings(Listing $baseListing, Listing $listingToMerge, array $selectedCollisionItems = [], User $ownerOfOutputListing) { if (!$this->haveListingsSamePeriod($baseListing, $listingToMerge)) { throw new RuntimeException('Given Listings must have same Period(Year and Month).'); } try { $this->em->beginTransaction(); $items = $this->itemsService->getMergedListOfItems($this->listingItemsReader->findListingItems($baseListing->getId()), $this->listingItemsReader->findListingItems($listingToMerge->getId()), $selectedCollisionItems); $newListing = new Listing($baseListing->year, $baseListing->month, $ownerOfOutputListing); $this->em->persist($newListing); foreach ($items as $item) { /** @var ListingItem $item */ $item->setListing($newListing); $this->em->persist($item); } $this->em->flush(); $this->em->commit(); return $newListing; } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); $this->onError('Merging of listings #id(' . $baseListing->getId() . ') and #id(' . $listingToMerge->getId() . ') failed.', $e, self::class); throw $e; } }
/** * @param ElasticIndex $oldIndex * @param ElasticIndex $newIndex */ private function moveDataBetweenIndices(ElasticIndex $oldIndex, ElasticIndex $newIndex) { CrossIndex::reindex($oldIndex, $newIndex); $newIndexEntity = new Index($newIndex->getName()); $this->entityManager->persist($newIndexEntity); $this->entityManager->flush($newIndexEntity); }
/** * @param array $values * @param User|null $user * @return ValidationObject */ public function update(array $values, User $user) { $this->em->beginTransaction(); $user->setFirstName($values['first_name']); $user->setLastName($values['last_name']); $validationObject = new ValidationObject(); // todo could be optimized $user->clearRoles(); $role = $this->getRole($values['role'], $validationObject); if (!$validationObject->isValid()) { $this->em->rollback(); return $validationObject; } $user->addRole($role); $this->em->persist($user); $this->em->flush(); if ($validationObject->isValid()) { $this->em->commit(); $this->onSuccessUserEditing($user); $this->cache->remove($user->getCacheKey()); } else { $this->em->rollback(); } return $validationObject; }
/** * @param Vote $vote * @param array $requestInfo * @param \Nette\Utils\ArrayHash $values * @return boolean Ulozeni hlasovani */ protected function processPoll($vote, $requestInfo, $values) { $voter_id = \App\Model\Entities\Poll::generateVoteIdentificator(); $answers = $this->parsePoll($values); foreach ($answers as $key => $value) { if ($key != 'text') { $myOption = $this->em->getReference(\App\Model\Entities\Option::class, $key); } else { $myOption = NULL; } $myNewPoll = new \App\Model\Entities\Poll($myOption, $value); $myNewPoll->setVoterIdentification($voter_id); $myNewPoll->setIp($requestInfo['ip']); $myNewPoll->setAgent($requestInfo['agent']); $myNewPoll->setCookie($requestInfo['cookie']); $vote->addPoll($myNewPoll); } try { $this->em->flush(); $result = TRUE; } catch (\Exception $e) { \Tracy\Debugger::log($e, \Tracy\Debugger::INFO); $result = FALSE; } return $result; }
/** * @param User $user * @param array $albums */ public function assignAlbums(User $user, array $albums) { $user->albums->clear(); $user->setAlbums($albums); $this->em->persist($user); $this->em->flush(); }
public function setText($ident, $text) { if ($this->authorizator->canWrite($ident)) { $et = $this->editableTextRepository->find($ident); $action = "saved"; if ($et === NULL) { $et = new EditableText($ident); $this->em->persist($et); $action = "created"; } $et->setText($text); $this->em->flush(); return ['action' => $action]; } else { throw new AuthenticationException("You have no authorization to edit text"); } }
public function save(array $values) { $options = $this->prepareOptions($this->findOptions()); foreach ((array) $values as $key => $value) { $options[$key]->setValue($value == '' ? null : $value); $this->em->persist($options[$key]); } try { $this->em->flush(); $this->cache->remove(Option::getCacheKey()); $this->onSuccessOptionsSaving(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); $this->logger->addError(sprintf('Save Options error: %s | error message: %s', date('Y-m-d H:i:s'), $e->getMessage())); throw $e; } }
/** * @todo Vylepsit to inkrementovani * Detail clanku * @param string $id Identifikator clanku: article_id-webalize_title */ public function actionPost($id) { list($parseId, $parseWebTitle) = Model\Entities\Article::parseWebId($id); $this->article = $this->articleRepository->getById($parseId); if (!is_object($this->article)) { //nepodarilo se ziskat clanek $this->flashMessage($this->translator->translate('system.articleNF'), self::MESSAGE_DANGER); $this->redirect('default'); } if (!$this->user->isLoggedIn() && !$this->article->isPublished()) { //nezobrazovat nezverejnene clanky neprihlasenym uzivatelum $this->flashMessage($this->translator->translate('system.requestNA'), self::MESSAGE_DANGER); $this->redirect('default'); } //inkrementovat citac pristupu a ulozeni zmeny $this->article->setCounter(); $this->entityManager->flush(); }
/** * @param $id * @param $performanceId * @param $position * * @throws \Exception */ public function handleMovePerformance($id, $performanceId, $position) { if ($performanceId and $performance = $this->performanceFacade->findPerformanceById($performanceId)) { $performance->setPosition($position); } $this->entityManager->flush(); $this->flashMessage("Představení bylo posunuto", "success"); $this->redirect(":Event:detail", $id); }
public function doctrineFlush($search = null) { // save entities if ($this->em->flush()) { // return last id return $search->getId(); } // when error return false return false; }