本文整理汇总了PHP中Kdyby\Doctrine\EntityManager::beginTransaction方法的典型用法代码示例。如果您正苦于以下问题:PHP EntityManager::beginTransaction方法的具体用法?PHP EntityManager::beginTransaction怎么用?PHP EntityManager::beginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Kdyby\Doctrine\EntityManager
的用法示例。
在下文中一共展示了EntityManager::beginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: linkUrls
/**
* @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;
}
}
示例2: processImage
/**
* @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;
}
示例3: save
/**
* @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;
}
示例4: getFreeAddress
public function getFreeAddress() : Address
{
if ($this->addressRepository->countBy([]) == 0) {
$this->generateAndPersistNewAddresses(10);
}
$this->entityManager->beginTransaction();
$addressMaxAge = new \DateTime($this->addressLockTime);
$qb = $this->addressRepository->createQueryBuilder('address');
$qb->addSelect('count(address) as free')->where('address.lastUsed IS NULL')->orWhere('address.lastUsed < :maxAge')->setParameter('maxAge', $addressMaxAge)->setMaxResults(1);
/** @var Address $address */
$result = $qb->getQuery()->getSingleResult();
$address = $result[0];
$free = $result['free'];
$address->useAddress();
$this->entityManager->flush($address);
$qb = $this->entityManager->createQueryBuilder();
$qb->select('COUNT(address) AS total')->from(Address::getClassName(), 'address');
$total = $qb->getQuery()->getSingleScalarResult();
$occupied = $total - $free;
if ($occupied / $total >= $this->occupiedAddressesTreshold) {
$this->generateAndPersistNewAddresses(round($total * $this->increaseRatio));
}
$this->entityManager->commit();
return $address;
}
示例5: sendMessage
/**
* @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;
}
示例6: removeImage
/**
* @param string $imageName image name is comprised of UUID and original name (UUID/origName.extension)
* @throws DBALException
* @throws FileRemovalException
*/
public function removeImage($imageName)
{
$id = mb_substr($imageName, 0, mb_strpos($imageName, '/'));
$file = sprintf('%s/%s', $this->imageFileRoot, $imageName);
try {
$this->em->beginTransaction();
$d = $this->em->createQuery('DELETE ' . Image::class . ' i WHERE i.id = :id')->execute(['id' => $id]);
$directory = sprintf('%s/%s', $this->imageFileRoot, $id);
// checks whether directory exists (each directory has always one file)
if ($d > 0 and \file_exists($directory) and is_dir($directory)) {
$r = \unlink($file);
// and if so then remove file in it
if ($r === false) {
// file couldn't be removed
$this->em->rollback();
$this->em->close();
throw new FileRemovalException();
} else {
// remove directory
FileSystem::delete($directory);
}
}
$this->em->commit();
} catch (DBALException $e) {
$this->em->rollback();
$this->em->close();
throw $e;
}
}
示例7: remove
/**
* @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;
}
}
示例8: remove
/**
* @param Comment $comment
* @throws ActionFailedException
*/
public function remove(Comment $comment)
{
try {
$this->em->beginTransaction();
$this->em->remove($comment)->flush();
$this->em->createQuery('UPDATE ' . Comment::class . ' c SET c.order = c.order - 1
WHERE c.page = :page and c.order > :order')->execute(['page' => $comment->getPageId(), 'order' => $comment->getOrder()]);
$this->em->commit();
} catch (\Exception $e) {
$this->em->rollback();
$this->em->close();
throw new ActionFailedException();
}
}
示例9: update
/**
* @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;
}
示例10: mergeListings
/**
* @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;
}
}
示例11: update
/**
* @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;
}
示例12: save
/**
* @param Url $url
* @return Url
* @throws UrlAlreadyExistsException
* @throws \Exception
*/
public function save(Url $url)
{
try {
$this->em->beginTransaction();
if ($url->getId() !== null) {
$url = $this->update($url);
} else {
$url = $this->create($url);
}
$this->em->commit();
} catch (UrlAlreadyExistsException $uae) {
$this->closeEntityManager();
$this->logger->addError(sprintf('Url path already exists: %s', $uae));
throw $uae;
} catch (\Exception $e) {
$this->closeEntityManager();
$this->logger->addError(sprintf('Url Entity saving failure: %s', $e));
throw $e;
}
return $url;
}
示例13: remove
/**
* @param $tagID
* @throws \Exception
*/
public function remove($tagID)
{
try {
$this->em->beginTransaction();
/** @var Tag $tag */
$tag = $this->tagRepository->find($tagID);
if ($tag === null) {
$this->em->commit();
return;
}
$tagSearchUrl = $this->urlFacade->getUrl('Pages:Front:Search', 'tag', $tag->getId());
$this->em->remove($tag);
$this->em->remove($tagSearchUrl);
$this->em->flush();
$this->em->commit();
$this->onSuccessTagRemoval($tag, $tagID);
} catch (\Exception $e) {
$this->em->rollback();
$this->em->close();
throw $e;
}
}
示例14: registerUser
/**
* @param User $newUser
* @param Invitation $invitation
* @return User
* @throws DuplicateUsernameException
* @throws DuplicateEmailException
* @throws InvalidUserInvitationEmailException
*/
public function registerUser(User $newUser, Invitation $invitation)
{
if ($newUser->email !== $invitation->email) {
throw new InvalidUserInvitationEmailException();
}
$this->em->beginTransaction();
$user = $this->em->safePersist($newUser);
if ($user === false) {
$this->em->rollback();
// e.g. when two users are trying to register
// at the same time on the same Invitation
if ($this->usersReader->isEmailRegistered($newUser->email)) {
$this->invitationsWriter->removeInvitation($invitation);
throw new DuplicateEmailException();
}
if ($this->usersReader->isUsernameRegistered($newUser->username)) {
throw new DuplicateUsernameException();
}
}
$this->invitationsWriter->removeInvitation($invitation);
$this->em->commit();
return $user;
}
示例15: updatePage
/**
* @param Page $page
* @param array $values
* @return Page
* @throws UrlAlreadyExistsException
* @throws PagePublicationTimeException
* @throws PageIntroHtmlLengthException
*/
private function updatePage(Page $page, array $values)
{
$this->em->beginTransaction();
$this->fillPageEntity($values, $page);
if ($page->getUrlPath() !== Strings::webalize($values['url'])) {
$newUrl = $this->redirectPageToUrl($values['url'], $page);
$page->setUrl($newUrl);
}
$page->clearTags();
$this->addTags2Page($values['tags'], $page);
$this->em->persist($page);
$this->em->flush();
$this->em->commit();
return $page;
}