/** * @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 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 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; }
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; }
/** * @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 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; } }
/** * @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 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(); } }
/** * @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 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 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; }
/** * @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; }
/** * @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; } }
/** * @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; }
/** * @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; }
/** * @param Role $role * @param array $permissionDefinitions * @throws DBALException * @throws \Exception */ public function save(Role $role, array $permissionDefinitions) { $resources = $this->em->createQuery('SELECT r FROM ' . Resource::class . ' r INDEX BY r.id')->execute(); $privileges = $this->em->createQuery('SELECT p FROM ' . Privilege::class . ' p INDEX BY p.id')->execute(); try { $this->em->beginTransaction(); $this->em->createQuery('DELETE ' . Permission::class . ' p WHERE p.role = :role')->execute(['role' => $role->getId()]); $parentRole = null; if ($role->hasParent()) { /** @var Role $parentRole */ $parentRole = $this->em->find(Role::class, $role->getParentId()); } foreach ($permissionDefinitions as $definition => $isAllowed) { $isAllowed = (bool) $isAllowed; $x = explode('-', $definition); // eg. 1-3 /** @var \Users\Authorization\Resource $resource */ $resource = $resources[$x[0]]; /** @var Privilege $privilege */ $privilege = $privileges[$x[1]]; // check Users\Authorization\Authorizator ACL assembling // Role without parent // privilege: allowed -> must be in database // privilege: denied -> does NOT have to be in database // Role with parent (all depths) /* ------------------------------------------------------------ parent | descendant | should be persisted? ------------------------------------------------------------ allowed allowed NO allowed denied YES denied denied NO denied allowed YES ------------------------------------------------------------ We save records where permission and denial differ */ if ($parentRole !== null) { // has parent if ($this->authorizator->isAllowed($parentRole, $resource->getName(), $privilege->getName()) === $isAllowed) { continue; } } else { // doesn't have parent if ($isAllowed === false) { continue; } } $permission = new Permission($role, $resource, $privilege, $isAllowed); $this->em->persist($permission); } $this->em->flush(); $this->em->commit(); $this->cache->remove('acl'); $this->onSuccessRolePermissionsEditing($role); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); // todo log error throw new $e(); } }