flush() public method

This effectively synchronizes the in-memory state of managed objects with the database.
public flush ( object $document = null, array $options = [] )
$document object
$options array Array of options to be used with batchInsert(), update() and remove()
Beispiel #1
0
 public function create($username, $password, $roles)
 {
     $user = new Document\User();
     $user->setUsername($username)->setPassword($password)->setRoles($roles);
     $this->manager->persist($user);
     $this->manager->flush();
 }
Beispiel #2
0
 protected function createImage(LoaderResult $loaderResult, $mimeType) : ImageInterface
 {
     $image = ($image = new Image())->setPath($loaderResult->getPath())->setSize($loaderResult->getSize())->setMimeType($mimeType)->setUploadedAt(new \DateTime());
     $this->dm->persist($image);
     $this->dm->flush($image);
     return $image;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $model = $input->getArgument('model');
     $seeds = $input->getArgument('seeds');
     $io = new SymfonyStyle($input, $output);
     if (!class_exists($model)) {
         $io->error(array('The model you specified does not exist.', 'You can create a model with the "model:create" command.'));
         return 1;
     }
     $this->dm = $this->createDocumentManager($input->getOption('server'));
     $faker = Faker\Factory::create();
     AnnotationRegistry::registerAutoloadNamespace('Hive\\Annotations', dirname(__FILE__) . '/../../');
     $reflectionClass = new \ReflectionClass($model);
     $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC);
     $reader = new AnnotationReader();
     for ($i = 0; $i < $seeds; $i++) {
         $instance = new $model();
         foreach ($properties as $property) {
             $name = $property->getName();
             $seed = $reader->getPropertyAnnotation($property, 'Hive\\Annotations\\Seed');
             if ($seed !== null) {
                 $fake = $seed->fake;
                 if (class_exists($fake)) {
                     $instance->{$name} = $this->createFakeReference($fake);
                 } else {
                     $instance->{$name} = $faker->{$seed->fake};
                 }
             }
         }
         $this->dm->persist($instance);
     }
     $this->dm->flush();
     $io->success(array("Created {$seeds} seeds for {$model}"));
 }
 function delete($entity, $flush = 1)
 {
     $this->dm->remove($entity);
     if (1 == $flush) {
         $this->dm->flush($entity);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function deletePartner(PartnerInterface $partner, $andFlush = true)
 {
     $this->dm->remove($partner);
     if ($andFlush) {
         $this->dm->flush();
     }
 }
 /**
  * @param string $uniqueKey
  */
 public function track(DuplicableInterface $duplicable)
 {
     $duplicateEmail = new Duplication();
     $duplicateEmail->setTrackingDate(new \DateTime('now'))->setUniqueKey($duplicable->getUniqueKey());
     $this->dm->persist($duplicateEmail);
     $this->dm->flush($duplicateEmail);
 }
Beispiel #7
0
 /**
  * @param Item        $item
  * @param string|null $collection
  * @return Item
  */
 public function delete($item, $collection = null)
 {
     $this->setCollection($collection);
     $this->dm->remove($item);
     $this->dm->flush();
     return $item;
 }
 /**
  *  Loads all fixtures data into the testing database
  * @return $this
  */
 public function loadData()
 {
     $email = new EmailDocument('*****@*****.**');
     $this->odm->persist($email);
     $this->odm->flush();
     return $this;
 }
 /**
  * @param Projection $projection
  */
 public function remove(Projection $projection)
 {
     $storedProjection = $this->repository->find($projection->getProjectionName() . '_' . $projection->getAggregateId());
     if (!empty($storedProjection)) {
         $this->manager->remove($storedProjection);
         $this->manager->flush();
     }
 }
Beispiel #10
0
 /**
  * @param Aggregate $aggregate
  */
 public function add(Aggregate $aggregate)
 {
     foreach ($aggregate->getEvents() as $event) {
         $storedEvent = new StoredEvent($aggregate->getAggregateId(), get_class($event), $event);
         $this->manager->persist($storedEvent);
     }
     $this->manager->flush();
 }
Beispiel #11
0
 /**
  * Persists a vote.
  *
  * @param VoteInterface $vote
  * @param VotableCommentInterface $comment
  * @return void
  */
 public function addVote(VoteInterface $vote, VotableCommentInterface $comment)
 {
     $vote->setComment($comment);
     $comment->setScore($comment->getScore() + $vote->getValue());
     $this->dm->persist($comment);
     $this->dm->persist($vote);
     $this->dm->flush();
 }
Beispiel #12
0
 public function remove($key)
 {
     $cache = $this->dm->getRepository('SGLiveChatBundle:CacheEntry')->getByKey($key);
     if ($cache) {
         $this->dm->remove($cache);
     }
     $this->dm->flush();
     return true;
 }
 /**
  * @inheritdoc
  */
 public function deleteFile($id)
 {
     $file = $this->getFile($id);
     if ($file === null) {
         return false;
     }
     $this->documentManager->remove($file);
     $this->documentManager->flush();
     return true;
 }
Beispiel #14
0
 /**
  * @depends testLang
  * @param $lang
  */
 public function testTranslationDelete($lang)
 {
     $language = $this->documentManager->find(get_class($lang->language), $lang->language->getId());
     $translation = $this->documentManager->find(get_class($lang->translation), $lang->translation->getId());
     $language->removeTranslation($translation);
     $this->documentManager->flush();
     $this->documentManager->remove($translation);
     $this->documentManager->remove($language);
     $this->documentManager->flush();
 }
Beispiel #15
0
 /**
  * @param User $user
  * @param Router $router
  * @return \Zend\EventManager\ResponseCollection
  */
 public function removeItems(User $user)
 {
     try {
         $this->getEventManager()->trigger(static::EVENT_REMOVE_ITEMS, $this, compact('user'));
         $this->documentManager->flush();
         return true;
     } catch (\Exception $e) {
         $this->documentManager->clear();
         return false;
     }
 }
 public function testFindPartner()
 {
     $p = $this->partnerMgr->createPartner(Partner::ROLE_CUSTOMER, Partner::ORGANISATION);
     $p->setPartnerId('PartnerTest002');
     $p->addRole(Partner::ROLE_EMPLOYEE);
     $this->dm->persist($p);
     $this->dm->flush();
     $partner = $this->partnerMgr->findOneByPartnerId('PartnerTest002');
     $this->assertTrue($partner instanceof PartnerInterface);
     $this->assertEquals(Partner::ORGANISATION, $partner->getType());
     $this->assertEquals(array(Partner::ROLE_CUSTOMER, Partner::ROLE_EMPLOYEE), $partner->getRoles());
 }
Beispiel #17
0
 /**
  * Creates User, specially for fixtures
  *
  * @param array $userData
  *
  * @return BackendUser $user
  */
 public function registerFixturesUser(array $userData)
 {
     $user = new BackendUser();
     $user->setEmail($userData['email']);
     $user->setUsername($userData['username']);
     $user->setPlainPassword($userData['password']);
     $user->setEnabled(true);
     $user->setLocked(false);
     $user->setLastLogin(new \DateTime(date('Y-m-d H:i:s')));
     $this->dm->persist($user);
     $this->dm->flush();
     return $user;
 }
 private function persistEmailMessage(Message $message, $type, $status, $arguments)
 {
     $email = new Email();
     $email->setType($type);
     $email->setBody($message->getMessage());
     $email->setEmailAddress($message->getTo());
     $email->setFrom($message->getFrom());
     $email->setSubject($message->getSubject());
     $email->setArguments($arguments);
     $email->setStatus($status);
     $this->documentManager->persist($email);
     $this->documentManager->flush();
 }
Beispiel #19
0
 /**
  * Разбор xml и сохранение в базу данных
  * @return $this
  */
 public function parse()
 {
     $this->_dm = $this->getServiceLocator()->get('doctrine-document');
     $this->_repository = $this->_dm->getRepository($this->_document);
     if (isset($this->_xml->Valute)) {
         /** @var \SimpleXMLElement $item */
         foreach ($this->_xml->Valute as $item) {
             if (isset($item->CharCode)) {
                 $this->save((string) $item->CharCode, $item);
             }
         }
     }
     $this->_dm->flush();
     return $this;
 }
 /**
  * @param Doctrine\ODM\MongoDB\DocumentManager $documentManager
  */
 private function _save(DocumentManager $documentManager)
 {
     try {
         if ($this->queue->count() <= 0) {
             $this->getLog()->debug('Queue contains no documents for processing.');
             return;
         }
         $this->getLog()->debug('Queue contains: ' . $this->queue->count() . ' documents.');
         foreach ($this->queue as $object) {
             $name = $object->getName();
             $_id = $object->getId();
             if (empty($_id)) {
                 $document = $object->getInstance();
                 $this->getLog()->info('Saving document: ' . $name . ' (' . $document->__toString() . ')');
                 //Debug::dump($document, 3);
                 $documentManager->persist($document);
                 $documentManager->flush();
                 $documentId = $document->getId();
                 if (!empty($name) && !empty($documentId)) {
                     $this->getLog()->info('Marking document: ' . $name . ' (' . get_class($document) . ') as persisted in cache with ID: ' . $documentId);
                     $this->markAsPersisted($name, $documentId, $document);
                 }
             }
         }
         $this->queue->clear();
         $this->getLog()->debug('Finished saving documents, queue now contains: ' . $this->queue->count() . ' documents.');
     } catch (\Exception $ex) {
         $this->getLog()->err('An error occurred while attempting to save one or more documents. ' . get_class($ex) . ' handled, with message: ' . $ex->getMessage());
         $documentManager->close();
         throw $ex;
     }
 }
Beispiel #21
0
 /**
  * Update parent for Node
  *
  * @param  array $params
  * @return Category $child
  *
  * @throws LogicException
  */
 public function updateParent($params)
 {
     /**
      * @var $child Category
      * @var $parent Category
      */
     $repo = $this->dm->getRepository($this->model);
     if ($categoryParentId = $params['parentId']) {
         $parent = $repo->find($categoryParentId);
         if (!$parent) {
             throw new LogicException('Nothing found');
         }
     }
     if ($categoryId = $params['id']) {
         $child = $repo->find($categoryId);
         if (!$child) {
             throw new LogicException('Nothing found');
         }
     }
     $child->setParent($parent);
     $this->dm->persist($child);
     $this->dm->flush();
     $parent->removeChild($child);
     $parent->addChild($child);
     $this->dm->persist($parent);
     $this->dm->flush();
     return $child;
 }
Beispiel #22
0
 /**
  * @param \Hive\Resource $resource
  * @param string $uri
  * @param string $property
  */
 protected function setupDelete($resource, $uri = null, $property = null)
 {
     if ($uri === null) {
         $uri = $resource->settings['actions']['Delete']['uri'];
     }
     $this->klein->respond('DELETE', $uri, function ($request, $response, $service, $app) use($resource, $property) {
         /**
          * @var Request $request
          * @var Response $response
          * @var ServiceProvider $service
          * @var App $app
          */
         $resourceRequest = ResourceRequest::create('Delete', $resource, $request, $response, $service, $app, $property);
         if (!call_user_func($resource->allowRequest, $resourceRequest)) {
             return false;
         }
         $result = call_user_func($resource->findOne, $resourceRequest);
         if ($result === null) {
             throw $this->createHttpException(404);
         }
         $this->dm->remove($result);
         $this->dm->flush();
         return call_user_func($resource->renderResult, $resourceRequest, $result);
     });
 }
Beispiel #23
0
 /**
  * Create invoice for order Id
  *
  * @param Order $order
  *
  * @return Invoice $invoice|false
  *
  */
 public function createInvoiceForOrder(Order $order)
 {
     if ($order) {
         if (!$order->getInvoice()) {
             $invoice = new Invoice();
             $this->dm->persist($invoice);
             $this->dm->flush();
             // Update order data
             $order->setInvoice($invoice);
             $this->dm->persist($order);
             $this->dm->flush();
             return $invoice;
         }
     }
     return false;
 }
 /**
  * @param User $user
  * @param $date
  * @param $lineNumber
  * @param $from
  * @param $to
  * @param $lineDeparture
  * @param int $continuation
  * @return Ticket|null
  */
 public function buyTicket(User $user, $date, $lineNumber, $from, $to, $lineDeparture, $continuation = 0)
 {
     // Get Trip
     $trip = $this->documentManager->getRepository('AppBundle:Trip')->findOneBy(['date' => $date, 'lineNumber' => (int) $lineNumber, 'departure' => (int) $lineDeparture]);
     // If doesn't exists
     if (!$trip) {
         // Check lineNumber | from | to | lineDeparture
         if (!($line = $this->trainInformation->verifyLine($lineNumber, $from, $to, $lineDeparture))) {
             throw new BadRequestHttpException('Invalid trip.');
         }
         // Create Trip
         $trip = new Trip($lineNumber, $line['stations'], $date, $lineDeparture, $this->trainInformation->getCapacity());
     }
     // Get Train capacity
     if ($trip->getAvailableCapacity($from, $to) == 0) {
         throw new BadRequestHttpException('Trip is full.');
     }
     if ($continuation == 1 && !$this->creditCardValidator->validate($user->getCreditCard())) {
         throw new BadRequestHttpException('Credit Card failed.');
     }
     // Create Ticket
     $ticket = new Ticket($user, $trip, $from, $to);
     // Update Trip
     $trip->addTicketBought($from, $to);
     // Persist
     $this->documentManager->persist($ticket);
     $this->documentManager->persist($trip);
     $this->documentManager->flush();
     return $ticket;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $limit = $input->getOption('limit');
     $emailsRepository = $this->documentManager->getRepository(Email::REPOSITORY);
     $emails = $emailsRepository->findBy(array('status' => Email::STATUS_TEMPORARY_ERROR), null, $limit);
     foreach ($emails as $email) {
         /* @var $email Email */
         $type = $email->getType();
         $emailAddress = $email->getEmailAddress();
         $arguments = $email->getArguments();
         $this->eventDispatcher->dispatch(EmailEvent::RESEND, new EmailEvent($type, $emailAddress, $arguments));
         $status = $this->communicationService->sendEmail($type, $emailAddress, $arguments);
         $email->setStatus($status);
         $this->documentManager->persist($email);
     }
     $this->documentManager->flush();
 }
 /**
  * Saves a message
  *
  * @param MessageInterface $message
  * @param Boolean $andFlush Whether to flush the changes (default true)
  */
 public function saveMessage(MessageInterface $message, $andFlush = true)
 {
     $message->denormalize();
     $this->dm->persist($message);
     if ($andFlush) {
         $this->dm->flush();
     }
 }
 /**
  * @depends testCreateProtocol
  * @depends testDeleteUpload
  */
 public function testDeleteProtocol(Protocol $protocol)
 {
     $forms = $this->dm->getRepository('FormBundle:Form')->findByName($protocol->getForm()->getName());
     foreach ($forms as $form) {
         $this->dm->remove($form);
     }
     $this->dm->flush();
 }
 public function testManyToManyReferences()
 {
     $categoryOne = new Category('one');
     $this->dm->persist($categoryOne);
     $categoryTwo = new Category('two');
     $this->dm->persist($categoryTwo);
     $document = new Document(new \MongoId(), 'document');
     $document->categories[] = $categoryOne;
     $this->dm->persist($document);
     $this->dm->flush();
     $form = $this->factory->create($this->typeFQCN ? FormType::CLASS : 'form', $document)->add('categories', $this->typeFQCN ? DocumentType::CLASS : 'document', ['class' => Category::class, 'multiple' => true, 'expanded' => true, 'document_manager' => 'default']);
     $view = $form->createView();
     $categoryView = $view['categories'];
     $this->assertInstanceOf(FormView::class, $categoryView);
     $this->assertCount(2, $categoryView->children);
     $this->assertTrue($categoryView->children[0]->vars['checked']);
     $this->assertFalse($categoryView->children[1]->vars['checked']);
 }
 public function testManyToManyReferences()
 {
     $categoryOne = new Category('one');
     $this->dm->persist($categoryOne);
     $categoryTwo = new Category('two');
     $this->dm->persist($categoryTwo);
     $document = new Document(new \MongoId(), 'document');
     $document->categories[] = $categoryOne;
     $this->dm->persist($document);
     $this->dm->flush();
     $form = $this->factory->create('form', $document)->add('categories', 'document', array('class' => 'Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Category', 'multiple' => true, 'expanded' => true, 'document_manager' => 'default'));
     $view = $form->createView();
     $categoryView = $view['categories'];
     $this->assertInstanceOf('Symfony\\Component\\Form\\FormView', $categoryView);
     $this->assertCount(2, $categoryView->children);
     $this->assertTrue($categoryView->children[0]->vars['checked']);
     $this->assertFalse($categoryView->children[1]->vars['checked']);
 }
 protected function truncate()
 {
     if ($this->list) {
         foreach ($this->list as $document) {
             $this->manager->remove($document);
         }
         $this->manager->flush();
     }
 }