/** * @param mixed $entity * @param boolean $flush */ public function update($entity, $flush = true) { $this->em->persist($entity); if ($flush) { $this->em->flush(); } }
/** * Load the fixture jobs in database * * @return null */ public function load() { $rawJobs = array(); $fileLocator = $this->container->get('file_locator'); foreach ($this->jobsFilePaths as $jobsFilePath) { $realPath = $fileLocator->locate('@' . $jobsFilePath); $this->reader->setFilePath($realPath); // read the jobs list while ($rawJob = $this->reader->read()) { $rawJobs[] = $rawJob; } // sort the jobs by order usort($rawJobs, function ($item1, $item2) { if ($item1['order'] === $item2['order']) { return 0; } return $item1['order'] < $item2['order'] ? -1 : 1; }); } // store the jobs foreach ($rawJobs as $rawJob) { unset($rawJob['order']); $job = $this->processor->process($rawJob); $config = $job->getRawConfiguration(); $config['filePath'] = sprintf('%s/%s', $this->installerDataPath, $config['filePath']); $job->setRawConfiguration($config); $this->em->persist($job); } $this->em->flush(); }
public function save(BaseEntityInterface $entity) { $this->entityManager->persist($entity); if ($this->autoFlush) { $this->entityManager->flush(); } }
/** * 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(); }
/** * 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 array|Student[] $students */ public function saveAll(array $students) { foreach ($students as $student) { $this->em->persist($student); } $this->em->flush(); }
/** * 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); } }
/** * @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; }
/** * @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(); }
/** * @param MailingList $list */ public function saveList(MailingList $list) { if (!$list->getId()) { $this->em->persist($list); } $this->em->flush($list); }
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; }
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()); }
/** * @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()); } } }
public function createMessage($text, $username, $email = null) { $message = new GuestBookMessage(); $message->setText($text)->setUsername($username)->setEmail($email); $this->manager->persist($message); $this->manager->flush(); }
/** * @param Request $request * @param Response $response * @param $args * @return Response */ public function save(Request $request, Response $response, $args) { $id = trim($request->getHeader('id')[0]); $summary = trim($request->getHeader('summary')[0]); $description = trim($request->getHeader('description')[0]); $dueDate = trim($request->getHeader('dueDate')[0]); if (!$summary) { $response->withStatus(500); } else { try { /** * @var Ticket $ticket ; */ $ticket = null; if ($id) { $ticket = $this->em->find('App\\Entity\\Ticket', $id); } else { $ticket = new Ticket(); } $ticket->setSummary($summary); $ticket->setDescription($description); $ticket->setDueDate($dueDate ? date_create_from_format('j/m/Y', $dueDate) : null); $this->em->persist($ticket); $this->em->flush(); $this->render($response, $ticket); } catch (\Exception $e) { $response->withStatus(500); } } return $response; }
/** * @inheritdoc */ public function delete(UserModel $user) : UserModel { $user->delete(); $this->em->persist($user); $this->em->flush(); return $user; }
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; }
/** * Create a new article with a given title and content * * @param Article $article */ public function create(Article $article) { // The created date can be set on PrePersist event // but this is an example for instructions that can be done while creating the Object $article->setCreatedDate(new \DateTime()); $this->em->persist($article); }
/** * 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(); }
/** * 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; }
/** * @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; }
/** * 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(); }
/** * {@inheritdoc} */ public function persist(TaskInterface $task) { $entity = $this->taskRepository->findByUuid($task->getUuid()); $this->setTask($entity, $task); $this->entityManager->persist($entity); $this->entityManager->flush(); }
/** * @inheritdoc */ public function delete(MessageModel $message) : MessageModel { $message->delete(); $this->em->persist($message); $this->em->flush(); return $message; }
/** * @param ModelInterface $entity * @return void */ public function save(ModelInterface $entity) { if (!$entity instanceof TutorialInterface) { throw new InvalidArgumentException('expect an TutorialInterface object'); } $this->em->persist($entity); $this->em->flush(); }
/** * Write the given item. * * @param mixed $item */ public function writeItem($item) { $this->entityManager->persist($item); ++$this->persistCount; if ($this->options['flushInterval'] && $this->shouldFlush()) { $this->finish(); } }
/** * @param string $path * @return object[] */ private function loadFromFile($path) { $entities = $this->aliceLoader->load($path); foreach ($entities as $entity) { $this->entityManager->persist($entity); } return $entities; }
/** * @param Article $article * @throws \Exception */ public function tryUpdateInsert(Article $article) { $this->tryValidate($article); $this->em->transactional(function () use($article) { // TODO 画像のアップロード処理必要 $this->em->persist($article); }); }