/**
  * @param Url $url
  * @return Url|object
  * @throws \Doctrine\DBAL\ConnectionException
  * @throws \Exception
  */
 public function encode(Url $url)
 {
     $this->em->beginTransaction();
     try {
         $urlRepository = $this->em->getRepository('Rz\\Bundle\\UrlShortenerBundle\\Entity\\Url');
         $entity = $urlRepository->findOneBy(['url' => $url->getUrl()]);
         if ($entity) {
             /** @var Url $url */
             $url = $entity;
         } else {
             $url->setNew(true);
             $this->em->persist($url);
             $this->em->flush();
             $url->setCode($this->encoder->encode($url->getId()));
             $params = ['code' => $url->getCode()];
             if (!$url->isDefaultSequence()) {
                 $params['index'] = $url->getSequence();
             }
             $url->setShortUrl($this->router->generate(UrlShortenerBundle::URL_GO, $params, UrlGeneratorInterface::ABSOLUTE_URL));
             $this->em->persist($url);
             $this->em->flush();
         }
         $this->em->getConnection()->commit();
         return $url;
     } catch (\Exception $e) {
         $this->em->getConnection()->rollBack();
         throw $e;
     }
 }
 /**
  * Writes the record down to the log of the implementing handler
  *
  * @param  array $record
  *
  * @return void
  */
 protected function write(array $record)
 {
     // Ensure the doctrine channel is ignored (unless its greater than a warning error), otherwise you will create an infinite loop, as doctrine like to log.. a lot..
     if ('doctrine' == $record['channel']) {
         if ((int) $record['level'] >= Logger::WARNING) {
             error_log($record['message']);
         }
         return;
     }
     // Only log errors greater than a warning
     //@todo - you could ideally add this into configuration variable
     if ((int) $record['level'] >= Logger::INFO && (string) $record['channel'] == 'backtrace') {
         try {
             // Create entity and fill with data
             $entity = new SystemLog();
             $entity->setChannel($record['channel'])->setLevel($record['level'])->setLog($record['message'])->setFormattedMsg($record['formatted'])->setCreatedAt(new \DateTime());
             $this->em->persist($entity);
             $this->em->flush();
         } catch (\Exception $e) {
             // Fallback to just writing to php error logs if something really bad happens
             error_log($record['message']);
             error_log($e->getMessage());
         }
     }
 }
Esempio n. 3
0
 /**
  * Persists and flushes all provided models to the database storage.
  *
  * @param ...$models
  */
 protected function persist(...$models)
 {
     foreach ($models as $model) {
         $this->entityManager->persist($model);
     }
     $this->entityManager->flush();
 }
Esempio n. 4
0
 public function setUp()
 {
     $this->em = $this->prophesize(EntityManagerInterface::class);
     $this->em->persist(Argument::any())->willReturn(null);
     $this->em->flush()->willReturn(null);
     $this->service = new ShortUrlService($this->em->reveal());
 }
 public function delete(BaseEntityInterface $entity)
 {
     $this->entityManager->remove($entity);
     if ($this->autoFlush) {
         $this->entityManager->flush();
     }
 }
Esempio n. 6
0
 /**
  * Creates and persists a unique shortcode generated for provided url
  *
  * @param UriInterface $url
  * @param string[] $tags
  * @return string
  * @throws InvalidUrlException
  * @throws RuntimeException
  */
 public function urlToShortCode(UriInterface $url, array $tags = [])
 {
     // If the url already exists in the database, just return its short code
     $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy(['originalUrl' => $url]);
     if (isset($shortUrl)) {
         return $shortUrl->getShortCode();
     }
     // Check that the URL exists
     $this->checkUrlExists($url);
     // Transactionally insert the short url, then generate the short code and finally update the short code
     try {
         $this->em->beginTransaction();
         // First, create the short URL with an empty short code
         $shortUrl = new ShortUrl();
         $shortUrl->setOriginalUrl($url);
         $this->em->persist($shortUrl);
         $this->em->flush();
         // Generate the short code and persist it
         $shortCode = $this->convertAutoincrementIdToShortCode($shortUrl->getId());
         $shortUrl->setShortCode($shortCode)->setTags($this->tagNamesToEntities($this->em, $tags));
         $this->em->flush();
         $this->em->commit();
         return $shortCode;
     } catch (ORMException $e) {
         if ($this->em->getConnection()->isTransactionActive()) {
             $this->em->rollback();
             $this->em->close();
         }
         throw new RuntimeException('An error occurred while persisting the short URL', -1, $e);
     }
 }
 /**
  * Persists an entity via the EntityManager
  *
  * @param mixed $built A built entity
  */
 public function persist($built)
 {
     $this->entityManager->persist($built);
     if ($this->flushAfterPersist) {
         $this->entityManager->flush();
     }
 }
 /**
  * @param $configKey
  * @param $objectId
  * @param $value
  * @param null|string $dataField
  * @throws ContentEditableException
  */
 public function updateEntity($configKey, $objectId, $value, $dataField = null)
 {
     if (!array_key_exists($configKey, $this->configuration['configurations'])) {
         throw new ContentEditableException('Missing configuration "' . $configKey . '"');
     }
     $config = $this->configuration['configurations'][$configKey];
     if ($dataField == null) {
         if (!array_key_exists('data_field', $config)) {
             throw new ContentEditableException('Missing data_field');
         }
         $dataField = $config['data_field'];
     }
     $idField = 'id';
     if (array_key_exists('id_field', $config)) {
         $idField = $config['id_field'];
     }
     $repository = $this->entityManager->getRepository($config['repository_class']);
     $entity = $repository->findOneBy([$idField => $objectId]);
     $setter = 'set' . ucfirst($dataField);
     if (!method_exists($entity, $setter)) {
         throw new ContentEditableException('No setter "' . $setter . '" found for "' . get_class($entity) . '"');
     }
     $entity->{$setter}(trim($value));
     $this->entityManager->persist($entity);
     $this->entityManager->flush();
 }
Esempio n. 9
0
 /**
  * @param array|Student[] $students
  */
 public function saveAll(array $students)
 {
     foreach ($students as $student) {
         $this->em->persist($student);
     }
     $this->em->flush();
 }
Esempio n. 10
0
 /**
  * @param MailingList $list
  */
 public function saveList(MailingList $list)
 {
     if (!$list->getId()) {
         $this->em->persist($list);
     }
     $this->em->flush($list);
 }
Esempio n. 11
0
 /**
  * @param $type
  * @param $id
  * @param $loader
  * @return Link
  */
 protected function createLink($type, $id, $loader)
 {
     $link = new Link($type, $id, $loader);
     $this->entityManager->persist($link);
     $this->entityManager->flush($link);
     return $link;
 }
Esempio n. 12
0
 public function __invoke()
 {
     if (null === ($renderer = $this->_renderer)) {
         return '';
     }
     if (null === ($page = $renderer->getCurrentPage())) {
         return '';
     }
     $metadata = $page->getMetadata();
     if (null === $metadata || $metadata->count() === 0) {
         //            @todo gvf
         $metadata = new MetaDataBag($this->metadataConfig, $page);
         $page->setMetaData($metadata);
         if ($this->entityManager->contains($page)) {
             $this->entityManager->flush($page);
         }
     }
     $result = '';
     foreach ($metadata as $meta) {
         if (0 < $meta->count() && 'title' !== $meta->getName()) {
             $result .= '<meta ';
             foreach ($meta as $attribute => $value) {
                 if (false !== strpos($meta->getName(), 'keyword') && 'content' === $attribute) {
                     $keywords = explode(',', $value);
                     foreach ($this->getKeywordObjects($keywords) as $object) {
                         $value = trim(str_replace($object->getUid(), $object->getKeyWord(), $value), ',');
                     }
                 }
                 $result .= $attribute . '="' . html_entity_decode($value, ENT_COMPAT, 'UTF-8') . '" ';
             }
             $result .= '/>' . PHP_EOL;
         }
     }
     return $result;
 }
Esempio n. 13
0
 public function execute()
 {
     $criteria = new Criteria(['owner' => $this->user], null, null, null);
     $items = $this->basketRepository->findByCriteria($criteria);
     $order = $this->orderRepository->findActive();
     $connection = $this->entityManager->getConnection();
     $connection->beginTransaction();
     try {
         $orderItems = [];
         foreach ($items as $item) {
             /** @var Basket $item */
             $previousOrderItem = $this->orderItemRepository->findOneByCriteria(new Criteria(['owner' => $item->getOwner(), 'product' => $item->getProduct()]));
             if ($previousOrderItem) {
                 /** @var OrderItem $orderItem */
                 $orderItem = $previousOrderItem;
                 $orderItem->increaseQuantityBy($item->getQuantity());
             } else {
                 $orderItem = OrderItem::createFromBasket($item, $order);
             }
             $this->entityManager->persist($orderItem);
             $this->entityManager->remove($item);
             $orderItems[] = $orderItem;
         }
         $this->entityManager->flush();
         $connection->commit();
     } catch (\Exception $e) {
         $connection->rollBack();
         return $e->getMessage();
     }
 }
 public function notify(UrlEvent $event)
 {
     if (!$this->isEnabled() || !$event->getUrl() || $event->getType() !== Shortener::NOTIFY_TYPE_REDIRECT) {
         return false;
     }
     $additional = $event->getAdditional();
     $ip = !empty($additional['ip']) ? $additional['ip'] : null;
     if (!$ip) {
         return false;
     }
     $urlRepository = $this->em->getRepository('Rz\\Bundle\\UrlShortenerBundle\\Entity\\Url');
     $urlStatRepository = $this->em->getRepository('Rz\\Bundle\\UrlShortenerBundle\\Entity\\UrlStat');
     /** @var Url $url */
     $url = $urlRepository->find($event->getUrl()->getId());
     $url->incrementRedirectCount();
     $url->setLastRedirectOn(new \DateTime());
     $urlStat = $urlStatRepository->findOneBy(['Url' => $url, 'ip' => $ip]);
     if (!$urlStat) {
         $url->incrementUniqueRedirectCount();
         $urlStat = new UrlStat();
         $urlStat->setUrl($url);
         $urlStat->setCreated(new \DateTime());
         $urlStat->setIp($ip);
         if (!empty($additional['user-agent'])) {
             $urlStat->setUserAgent($additional['user-agent']);
         }
         $this->em->persist($urlStat);
     }
     $this->em->persist($url);
     $this->em->flush();
     return true;
 }
Esempio n. 15
0
 /**
  * Update the users last login.
  *
  * @param UserInterface $user
  */
 protected function updateLastLogin($user)
 {
     if ($user instanceof BaseUser) {
         $user->setLastLogin(new \DateTime());
         $this->entityManager->flush();
     }
 }
Esempio n. 16
0
 /**
  * @param array|Doctrine\Common\Collections\Collection|\Traversable
  * @param boolean $flush
  */
 function delete($entity, $flush = self::FLUSH)
 {
     $this->em->delete($entity);
     if ($flush) {
         $this->em->flush($entity);
     }
 }
Esempio n. 17
0
 /**
  * Unregisters the smartCode from its subject.
  *
  * @param SubjectInterface   $subject
  * @param SmartCodeInterface $smartCode
  *
  * @return mixed
  */
 public function unregister(SubjectInterface $subject, SmartCodeInterface $smartCode)
 {
     $subject->removeSmartCode($smartCode);
     $smartCode->setUsed($smartCode->getUsed() - 1);
     $this->manager->persist($subject);
     $this->manager->flush();
 }
Esempio n. 18
0
 /**
  * @inheritdoc
  */
 public function delete(MessageModel $message) : MessageModel
 {
     $message->delete();
     $this->em->persist($message);
     $this->em->flush();
     return $message;
 }
Esempio n. 19
0
 /**
  * @param object $entity
  * @param bool $doFlush
  */
 public function remove($entity, $doFlush = true)
 {
     $this->entityManager->remove($entity);
     if ($doFlush) {
         $this->entityManager->flush();
     }
 }
Esempio n. 20
0
 public function createMessage($text, $username, $email = null)
 {
     $message = new GuestBookMessage();
     $message->setText($text)->setUsername($username)->setEmail($email);
     $this->manager->persist($message);
     $this->manager->flush();
 }
Esempio n. 21
0
 public function processDelete(ProcessHook $hook)
 {
     $repository = $this->entityManager->getRepository('CmfcmfMediaModule:HookedObject\\HookedObjectEntity');
     $hookedObject = $repository->getByHookOrCreate($hook);
     $this->entityManager->remove($hookedObject);
     $this->entityManager->flush();
 }
Esempio n. 22
0
 public function updateTranslationRoute(Routeable $routeable, $locale, $staticPrefix)
 {
     $route = $routeable->getRoute();
     $return = null;
     if (!$route instanceof Route) {
         return null;
     }
     $translationRoute = $this->em->getRepository('EnhavoTranslationBundle:TranslationRoute')->findOneBy(['type' => $route->getType(), 'typeId' => $route->getTypeId(), 'locale' => $locale]);
     if ($translationRoute === null) {
         $route = new Route();
         $route->setContent($routeable);
         $translationRoute = new TranslationRoute();
         $translationRoute->setLocale($locale);
         $translationRoute->setRoute($route);
         $this->em->persist($translationRoute);
     }
     /** @var Route $route */
     $route = $translationRoute->getRoute();
     $route->setStaticPrefix($staticPrefix);
     $translationRoute->setPath($staticPrefix);
     $this->em->flush();
     $this->routeManager->update($route);
     $translationRoute->setType($route->getType());
     $translationRoute->setTypeId($route->getTypeId());
     $this->em->flush();
     return $translationRoute;
 }
Esempio n. 23
0
 /**
  * @inheritdoc
  */
 public function delete(UserModel $user) : UserModel
 {
     $user->delete();
     $this->em->persist($user);
     $this->em->flush();
     return $user;
 }
Esempio n. 24
0
 /**
  * Renueva el alquiler.
  *
  * @param Rental $rental
  *
  * @return Rental
  */
 public function renewRental(Rental $rental)
 {
     if ($rental->getReturnAt()) {
         throw new FinishedRentalException();
     }
     if ($rental->getUser()->getIsPenalized()) {
         throw new PenalizedUserException();
     }
     if ($rental->getUser()->getFaculty()->getIsEnabled() === false) {
         throw new PenalizedFacultyException();
     }
     if (!$rental->getIsRenewable()) {
         throw new NotRenewableRentalException();
     }
     if ($rental->getIsExpired()) {
         throw new ExpiredRentalException();
     }
     if ($rental->getDaysLeft() > $this->days_before_renovation) {
         throw new TooEarlyRenovationException();
     }
     $left = $rental->getDaysLeft() + $this->days_length_rental;
     $rental->setEndAt(new \DateTime($left . ' days midnight'));
     $this->manager->persist($rental);
     $this->manager->flush();
     $event = new RentalEvent($rental);
     $this->dispatcher->dispatch(RentalEvents::LOCKER_RENEWED, $event);
     return $rental;
 }
Esempio n. 25
0
 /**
  * Activates new user by activation code
  *
  * @param string $code
  *
  * @throws IOException
  */
 public function activate($code)
 {
     $user = $this->userRepository->findOneBy(['code' => $code, 'frozen' => true]);
     $user->activate();
     $this->entityManager->persist($user);
     $this->entityManager->flush();
 }
Esempio n. 26
0
 /**
  * @param Subscription $subscription
  * @param string       $status
  *
  * @return $this
  */
 public function updateStatus(Subscription $subscription, $status)
 {
     $subscription->setStatus($status);
     $this->em->persist($subscription);
     $this->em->flush($subscription);
     return $this;
 }
 /**
  * {@inheritDoc}
  *
  * @return void
  */
 public function run(EntityInterface $user)
 {
     $user->setActivationKey(base64_encode($this->secureRandom->nextBytes(24)));
     $user->setPassword($this->passwordEncoder->encodePassword($user->getPassword(), User::SALT));
     $user->setRegistrationDate(new \DateTime());
     $this->entityManager->getRepository(User::class)->add($user);
     $this->entityManager->flush();
 }
Esempio n. 28
0
 /**
  * @param ModelInterface $entity
  * @return void
  */
 public function delete(ModelInterface $entity)
 {
     if (!$entity instanceof CourseInterface) {
         throw new InvalidArgumentException('expect an CourseInterface object');
     }
     $this->em->remove($entity);
     $this->em->flush();
 }
Esempio n. 29
0
 /**
  * "Success" form handler
  *
  * @param Contact $entity
  * @param array $appendAccounts
  * @param array $removeAccounts
  */
 protected function onSuccess(Contact $entity, array $appendAccounts, array $removeAccounts)
 {
     $this->appendAccounts($entity, $appendAccounts);
     $this->removeAccounts($entity, $removeAccounts);
     $this->manager->persist($entity);
     $this->setUpdatedAt($entity);
     $this->manager->flush();
 }
Esempio n. 30
0
 public function abandon(GenericEvent $event)
 {
     $cart = $event->getSubject();
     if ($cart instanceof OrderInterface) {
         $cart->setExpiresAt(new \DateTime());
     }
     $this->em->flush();
 }