Skip to content

Commit

Permalink
Add a clear command. Fixes #5
Browse files Browse the repository at this point in the history
  • Loading branch information
maxiloc committed Jul 23, 2015
1 parent 520a2ff commit d9dd50e
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
70 changes: 70 additions & 0 deletions Command/ClearCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace Algolia\AlgoliaSearchBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ClearCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->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);
}
}
11 changes: 11 additions & 0 deletions Indexer/ManualIndexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down

0 comments on commit d9dd50e

Please sign in to comment.