Example #1
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;
     }
 }
Example #2
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 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;
 }
Example #4
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;
 }
Example #5
0
 /**
  * @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;
     }
 }
Example #6
0
 /**
  * @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();
     }
 }
Example #7
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;
 }
 /**
  * @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;
     }
 }
Example #9
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;
     }
 }
Example #10
0
 /**
  * @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;
 }
Example #12
0
 private function closeEntityManager()
 {
     $this->em->rollback();
     $this->em->close();
 }
Example #13
0
 /**
  * @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();
     }
 }