/**
  * Get profiles from Elasticsearch.
  *
  * @return array
  */
 public function getProfiles()
 {
     $repo = $this->manager->getRepository('ONGRSettingsBundle:Setting');
     // Create aggregated profiles list from all available settings.
     $aggregation = new TermsAggregation('profile_agg');
     $aggregation->setField('profile');
     // Create query.
     $search = $repo->createSearch()->addAggregation($aggregation)->setFields(['profile']);
     // Process query. Get RESULTS_RAW.
     $results = $repo->execute($search, Repository::RESULTS_ARRAY);
     return $results;
 }
 /**
  * Before a test method is run, a template method called setUp() is invoked.
  */
 public function setUp()
 {
     $this->esRatesResult = [];
     foreach ($this->ratesFixture as $currency => $rate) {
         $this->esRatesBackup[0]['rates'][] = ['name' => $currency, 'value' => $rate];
     }
     $searchMock = $this->getMock('ONGR\\ElasticsearchBundle\\DSL\\Search');
     $searchMock->expects($this->any())->method('addSort')->will($this->returnSelf());
     $this->repositoryMock = $this->getMockBuilder('ONGR\\ElasticsearchBundle\\ORM\\Repository')->disableOriginalConstructor()->setMethods(['createSearch', 'execute', 'createDocument'])->getMock();
     $this->repositoryMock->expects($this->any())->method('createSearch')->willReturn($searchMock);
     $this->repositoryMock->expects($this->any())->method('createDocument')->willReturn(new CurrencyDocument());
     $this->esManagerMock = $this->getMockBuilder('ONGR\\ElasticsearchBundle\\ORM\\Manager')->setMethods(['getRepository', 'persist', 'commit'])->disableOriginalConstructor()->getMock();
     $this->esManagerMock->expects($this->any())->method('getRepository')->willReturn($this->repositoryMock);
     $this->esManagerMock->expects($this->any())->method('createSearch')->willReturn($searchMock);
 }
 /**
  * Check command execute.
  */
 public function testExecute()
 {
     // Parameter was not set, so it has no value.
     $this->commandTester->execute(['command' => $this->command->getName(), 'parameter' => 'test1']);
     $this->assertContains('Parameter `test1`: has no value.', $this->commandTester->getDisplay());
     $this->assertContains('If you want to write new value, use --set="<new value>" option.', $this->commandTester->getDisplay());
     // Set some value, and test if it was set and returned.
     $value = '2014-01-01 01:01:01';
     $this->commandTester->execute(['command' => $this->command->getName(), 'parameter' => 'test1', '--set' => $value]);
     $this->assertContains('New value written:', $this->commandTester->getDisplay());
     /** @var Repository $repo */
     $repo = $this->manager->getRepository('ONGRConnectionsBundle:Pair');
     $parameter = $repo->find('test1');
     $this->assertEquals($value, $parameter->getValue());
 }
 /**
  * Removes a setting.
  *
  * @param Setting $setting
  */
 public function remove(Setting $setting)
 {
     $this->repo->remove($setting->getId());
     $this->manager->flush();
     $this->manager->refresh();
     $this->eventDispatcher->dispatch('ongr_settings.setting_change', new SettingChangeEvent('delete'));
 }
 /**
  * Returns array of links got by document id.
  *
  * @return array
  */
 protected function getUrlsByDocumentParameter()
 {
     if (count($this->documentParamCache) < 1) {
         return [];
     }
     $urls = [];
     $query = new Query();
     $queryTerms = [];
     foreach ($this->documentParamCache as $param) {
         $queryTerms[$param[0]][] = $param[1];
     }
     foreach ($queryTerms as $field => $values) {
         $termQuery = new TermQuery($field, $values);
         $query->addQuery($termQuery, 'should');
     }
     $limitFilter = new LimitFilter(count($this->documentParamCache));
     $repository = $this->manager->getRepository('MultiModel');
     $search = $repository->createSearch()->addQuery($query)->addFilter($limitFilter);
     $documents = $repository->execute($search);
     // Add all category urls to invalidate.
     foreach ($documents as $document) {
         if (is_array($document->url)) {
             foreach ($document->url as $url) {
                 $urls[] = $url['url'];
             }
         }
     }
     array_walk($urls, [$this, 'addWildcard']);
     $this->addUrls($urls);
     return $urls;
 }
 /**
  * Creates pair model.
  *
  * @param string $key
  * @param mixed  $value
  *
  * @return Pair
  */
 private function getPair($key, $value)
 {
     /** @var Repository $repository */
     $repository = $this->manager->getRepository('ONGRConnectionsBundle:Pair');
     /** @var Pair $pair */
     $pair = $repository->createDocument();
     $pair->__setInitialized(true);
     $pair->setId($key);
     $pair->setValue($value);
     $pair->setScore(1.0);
     return $pair;
 }
 /**
  * Gets settings.
  *
  * @return array
  *
  * @throws \LogicException
  */
 public function getSettings()
 {
     if ($this->manager === null) {
         throw new \LogicException('setManager must be called before getSettings.');
     }
     /** @var Repository $repo */
     $repo = $this->manager->getRepository('ONGRSettingsBundle:Setting');
     // Create query.
     $search = $repo->createSearch();
     $match = new MatchQuery('profile', $this->getProfile());
     $search->addQuery($match);
     $limit = new LimitFilter($this->getLimit());
     $search->addFilter($limit);
     // Process query.
     $settings = $repo->execute($search);
     $result = [];
     /** @var Setting $setting */
     foreach ($settings as $setting) {
         $result[$setting->getName()] = $setting->getData()['value'];
     }
     return $result;
 }
 /**
  * Test for get().
  *
  * @param string $key
  * @param string $value
  * @param bool   $exception
  *
  * @dataProvider getDataSetForSet
  */
 public function testGet($key, $value, $exception)
 {
     if ($exception) {
         $this->repositoryMock->expects($this->once())->method('find')->will($this->returnValue(null));
     } else {
         $pair = new Pair();
         $pair->setId($key);
         $pair->setValue($value);
         $this->repositoryMock->expects($this->once())->method('find')->willReturn($pair);
     }
     $this->ormManagerMock->expects($this->once())->method('getRepository')->willReturn($this->repositoryMock);
     $pairStorage = $this->getPairStorage($this->ormManagerMock);
     $this->assertEquals($exception ? null : $value, $pairStorage->get($key));
 }
 /**
  * Exports es index to provided file.
  *
  * @param Manager         $manager
  * @param string          $filename
  * @param int             $chunkSize
  * @param OutputInterface $output
  */
 public function exportIndex(Manager $manager, $filename, $chunkSize, OutputInterface $output)
 {
     $types = $manager->getTypesMapping();
     $repo = $manager->getRepository($types);
     $results = $this->getResults($repo, $chunkSize);
     if (class_exists('\\Symfony\\Component\\Console\\Helper\\ProgressBar')) {
         $progress = new ProgressBar($output, $results->getTotalCount());
         $progress->setRedrawFrequency(100);
         $progress->start();
     } else {
         $progress = new ProgressHelper();
         $progress->setRedrawFrequency(100);
         $progress->start($output, $results->getTotalCount());
     }
     $metadata = ['count' => $results->getTotalCount(), 'date' => date(\DateTime::ISO8601)];
     $writer = $this->getWriter($this->getFilePath($filename), $metadata);
     foreach ($results as $data) {
         $writer->push(array_intersect_key($data, array_flip(['_id', '_type', '_source'])));
         $progress->advance();
     }
     $writer->finalize();
     $progress->finish();
     $output->writeln('');
 }
 /**
  * Tests duplicate method.
  */
 public function testDuplicate()
 {
     $manager = new SettingsManager($this->container->get('translator'), $this->container->get('event_dispatcher'), $this->manager);
     $settingToCopy = $manager->get('name0', 'default');
     $settingToCopy->setScore(1.0);
     $settingToCopy->setName('SettingModel');
     $manager->duplicate($settingToCopy, 'newDomain');
     $repo = $this->manager->getRepository('ONGRSettingsBundle:Setting');
     $search = $repo->createSearch()->addQuery(new MatchAllQuery());
     $documents = $repo->execute($search);
     $expectedCreated = clone $settingToCopy;
     $expectedCreated->setId('newDomain_SettingModel');
     $expectedCreated->setProfile('newDomain');
     $settingToCopy->setName('name0');
     $actual = iterator_to_array($documents);
     $expected = [$settingToCopy, $expectedCreated];
     sort($actual);
     sort($expected);
     $this->assertEquals($expected, $actual);
 }
 /**
  * Check if ignored version skipping works as expected.
  *
  * @param string $version
  * @param array  $ignoredVersions
  * @param bool   $shouldSkip
  * @param string $expectedMessage
  *
  * @dataProvider getIgnoreVersionData()
  */
 public function testIgnoreVersion($version, $ignoredVersions, $shouldSkip, $expectedMessage = '')
 {
     $actualMessage = '';
     $skipped = false;
     $this->dummyBase = $this->getMockBuilder('ONGR\\ElasticsearchBundle\\Tests\\Unit\\Test\\ElasticsearchTestCaseDummy')->setMethods(['getIgnoredVersions', 'getContainer'])->disableOriginalConstructor()->getMock();
     $this->dummyBase->expects($this->any())->method('getContainer')->will($this->returnValue($this->containerMock));
     $this->dummyBase->expects($this->once())->method('getIgnoredVersions')->willReturn($ignoredVersions);
     $this->containerMock->expects($this->once())->method('has')->with('es.manager.default')->will($this->returnValue(true));
     $this->containerMock->expects($this->once())->method('get')->with('es.manager.default')->will($this->returnValue($this->managerMock));
     $this->managerMock->expects($this->once())->method('getConnection')->willReturn($this->connectionMock);
     $this->connectionMock->expects($shouldSkip ? $this->never() : $this->once())->method('dropAndCreateIndex');
     $this->connectionMock->expects($this->once())->method('getVersionNumber')->willReturn($version);
     $reflection = new \ReflectionMethod($this->dummyBase, 'setUp');
     $reflection->setAccessible(true);
     try {
         $reflection->invokeArgs($this->dummyBase, []);
     } catch (\PHPUnit_Framework_SkippedTestError $ex) {
         $actualMessage = $ex->getMessage();
         $skipped = true;
     }
     $this->assertEquals($shouldSkip, $skipped);
     $this->assertEquals($actualMessage, $expectedMessage);
 }
 /**
  * Reloads rates using given driver.
  *
  * @return array
  */
 public function reloadRates()
 {
     $esRates = [];
     $this->rates = $this->driver->getRates();
     $repository = $this->manager->getRepository('ONGRCurrencyExchangeBundle:CurrencyDocument');
     /** @var CurrencyDocument $document */
     $document = $repository->createDocument();
     $document->setCreatedAt(new \DateTime());
     if ($this->rates) {
         foreach ($this->rates as $name => $value) {
             $ratesObject = new RatesObject();
             $ratesObject->setName($name);
             $ratesObject->setValue($value);
             $esRates[] = $ratesObject;
         }
         $document->rates = $esRates;
         $this->manager->persist($document);
         $this->manager->commit();
         $this->updateRatesCache($this->rates);
         return $this->rates;
     }
     $this->logger && $this->logger->notice('Failed to retrieve currency rates from provider.');
     return null;
 }
 /**
  * Constructor.
  *
  * @param Manager $manager
  * @param string  $repositoryName
  */
 public function __construct(Manager $manager, $repositoryName)
 {
     $this->repository = $manager->getRepository($repositoryName);
 }
 /**
  * Setup mock for test.
  */
 public function setUp()
 {
     $this->manager = $this->getMockBuilder('ONGR\\ElasticsearchBundle\\ORM\\Manager')->disableOriginalConstructor()->setMethods(['getRepository'])->getMock();
     $this->manager->expects($this->any())->method('getRepository')->willReturnSelf();
 }
 /**
  * Persist document to Elasticsearch.
  *
  * @return bool
  */
 protected function persistDocument()
 {
     $this->manager->persist($this->importItem->getDocument());
     return true;
 }
 /**
  * Check if an exception is thrown when an undefined repository is specified and only a single rep is specified.
  *
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage Undefined repository `rep1`, valid repositories are: `rep2`, `rep3`.
  */
 public function testGetRepositoriesExceptionSingle()
 {
     $manager = new Manager(null, $this->getClassMetadataCollectionMock(['rep2' => '', 'rep3' => '']), $this->getMock('Symfony\\Components\\EventDispatcher\\EventDispatcher'));
     $manager->getRepository('rep1');
 }
 /**
  * Finish and commit.
  */
 public function onFinish()
 {
     $this->manager->commit();
 }
Beispiel #18
0
 /**
  * Saves pair object.
  *
  * @param Pair $pair
  */
 private function save(Pair $pair)
 {
     $this->manager->persist($pair);
     $this->manager->commit();
     $this->manager->refresh();
 }
 /**
  * Populates elasticsearch with data.
  *
  * @param Manager $manager
  * @param array   $data
  */
 protected function populateElasticsearchWithData($manager, array $data)
 {
     if (!empty($data)) {
         foreach ($data as $type => $documents) {
             foreach ($documents as $document) {
                 $manager->getConnection()->bulk('index', $type, $document);
             }
         }
         $manager->commit();
     }
 }