diff --git a/Command/ClearCommand.php b/Command/ClearCommand.php new file mode 100644 index 00000000..56c369f6 --- /dev/null +++ b/Command/ClearCommand.php @@ -0,0 +1,70 @@ +setName('algolia:clean') + ->setDescription('Clear the index related to an entity') + ->addArgument('entityName', InputArgument::OPTIONAL, 'Which entity index do you want to clear? If not set, all is assumed.') + ; + } + + protected function getEntityManager() + { + return $this + ->getContainer() + ->get('doctrine.orm.entity_manager'); + } + + protected function getEntityClasses() + { + $metaData = $this->getEntityManager() + ->getMetadataFactory() + ->getAllMetaData(); + + return array_map(function ($data) { + return $data->getName(); + }, $metaData); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $toReindex = []; + + if ($input->hasArgument('entityName')) { + $filter = $this->getEntityManager()->getRepository($input->getArgument('entityName'))->getClassName(); + } else { + $filter = null; + } + + foreach ($this->getEntityClasses() as $class) { + if (!$filter || $class === $filter) { + $toReindex[] = $class; + } + } + + $nIndexed = 0; + foreach ($toReindex as $className) { + $nIndexed += $this->clear($className); + } + + return $nIndexed; + } + + public function clear($className) + { + $reIndexer = $this->getContainer()->get('algolia.indexer')->getManualIndexer($this->getEntityManager()); + + return $reIndexer->clear($className); + } +} diff --git a/Indexer/ManualIndexer.php b/Indexer/ManualIndexer.php index dc6342e9..c9bcdf40 100644 --- a/Indexer/ManualIndexer.php +++ b/Indexer/ManualIndexer.php @@ -181,6 +181,17 @@ public function unIndex($entities, array $options = array()) } } + public function clear($entityName) + { + $className = $this->entityManager->getRepository($entityName)->getClassName(); + + $this->indexer->discoverEntity($className, $this->entityManager); + + $targetIndexName = $this->indexer->getAlgoliaIndexName($className); + + $this->indexer->getIndex($targetIndexName)->clearIndex(); + } + /** * Re-index entities from a collection. *