/** * @param float $discount */ public function apply($discount) { $this->entityManager->transactional(function () use($discount) { foreach ($this->items->findAll() as $item) { $item->applyDiscount($discount); } }); $this->entityManager->clear(); }
/** * Finish processed batch */ protected function finishBatch() { $this->entityManager->flush(); if ($this->entityManager->getConnection()->getTransactionNestingLevel() == 1) { $this->entityManager->clear(); } }
private function getWeaponsInfo() { $parameters = array('iDisplayStart' => 0, 'iDisplayLenght' => 50, 'type' => 1); $response = file_get_contents($this->url . '?' . http_build_query($parameters)); $response = json_decode($response, true); $data = $response['aaData']; $formattedData = array(); //Formatting Data foreach ($data as $value) { $index = $value[0]['name'] . $value[0]['requiredLevel']; $formattedData[$index] = array('name' => $value[0]['name'], 'description' => $value[0]['description'], 'level' => $value[0]['requiredLevel']); } $i = 0; foreach ($formattedData as $value) { $i++; $item = new Item(); $item->setName($value['name']); $item->setDescription($value['description']); $item->setLevel($value['level']); $item->setType('weapon'); $this->em->persist($item); if ($i % 20 === 0) { $this->em->flush(); $this->em->clear(); } } $this->em->flush(); $this->em->clear(); }
protected function tearDown() { // Clean anything still idle in the UOW $this->_em->clear(); // Clear out anything set in the db (schema is recreated on setUp() $this->_schemaTool->dropDatabase(); }
private function setupTestSchema() { $this->entityManager->clear(); $classes = $this->entityManager->getMetaDataFactory()->getAllMetaData(); $tool = new Doctrine\ORM\Tools\SchemaTool($this->entityManager); // $tool->dropSchema($classes); $tool->createSchema($classes); }
/** * Do persist into EntityManager * * @param array $items */ private function write(array $items) { foreach ($items as $item) { $this->em->persist($item); } $this->em->flush(); $this->em->clear(); }
/** * Sweeps the database tables and clears the EntityManager. * * @return void */ protected function tearDown() { if (null === static::$_conn) { return; } if (null !== static::$_em) { static::$_em->clear(); } }
/** * {@inheritdoc} */ public function write(array $items) { foreach ($items as $item) { $this->entityManager->persist($item); $this->detachFixer->fixEntityAssociationFields($item, 1); } $this->entityManager->flush(); $this->entityManager->clear(); }
protected function clean() { $em = self::$em; $reflectedEm = new \ReflectionClass($em); if ($reflectedEm->hasProperty('repositories')) { $property = $reflectedEm->getProperty('repositories'); $property->setAccessible(true); $property->setValue($em, array()); } self::$em->clear(); }
/** * {@inheritdoc} */ public function write(array $items) { foreach ($items as $item) { $this->entityManager->persist($item); $this->detachFixer->fixEntityAssociationFields($item, 1); } $this->entityManager->flush(); $configuration = $this->contextRegistry->getByStepExecution($this->stepExecution)->getConfiguration(); if (empty($configuration[self::SKIP_CLEAR])) { $this->entityManager->clear(); } }
/** @test */ public function should_add_new_user() { $userStub = UserStub::create(); $user = $this->repository->add($userStub); $this->em->clear(); $user = $this->repository->userOfEmail($userStub->email()); $this->assertEquals($userStub->id(), $user->id()); $this->assertEquals($userStub->email(), $user->email()); $this->assertEquals($userStub->username(), $user->username()); $this->assertEquals($userStub->firstName(), $user->firstName()); $this->assertEquals($userStub->lastName(), $user->lastName()); }
protected function setUp() { $config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../Entity/'], true, null, null, false); $this->manager = EntityManager::create(['driver' => 'pdo_sqlite', 'memory' => true], $config); (new SchemaTool($this->manager))->createSchema($this->manager->getMetadataFactory()->getAllMetadata()); $this->manager->persist(new Person('john', 'John', 11, null)); $this->manager->persist(new Person('jane', 'Jane', 21, '*****@*****.**')); $this->manager->persist(new Person('joey', 'Joey', 31, '')); $this->manager->flush(); $this->manager->clear(); $this->transformer = SQLTransformerBuilder::make()->build(); }
protected function getConnection() { if (is_null($this->app)) { $this->app = $this->getApplication(); } $this->em = EntityManagerFactory::initializeTestEntityManager($this->app); $pdo = $this->em->getConnection()->getWrappedConnection(); $this->em->clear(); $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em); $classes = $this->em->getMetadataFactory()->getAllMetadata(); $tool->dropSchema($classes); $tool->createSchema($classes); return $this->createDefaultDBConnection($pdo, 'fcms_test'); }
public function testTransformedValueIsStored() { $this->setUpEntityManager(); $test = new Test(); $test->setValue(self::VALUE); $this->em->persist($test); $this->em->flush(); $dbRow = $this->em->getConnection()->fetchAssoc('SELECT * FROM tests WHERE id = ?', [$test->getId()]); $this->assertEquals(self::VALUE_TRANSFORMED, $dbRow['value']); $this->assertEquals(self::VALUE, $test->getValue()); $this->em->clear(); $test = $this->em->find('Transformable\\Fixture\\Test', 1); $this->assertEquals(self::VALUE, $test->getValue()); }
/** * Runs all sample data providers. * * @param callable|null $callback A function that will be called with the name of each provider as a parameter. * @return void */ public function run(callable $callback = null) { $this->em->beginTransaction(); foreach ($this->providers as $provider) { $this->em->clear(); /** @var $provider \Brick\Sample\SampleDataProvider */ $provider = $this->injector->instantiate($provider); if ($callback) { $callback($provider->getName()); } $provider->run(); $this->em->flush(); } $this->em->commit(); }
public function _after(\Codeception\TestCase $test) { if (!self::$em) { throw new \Codeception\Exception\ModuleConfig(__CLASS__, "Doctrine2 module requires EntityManager explictly set.\n" . "You can use your bootstrap file to assign the EntityManager:\n\n" . '\\Codeception\\Module\\Doctrine2::$em = $em'); } if ($this->config['cleanup']) { self::$em->getConnection()->rollback(); } $em = self::$em; $reflectedEm = new \ReflectionClass($em); $property = $reflectedEm->getProperty('repositories'); $property->setAccessible(true); $property->setValue($em, array()); self::$em->clear(); }
private function setupTestSchema() { $this->entityManager->clear(); if (empty($this->metaDataClassNames)) { $classes = $this->entityManager->getMetaDataFactory()->getAllMetaData(); } else { $classes = []; foreach ($this->metaDataClassNames as $className) { $classes[] = $this->entityManager->getMetaDataFactory()->getMetadataFor($className); } } $tool = new Doctrine\ORM\Tools\SchemaTool($this->entityManager); // $tool->dropSchema($classes); $tool->createSchema($classes); }
/** * Get database connection. * * @static * * @return DatabaseConnection */ public static function create($mappingPath) { self::$_config = array('dbname' => $GLOBALS['db_name'], 'driver' => 'pdo_mysql', 'host' => $GLOBALS['db_host'], 'user' => $GLOBALS['db_user'], 'password' => $GLOBALS['db_password'], 'charset' => 'UTF8'); self::createDatabase(self::$_config); /** @var \Doctrine\ORM\Configuration */ $metadataConfiguration = Setup::createAnnotationMetadataConfiguration(array($mappingPath), true, null, null, false); self::$_em = EntityManager::create(self::$_config, $metadataConfiguration); $pdo = self::$_em->getConnection()->getWrappedConnection(); self::$_em->clear(); $tool = new SchemaTool(self::$_em); $classes = self::$_em->getMetaDataFactory()->getAllMetaData(); $tool->dropSchema($classes); $tool->createSchema($classes); return new self(); }
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)); }
private function flush() { $flushTimeStart = microtime(true); $this->em->flush(); $this->em->clear(); $this->logger->addInfo(sprintf('Flush db take %s sec to proceed', microtime(true) - $flushTimeStart)); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->em = $this->getContainer()->get('doctrine.orm.entity_manager'); $f = $this->em->createQuery('SELECT i ' . 'FROM AppBundle:Image i ' . 'LEFT JOIN AppBundle:FundReport r WITH r.photo=i ' . 'LEFT JOIN AppBundle:BizAction a WITH a.photo=i ' . 'WHERE ' . '(i.create_time = \'0000-00-00 00:00:00\' or DATE_DIFF(CURRENT_TIMESTAMP(),i.create_time)>0) and ' . 'r.id is null and ' . 'a.id is null')->execute(); // $prefix = __DIR__ . '/../../../web'; foreach ($f as $v) { $target = $prefix . $v->getUri(); @unlink($target); $this->em->remove($v); $v = null; } $this->em->flush(); $this->em->clear(); return 0; }
public function getConnection() { $this->em = EntityManagerFactory::createEntityManager(__DIR__ . '/../../../../app/config/parameters_test.yml', __DIR__ . '/../../../../src', false); // Retrieve PDO instance $pdo = $this->em->getConnection()->getWrappedConnection(); // Clear Doctrine to be safe $this->em->clear(); // Schema Tool to process our entities $tool = new SchemaTool($this->em); $classes = $this->em->getMetaDataFactory()->getAllMetaData(); // Drop all classes and re-build them for each test case $tool->dropSchema($classes); $tool->createSchema($classes); // Pass to PHPUnit return $this->createDefaultDBConnection($pdo, 'angular_cms_test'); }
public function clear() { $this->em->clear(); unset($this->images); $this->images = new ArrayCollection(); return $this; }
/** * @param \Scribe\Doctrine\ORM\Mapping\Entity|mixed $entity * @param mixed $index * * @throws \Exception * * @return $this */ protected function loadAndMergeEntity($index, $entity) { try { $entityMetadata = $this->getClassMetadata($this->getEntityFQCN()); $this->identLog[] = $identity = $entityMetadata->getIdentifierValues($entity); if (count($identity) > 0) { $identity = [key($identity) => current($identity)]; } elseif (!$entity->hasIdentity()) { OutBuffer::stat('+y/b-preload +y/i-[warns]+w/- import could not begin for "%s:%d"', basename($this->metadata->getName()), $index); OutBuffer::stat('+y/b-preload +y/i-[warns]+w/- import strategy "merge" unavailable due to failed identifier map resolution'); } $repository = $this->manager->getRepository($this->getEntityFQCN()); $entitySearched = $repository->findOneBy($identity); $this->manager->initializeObject($entitySearched); if ($entitySearched && !$entity->isEqualTo($entitySearched)) { $mapper = new HydratorManager(new HydratorMapping(true)); $entity = $mapper->getMappedObject($entity, $entitySearched); $this->manager->remove($entitySearched); $this->manager->merge($entity); $this->manager->persist($entity); $this->manager->flush(); $this->manager->clear(); ++$this->countUpdate; return $this; } elseif ($entitySearched && $entity->isEqualTo($entitySearched)) { $entity = $entitySearched; ++$this->countSkip; return $this; } $this->loadAndPersistEntity($entity); } catch (\Exception $e) { throw $e; } return $this; }
/** * Purify session description * @param OutputInterface $output */ protected function purifySessionDescription(OutputInterface $output) { $cleaned = 0; $offset = 1; $limit = self::QUERY_LIMIT; $total = $this->sessionDescriptionManager->getTotalSessionDescriptionCount(); $progress = new ProgressBar($output, $total); $progress->setRedrawFrequency(208); $output->writeln("<info>Starting cleanup of session descriptions...</info>"); $progress->start(); do { $descriptions = $this->sessionDescriptionManager->findBy(array(), array('id' => 'ASC'), $limit, $offset); foreach ($descriptions as $description) { $original = $description->getDescription(); $clean = $this->purifier->purify($original); if ($original != $clean) { $cleaned++; $description->setDescription($clean); $this->sessionDescriptionManager->update($description, false); } $progress->advance(); } $offset += $limit; $this->em->flush(); $this->em->clear(); } while (count($descriptions) == $limit); $progress->finish(); $output->writeln(''); $output->writeln("<info>{$cleaned} Session Descriptions updated.</info>"); }
/** * {@inheritdoc} * @param string|array $entity * @return EntityManager */ public function clear($entityName = null) { foreach (is_array($entityName) ? $entityName : func_get_args() + array(0 => NULL) as $item) { parent::clear($item); } return $this; }
/** * @param \Generator $fileRows * @param \DateTime|null $until * * @throws FormatException * * @return array */ private function collectFile($fileRows, \DateTime $until = null) { $stat = ['proceed' => 0, 'succeed' => 0]; // TODO make it configurable $batchSize = 100; $this->consecutiveInvalid = 0; // TODO there is no place for that foreach ($fileRows as $row) { $stat['proceed']++; $logEntry = $this->createLogEntry($row); if (!$this->isLogEntryValid($logEntry)) { continue; } if (!$this->shouldContinue($logEntry, $until)) { break; } $this->entityManager->persist($logEntry); $stat['succeed']++; if ($stat['succeed'] % $batchSize === 0) { $this->entityManager->flush(); $this->entityManager->clear(); } } $this->entityManager->flush(); $this->entityManager->clear(); return $stat; }
/** * @param ImapEmailFolder $imapFolder */ protected function clearFolder($imapFolder) { $folder = $imapFolder->getFolder(); $query = $this->em->getRepository('OroEmailBundle:EmailUser')->getEmailUserByFolder($folder)->getQuery(); $iterableResult = $query->iterate(); $i = 0; while (($row = $iterableResult->next()) !== false) { /** @var EmailUser $emailUser */ $emailUser = $row[0]; $email = $emailUser->getEmail(); $this->em->remove($emailUser); $imapEmails = $this->em->getRepository('OroImapBundle:ImapEmail')->findBy(['email' => $email, 'imapFolder' => $imapFolder]); foreach ($imapEmails as $imapEmail) { $this->em->remove($imapEmail); } if ($i % self::BATCH_SIZE === 0) { $this->em->flush(); $this->em->clear('OroEmailBundle:EmailUser'); $this->em->clear('OroImapBundle:ImapEmail'); } ++$i; } if ($i > 0) { $this->logger->notice(sprintf('ImapFolder with ID %s cleared. Removed %d emails.', $imapFolder->getId(), $i)); } $this->em->flush(); }
/** * Cleans doctrine's UOF to prevent: * - "eating" too much memory * - storing too many object which cause slowness of sync process * Tracks time when last batch was saved. * Calculates time between batch saves. * * @param bool $isFolderSyncComplete * @param null|EmailFolder $folder */ protected function cleanUp($isFolderSyncComplete = false, $folder = null) { $this->emailEntityBuilder->getBatch()->clear(); /** * Clear entity manager. */ $map = $this->entitiesToClear(); foreach ($map as $entityClass) { $this->em->clear($entityClass); } /** * In case folder sync completed and batch save time exceeded limit - throws exception. */ if ($isFolderSyncComplete && $folder != null && $this->dbBatchSaveTime > 0 && $this->dbBatchSaveTime > self::DB_BATCH_TIME) { throw new SyncFolderTimeoutException($folder->getOrigin()->getId(), $folder->getFullName()); } elseif ($isFolderSyncComplete) { /** * In case folder sync completed without batch save time exceed - reset dbBatchSaveTime. */ $this->dbBatchSaveTime = -1; } else { /** * After batch save - calculate time difference between batches */ if ($this->dbBatchSaveTimestamp !== 0) { $this->dbBatchSaveTime = time() - $this->dbBatchSaveTimestamp; $this->logger->info(sprintf('Batch save time: "%d" seconds.', $this->dbBatchSaveTime)); } } $this->dbBatchSaveTimestamp = time(); }
public function play(EntityManager $entityManager, array $input) { for ($i = 0; $i < 2000; $i++) { $vehicle = new Vehicle(); $vehicle->setOffer("Brand New Audi A8 for just 80.000 €"); $vehicle->setPrice(1000 * ($i % 100)); $vehicle->setAdmission(new \DateTime(1980 + rand(0, 32) . "-01-01")); $vehicle->setKilometres(400 * rand(1, 10000)); $entityManager->persist($vehicle); if ($i % 1000 == 0) { $entityManager->flush(); $entityManager->clear(); } } $entityManager->flush(); $entityManager->clear(); }