flush() public method

This effectively synchronizes the in-memory state of managed objects with the database.
public flush ( )
Exemplo n.º 1
1
 /**
  * @param PostFlushEventArgs $args
  */
 public function postFlush(PostFlushEventArgs $args)
 {
     if ($this->isInProgress) {
         return;
     }
     $this->initializeFromEventArgs($args);
     if (count($this->queued) > 0) {
         $toOutDate = [];
         foreach ($this->queued as $customerIdentity => $groupedByEntityUpdates) {
             foreach ($groupedByEntityUpdates as $data) {
                 /** @var Account $account */
                 $account = is_object($data['account']) ? $data['account'] : $this->em->getReference('OroCRMAccountBundle:Account', $data['account']);
                 /** @var Channel $channel */
                 $channel = is_object($data['channel']) ? $data['channel'] : $this->em->getReference('OroCRMChannelBundle:Channel', $data['channel']);
                 $entity = $this->createHistoryEntry($customerIdentity, $account, $channel);
                 $toOutDate[] = [$account, $channel, $entity];
                 $this->em->persist($entity);
             }
         }
         $this->isInProgress = true;
         $this->em->flush();
         foreach (array_chunk($toOutDate, self::MAX_UPDATE_CHUNK_SIZE) as $chunks) {
             $this->lifetimeRepo->massStatusUpdate($chunks);
         }
         $this->queued = [];
         $this->isInProgress = false;
     }
 }
Exemplo n.º 2
0
 /**
  * @param Todo $entity
  */
 public function run(EntityInterface $entity)
 {
     assert($entity instanceof Todo);
     $entity->setStatus(new TodoStatus());
     $this->repository->add($entity);
     $this->entityManager->flush();
 }
Exemplo n.º 3
0
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
         $this->markTestSkipped('Doctrine DBAL is not available.');
     }
     if (!class_exists('Doctrine\\Common\\Version')) {
         $this->markTestSkipped('Doctrine Common is not available.');
     }
     if (!class_exists('Doctrine\\ORM\\EntityManager')) {
         $this->markTestSkipped('Doctrine ORM is not available.');
     }
     $this->em = DoctrineOrmTestCase::createTestEntityManager();
     parent::setUp();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::ENTITY_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
     $ids = range(1, 300);
     foreach ($ids as $id) {
         $name = 65 + chr($id % 57);
         $this->em->persist(new SingleIdentEntity($id, $name));
     }
     $this->em->flush();
 }
 public function down(Schema $schema)
 {
     $lookingFor = new Profile\LookingFor();
     $lookingFor->setName('Intimate');
     $this->em->persist($lookingFor);
     $this->em->flush();
 }
 /**
  * Flush on kernel terminate.
  */
 public function onKernelTerminate()
 {
     if ($this->em->isOpen()) {
         $this->em->flush();
         // That was not so hard... And you need a bundle to do that! Poor guy...
     }
 }
Exemplo n.º 6
0
 /**
  * Update the user "lastActivity" on each request
  *
  * @param FilterControllerEvent $event
  */
 public function onCoreController(FilterControllerEvent $event)
 {
     // Here we are checking that the current request is a "MASTER_REQUEST",
     // and ignore any
     // subrequest in the process (for example when
     // doing a render() in a twig template)
     if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
         return;
     }
     // We are checking a token authentification is available before using
     // the User
     if ($this->securityContext->getToken()) {
         $user = $this->securityContext->getToken()->getUser();
         // We are using a delay during wich the user will be considered as
         // still active, in order to
         // avoid too much UPDATE in the
         // database
         // $delay = new \DateTime ();
         // $delay->setTimestamp (strtotime ('2 minutes ago'));
         // We are checking the Admin class in order to be certain we can
         // call "getLastActivity".
         // && $user->getLastActivity() < $delay) {
         if ($user instanceof User) {
             $user->isActiveNow();
             $this->em->persist($user);
             $this->em->flush();
         }
     }
 }
 public function schedule()
 {
     $licenseRepo = $this->em->getRepository('AppBundle:License');
     $drillSchemaEventsRepo = $this->em->getRepository('AppBundle:DrillSchemaEvent');
     $licensesWithoutSchema = $licenseRepo->findWithoutRegisteredSchema();
     foreach ($licensesWithoutSchema as $license) {
         $drillSchemaEvents = $drillSchemaEventsRepo->findByAddonKey($license->getAddonKey());
         if (empty($drillSchemaEvents)) {
             continue;
         }
         $drillRegisteredSchema = new DrillRegisteredSchema();
         $drillRegisteredSchema->setLicenseId($license->getLicenseId());
         $drillRegisteredSchema->setAddonKey($license->getAddonKey());
         $this->em->persist($drillRegisteredSchema);
         foreach ($drillSchemaEvents as $drillSchemaEvent) {
             $sendDate = $this->calculateSendDate($drillSchemaEvent, $license);
             $today = new \DateTime();
             // prevent creating events from past
             if ($sendDate < $today->modify('-2 days')) {
                 continue;
             }
             $drillRegisteredEvent = new DrillRegisteredEvent();
             $drillRegisteredEvent->setDrillRegisteredSchema($drillRegisteredSchema);
             $drillRegisteredEvent->setDrillSchemaEvent($drillSchemaEvent);
             // Calculate
             $drillRegisteredEvent->setSendDate($sendDate);
             $drillRegisteredEvent->setStatus('new');
             $this->em->persist($drillRegisteredEvent);
         }
     }
     $this->em->flush();
 }
 /**
  * @param ProviderLocation $providerLocation
  * @param bool             $withFlush
  */
 public function save(ProviderLocation $providerLocation, $withFlush = true)
 {
     $this->entityManager->persist($providerLocation);
     if ($withFlush) {
         $this->entityManager->flush();
     }
 }
Exemplo n.º 9
0
 public function get($name)
 {
     $uppername = strtoupper($name);
     /*
             //create unique key for kind and uppercased name
             $key = md5('kind.' . $uppername);
             //cache has value return this one
             $cached = Cache::get($key);
             if ($cached) {
                 return $cached;
             }*/
     //find or create in store
     $kind = $this->em->getRepository($this->class)->findOneBy(['name' => $uppername]);
     if (!$kind) {
         $kind = new Kind(new Name($uppername));
         $this->em->persist($kind);
         $this->em->flush();
     }
     /*
             //cache it for next request
             Cache::forever($key, $kind);
             return Cache::get($key);
     */
     return $kind;
 }
Exemplo n.º 10
0
 public function onKernelTerminate(PostResponseEvent $event)
 {
     /** @var Request $request */
     $request = $event->getRequest();
     if (!$this->isEnable || !$this->isLoggableRequest($request)) {
         return;
     }
     try {
         /** @var Response $response */
         $response = $event->getResponse();
         $route = $request->get('_route');
         $content = $this->cleanSensitiveContent($route, $request->getContent());
         $token = $this->tokenStorage->getToken();
         $user = !is_null($token) ? $token->getUser() : null;
         $logRequest = new LogRequest();
         $logRequest->setRoute($route)->setPath($request->getPathInfo())->setMethod($request->getMethod())->setQuery(urldecode($request->getQueryString()))->setContent($content)->setStatus($response->getStatusCode())->setIp($request->getClientIp())->setUser(!is_string($user) ? $user : null);
         if ($this->logResponse($response)) {
             $logRequest->setResponse($response->getContent());
         }
         $this->em->persist($logRequest);
         $this->em->flush();
     } catch (\Exception $e) {
         $this->logger->error(sprintf("LogRequest couldn't be persist : %s", $e->getMessage()));
     }
 }
Exemplo n.º 11
0
 public function testRemovePage()
 {
     $page = new Page();
     $page->setTitle('Test')->setContent('<p>test</p>')->setCurrentSlugUrl('/remove');
     $this->entityManager->persist($page);
     $childPage1 = new Page();
     $childPage1->setTitle('Test child Page 1')->setContent('<p>test child page</p>')->setCurrentSlugUrl('/child1');
     $this->entityManager->persist($childPage1);
     $childPage2 = new Page();
     $childPage2->setTitle('Test child Page 2')->setContent('<p>test child page</p>')->setCurrentSlugUrl('/child2');
     $this->entityManager->persist($childPage2);
     $page->addChildPage($childPage1);
     $page->addChildPage($childPage2);
     $this->entityManager->flush($page);
     $pageSlugId = $page->getCurrentSlug()->getId();
     $childPage1SlugId = $childPage1->getCurrentSlug()->getId();
     $childPage2SlugId = $childPage2->getCurrentSlug()->getId();
     $this->entityManager->remove($page);
     $this->entityManager->flush();
     // make sure data updated correctly
     $this->entityManager->clear();
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $pageSlugId));
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $childPage1SlugId));
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $childPage2SlugId));
 }
 /**
  * Process onReslonse event, updates user history information
  *
  * @param  FilterResponseEvent $event
  * @return bool|void
  */
 public function onResponse(FilterResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         // Do not do anything
         return;
     }
     $request = $event->getRequest();
     $response = $event->getResponse();
     // do not process requests other than in html format
     // with 200 OK status using GET method and not _internal and _wdt
     if (!$this->matchRequest($response, $request)) {
         return false;
     }
     $postArray = ['url' => $request->getRequestUri(), 'user' => $this->user];
     /** @var $historyItem  NavigationHistoryItem */
     $historyItem = $this->em->getRepository('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationHistoryItem')->findOneBy($postArray);
     if (!$historyItem) {
         /** @var $historyItem \Oro\Bundle\NavigationBundle\Entity\NavigationItemInterface */
         $historyItem = $this->navItemFactory->createItem(NavigationHistoryItem::NAVIGATION_HISTORY_ITEM_TYPE, $postArray);
     }
     $historyItem->setTitle($this->titleService->getSerialized());
     // force update
     $historyItem->doUpdate();
     $this->em->persist($historyItem);
     $this->em->flush($historyItem);
     return true;
 }
Exemplo n.º 13
0
 /**
  * Finish processed batch
  */
 protected function finishBatch()
 {
     $this->entityManager->flush();
     if ($this->entityManager->getConnection()->getTransactionNestingLevel() == 1) {
         $this->entityManager->clear();
     }
 }
Exemplo n.º 14
0
 /**
  * Duplicate Jam entities
  *
  * For details see
  * {@link http://stackoverflow.com/questions/9071094/how-to-re-save-the-entity-as-another-row-in-doctrine-2}
  *
  * @param Jam $entity
  * @param integer $count
  */
 public function duplicate(Jam $entity, $count = 0)
 {
     for ($i = 0; $i < $count; $i++) {
         $this->em->persist($this->cloneService->cloneObject($entity));
     }
     $this->em->flush();
 }
 /**
  * Callback method, that is called once form is successfully submitted, without validation errors.
  *
  * @param Form $form
  * @param Nette\Utils\ArrayHash $values
  */
 public function formSucceeded(Form $form, $values)
 {
     if (!($user = $this->userRepository->findOneBy(['email' => $values->email]))) {
         $form['email']->addError("User with given email doesn't exist");
         return;
     }
     // this is not a very secure way of getting new password
     // but it's the same way the symfony app is doing it...
     $newPassword = $user->generateRandomPassword();
     $this->em->flush();
     try {
         $message = new Nette\Mail\Message();
         $message->setSubject('Notejam password');
         $message->setFrom('*****@*****.**');
         $message->addTo($user->getEmail());
         // !!! Never send passwords through email !!!
         // This is only for demonstration purposes of Notejam.
         // Ideally, you can create a unique link where user can change his password
         // himself for limited amount of time, and then send the link.
         $message->setBody("Your new password is {$newPassword}");
         $this->mailer->send($message);
     } catch (Nette\Mail\SendException $e) {
         Debugger::log($e, 'email');
         $form->addError('Could not send email with new password');
     }
     $this->onSuccess($this);
 }
Exemplo n.º 16
0
 /**
  * Publishes a gif and posts a link on social networks
  * @param Gif $gif
  * @return bool
  */
 public function publish(Gif $gif)
 {
     if (!$gif) {
         return false;
     }
     if (!$gif->getGifStatus() == GifState::ACCEPTED) {
         return false;
     }
     $gif->setPublishDate(new DateTime());
     $gif->setGifStatus(GifState::PUBLISHED);
     $gif->generateUrlReadyPermalink();
     // Check if permalink is unique
     /** @var GifRepository $gifsRepo */
     $gifsRepo = $this->em->getRepository('LjdsBundle:Gif');
     $permalink = $gif->getPermalink();
     $i = 1;
     while (!empty($gifsRepo->findBy(['permalink' => $gif->getPermalink(), 'gifStatus' => GifState::PUBLISHED]))) {
         // Generate a new permalink
         $gif->setPermalink($permalink . $i);
         $i++;
     }
     $this->em->flush();
     if ($this->facebookAutopost) {
         $this->facebookService->postGif($gif);
     }
     if ($this->twitterAutopost) {
         $this->twitterService->postGif($gif);
     }
     return true;
 }
Exemplo n.º 17
0
 /**
  * Run all new tasks
  *
  * @throws \InvalidArgumentException
  * @return void
  */
 public function runJobs()
 {
     $cronRepo = $this->entityManager->getRepository('KingdomHallTaskBundle:Task');
     $jobs = $cronRepo->getNewJobs();
     foreach ($jobs as $job) {
         $task = $job->getTask();
         if (!array_key_exists($task, $this->taskServices)) {
             throw new \InvalidArgumentException($task . ' service not found. Available task services : ' . implode(', ', array_keys($this->taskServices)));
         }
         $service = $this->taskServices[$task];
         $parameters = json_decode($job->getParameters());
         $job->setStatus(Task::TASK_STATUS_PENDING);
         $this->entityManager->persist($job);
         $this->entityManager->flush();
         try {
             $service->process($job->getId(), $parameters);
         } catch (\Exception $e) {
             $job->setStatus(Task::TASK_STATUS_ERROR);
             $job->setErrorMessage($e->getMessage());
             $this->entityManager->persist($job);
             $this->entityManager->flush();
             return;
         }
         $job->setStatus(Task::TASK_STATUS_SUCCESS);
         $this->entityManager->persist($job);
         $this->entityManager->flush();
     }
     // Purge old jobs
     $cronRepo->purge();
 }
Exemplo n.º 18
0
 /**
  * @param Tournament $tournament
  * @return void
  */
 public function makeDrawForNextRound(Tournament $tournament)
 {
     $nextRound = $tournament->getCurrentRound() + 1;
     $this->makeDraw($tournament, $nextRound);
     $tournament->setCurrentRound($nextRound);
     $this->manager->flush($tournament);
 }
Exemplo n.º 19
0
 /**
  * @param Organization $organization
  * @param bool         $flush
  */
 public function updateOrganization(Organization $organization, $flush = true)
 {
     $this->em->persist($organization);
     if ($flush) {
         $this->em->flush();
     }
 }
Exemplo n.º 20
0
 /**
  * @param int $id
  * @param string $state
  */
 protected function saveState($id, $state)
 {
     $notification = $this->getById($id);
     $notification->setState($state);
     $this->entityManager->persist($notification);
     $this->entityManager->flush();
 }
Exemplo n.º 21
0
 /**
  * Imports units.
  *
  * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported
  * @throws \Exception If an error occured
  */
 public function importUnits()
 {
     $path = $this->kernel->locateResource(self::UNIT_PATH . self::UNIT_DATA);
     $yaml = new Parser();
     $data = $yaml->parse(file_get_contents($path));
     $count = 0;
     $skipped = 0;
     foreach ($data as $unitName => $unitData) {
         $unit = $this->getUnit($unitName);
         if ($unit === null) {
             $unit = new Unit();
             $unit->setName($unitName);
             $unit->setSymbol($unitData["symbol"]);
             if (array_key_exists("prefixes", $unitData)) {
                 if (!is_array($unitData["prefixes"])) {
                     throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array.");
                 }
                 foreach ($unitData["prefixes"] as $name) {
                     $prefix = $this->getSiPrefix($name);
                     if ($prefix === null) {
                         throw new \Exception("Unable to find SI Prefix " . $name);
                     }
                     $unit->getPrefixes()->add($prefix);
                 }
             }
             $this->entityManager->persist($unit);
             $this->entityManager->flush();
             $count++;
         } else {
             $skipped++;
         }
     }
     return array("imported" => $count, "skipped" => $skipped);
 }
Exemplo n.º 22
0
 /**
  * @param object $object
  * @param string $flush
  */
 public function delete($object, $flush = true)
 {
     $this->entityManager->remove($object);
     if ($flush) {
         $this->entityManager->flush();
     }
 }
 public function sendAction(Request $request)
 {
     $message = $this->messageBuilder->getMessage($request->request->all());
     $this->eventDispatcher->dispatch('slack.message_received', new MessageEvent($message));
     $this->entityManager->flush();
     return new JsonResponse([]);
 }
Exemplo n.º 24
0
 /**
  * @param $entity
  * @param bool $andFlush
  */
 public function delete($entity, $andFlush = true)
 {
     $this->em->remove($entity);
     if ($andFlush) {
         $this->em->flush();
     }
 }
Exemplo n.º 25
0
 protected function createImage(LoaderResult $loaderResult, $mimeType) : ImageInterface
 {
     $image = ($image = new Image())->setPath($loaderResult->getPath())->setSize($loaderResult->getSize())->setMimeType($mimeType)->setUploadedAt(new \DateTime());
     $this->em->persist($image);
     $this->em->flush($image);
     return $image;
 }
Exemplo n.º 26
0
 /**
  * Make sure the menu objects exist in the database for each locale.
  */
 public function makeSureMenusExist()
 {
     $locales = array_unique($this->getLocales());
     $required = array();
     foreach ($this->menuNames as $name) {
         $required[$name] = $locales;
     }
     $menuObjects = $this->em->getRepository('KunstmaanMenuBundle:Menu')->findAll();
     foreach ($menuObjects as $menu) {
         if (array_key_exists($menu->getName(), $required)) {
             $index = array_search($menu->getLocale(), $required[$menu->getName()]);
             if ($index !== false) {
                 unset($required[$menu->getName()][$index]);
             }
         }
     }
     foreach ($required as $name => $locales) {
         foreach ($locales as $locale) {
             $menu = new Menu();
             $menu->setName($name);
             $menu->setLocale($locale);
             $this->em->persist($menu);
         }
     }
     $this->em->flush();
 }
Exemplo n.º 27
0
 public function clearCustomerShoppingCarts()
 {
     $customer = $this->getCustomer();
     $customer->setSessionId(new ArrayCollection());
     $this->entityManager->persist($customer);
     $this->entityManager->flush();
 }
Exemplo n.º 28
0
 /**
  * onAuthenticationSuccess
  *
  * @author     Joe Sexton <*****@*****.**>
  * @param     InteractiveLoginEvent $event
  */
 public function onAuthenticationSuccess(InteractiveLoginEvent $event)
 {
     $user = $this->getUser();
     $user->setLoginAttempts(0);
     $this->em->persist($user);
     $this->em->flush();
 }
Exemplo n.º 29
0
 protected function setUpOperators()
 {
     $this->op1 = $this->createSimpleOperator(DataTypes::NUMBER_TYPE, 'input', '>', 'groesser');
     $this->op2 = $this->createSimpleOperator(DataTypes::NUMBER_TYPE, 'input', '<', 'kleiner');
     $this->op3 = $this->createOperator(DataTypes::DATETIME_TYPE, 'datepicker', '<', 'kleiner');
     $this->em->flush();
 }
Exemplo n.º 30
0
 /**
  * @param $entity
  */
 public function removeEntity($entity)
 {
     $this->em->remove($entity);
     $this->em->flush();
     $isFound = $this->em->getRepository(get_class($entity))->findOneBy(['id' => $entity->getId()]);
     $this->assertNull($isFound);
 }