persist() public méthode

public persist ( object | array $entity ) : EntityManager
$entity object | array
Résultat EntityManager
Exemple #1
0
 /**
  * @param FileUpload $file
  * @return Image
  * @throws NotImageUploadedException
  * @throws FileSizeException
  * @throws DBALException
  * @throws InvalidStateException
  */
 public function processImage(FileUpload $file)
 {
     if (!$file->isImage()) {
         throw new NotImageUploadedException();
     }
     if (\filesize($file->getTemporaryFile()) > Image::MAX_FILE_SIZE) {
         throw new FileSizeException();
     }
     try {
         $this->em->beginTransaction();
         $image = new Image($file);
         $this->em->persist($image)->flush();
         $file->move($this->composeImageLocation($image));
         $this->em->commit();
     } catch (InvalidStateException $is) {
         $this->em->rollback();
         $this->em->close();
         $this->logger->addError('Error occurs while moving temp. image file to new location.');
         throw $is;
     } catch (DBALException $e) {
         $this->em->rollback();
         $this->em->close();
         $this->logger->addError('Image error');
         // todo err message
         throw $e;
     }
     return $image;
 }
 /**
  * @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;
 }
Exemple #3
0
 /**
  * @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;
     }
 }
Exemple #4
0
 /**
  * @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 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();
 }
Exemple #6
0
 public function save($entity, $immediately = true)
 {
     $this->em->persist($entity);
     if ($immediately) {
         $this->em->flush();
     }
 }
Exemple #7
0
 /**
  * @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();
 }
 /**
  * @param Privilege $privilege
  * @param Role $role
  * @return $this
  */
 public function addDefinition(Privilege $privilege, Role $role)
 {
     $accessDefinition = new AccessDefinition($this->resource, $privilege);
     $this->em->persist($accessDefinition);
     $permission = new Permission($role, $this->resource, $privilege);
     $this->em->persist($permission);
     return $this;
 }
 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();
 }
 public function addGenre(string $name)
 {
     if ($this->genreExists($name)) {
         return;
     }
     $genre = new Genre($name);
     $this->entityManager->persist($genre);
     $this->entityManager->flush($genre);
 }
 /**
  * @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;
 }
 /**
  * @param User $user
  * @return User
  * @throws \Exception
  */
 public function saveUser(User $user)
 {
     try {
         $this->em->persist($user)->flush();
         return $user;
     } catch (\Exception $e) {
         $this->onError(sprintf('Saving of user "%s" #id(%s) failed', $user->username, $user->getId()), $e, self::class);
         throw $e;
     }
 }
 /**
  * @param $albumId
  */
 public function delete($albumId)
 {
     /**
      * @var Album $album
      */
     $album = $this->albumDao->find($albumId);
     $album->delete();
     $this->em->persist($album);
     $this->em->flush();
 }
 /**
  * @param Listing $listing
  * @return Listing
  * @throws \Exception
  */
 public function saveListing(Listing $listing)
 {
     try {
         $this->em->persist($listing)->flush();
         return $listing;
     } catch (\Exception $e) {
         $this->onCritical('Saving of Listing failed. [saveListing]', $e, self::class);
         throw $e;
     }
 }
 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();
 }
Exemple #16
0
 /**
  * @param Entity\Event $event
  */
 public function save(Entity\Event $event)
 {
     foreach ($event->performances as $performance) {
         foreach ($performance->children as $child) {
             $this->em->persist($child);
         }
         $this->em->persist($performance);
     }
     $this->em->persist($event);
     $this->em->flush();
 }
Exemple #17
0
 /**
  * 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;
 }
Exemple #18
0
 /**
  * @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();
     }
 }
 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);
 }
Exemple #20
0
 /**
  * @param string $entityName
  * @param int $id
  * @return mixed
  * @throws \Exception
  */
 public function findOrCreateEntity($entityName, $id)
 {
     if ($id === NULL) {
         $entity = new $entityName();
         $this->em->persist($entity);
         return $entity;
     }
     $entity = $this->em->getRepository($entityName)->find($id);
     if ($entity === NULL) {
         throw new \Exception('Entity was not fount.');
     }
     return $entity;
 }
Exemple #21
0
 /**
  * @param Nette\Utils\ArrayHash $values
  * @return boolean Vytvoreni nove rubriky problehlo uspesne?
  */
 protected function newTag($values)
 {
     $result = TRUE;
     try {
         $newTag = new \App\Model\Entities\Tag($values->title);
         //pridani nove rubriky a ulozeni zmen
         $this->em->persist($newTag);
         $this->em->flush();
     } catch (\Exception $e) {
         \Tracy\Debugger::log($e, \Tracy\Debugger::INFO);
         $result = FALSE;
     }
     return $result;
 }
 /**
  * @param ListingItem $listingItem
  * @return ListingItem
  * @throws ListingItemDayAlreadyExistsException
  * @throws \Exception
  */
 public function saveListingItem(ListingItem $listingItem)
 {
     try {
         $this->em->persist($listingItem)->flush();
     } catch (UniqueConstraintViolationException $u) {
         $this->em->close();
         throw new ListingItemDayAlreadyExistsException();
     } catch (\Exception $e) {
         $this->em->close();
         $this->onCritical('Listing item saving of Listing #id(' . $listingItem->getListing()->getId() . ') failed.', $e, self::class);
         throw $e;
     }
     return $listingItem;
 }
 /**
  * @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 File $file
  * @param string|null $genreId
  * @param bool $copy
  * @return bool returns true if file already exists
  * @throws \Exception
  */
 private function addSong(File $file, string $genreId = null, $copy = false) : bool
 {
     if ($this->songExists($file->getDestination())) {
         return true;
     }
     //		$albumURL = $this->albumCoverProvider->getAlbumCoverURL($file->getDestination());
     $albumURL = '';
     if ($genreId) {
         $genre = $this->genresRepository->find($genreId);
     } else {
         $genre = null;
     }
     $hash = md5_file($file->getDestination());
     $song = new Song($file->getName(), $albumURL, $hash, $genre);
     $this->entityManager->persist($song);
     $destination = $this->getSongPath($song->getId());
     if ($copy) {
         $file->copy($destination);
     } else {
         $file->move($destination);
     }
     $this->processSong($song);
     $this->entityManager->flush($song);
     return false;
 }
Exemple #25
0
 /**
  * @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;
 }
Exemple #26
0
 /**
  * @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);
 }
Exemple #27
0
 public function setup()
 {
     $this->entityManager->transactional(function () {
         $privileges = $this->createPrivileges();
         if (!empty($privileges)) {
             $this->entityManager->persist($privileges);
         }
         $invalidPrivileges = $this->findInvalidPrivileges($privileges);
         if (!empty($invalidPrivileges)) {
             $this->entityManager->remove($invalidPrivileges);
         }
         $roles = $this->createRoles($privileges);
         if (!empty($roles)) {
             $this->entityManager->persist($roles);
         }
     });
 }
Exemple #28
0
 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");
     }
 }
Exemple #29
0
 /**
  * @param array $values
  * @param Tag $tag
  * @return Tag
  * @throws \Exception
  */
 private function update(array $values, Tag $tag)
 {
     $this->em->beginTransaction();
     $this->fillTag($values, $tag);
     $this->em->persist($tag)->flush();
     $this->em->commit();
     return $tag;
 }
Exemple #30
0
 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;
     }
 }