/** * @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; }
/** * @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 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 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; } }
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; } }
/** * @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 array $values * @param User $user * @return ValidationObject * @throws \Exception */ public function save(array $values, User $user = null) { foreach ($values as $key => $value) { $values[$key] = $value !== '' ? $value : null; } try { if (isset($user) and $user->getId() !== null) { $validationObject = $this->update($values, $user); } else { $validationObject = $this->create($values, $user); } } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); // todo log throw $e; } if ($validationObject->isValid()) { $validationObject->setResult($user); } return $validationObject; }
private function closeEntityManager() { $this->em->rollback(); $this->em->close(); }
/** * @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(); } }