Command/SyncDocumentsCommand.php
author ymh <ymh.work@gmail.com>
Wed, 19 Oct 2011 14:33:40 +0200
changeset 6 2dcfef6e75c3
child 23 b435f8055cb4
permissions -rw-r--r--
add command to sync documents

<?php
/*
 * This file is part of the WikiTagBundle package.
 *
 * (c) IRI <http://www.iri.centrepompidou.fr/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace IRI\Bundle\WikiTagBundle\Command;

use Doctrine\ORM\Query;

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 SyncDocumentsCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        parent::configure();
        
        $this
            ->setName('wikitag:sync-doc')
            ->setDescription('Synchronize and index document class')
            ->addArgument('class', InputArgument::REQUIRED, 'The document class')
            ->addOption('clear', 'c', InputOption::VALUE_NONE, "clear all docs");
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $class = $input->getArgument('class');
        $clear = $input->getOption('clear');
     
        
        $doctrine = $this->getContainer()->get('doctrine');
        
        $docrep = $doctrine->getRepository('WikiTagBundle:Document');
        $rep = $doctrine->getRepository($class);
        
        if(is_null($rep)) {
            //TODO : translate
            $output->writeln("$class does not have a repository : exiting.");
            return ;
        }
        
        //TODO : check class to implement DocumentInterface
        //TODO : write progress
        $doclist = $rep->findAll();
        foreach ($doclist as $doc) {
            $output->writeln("TITLE : ".$doc->getTitle());
            $docrep->writeDocument($doc);
        }
        $doctrine->getEntityManager()->flush();
        
        if($clear) {
            
            $req_ids = $doctrine->getEntityManager()->createQuery("SELECT partial doc.{id} FROM $class doc");
            $doc_ids = array();
            foreach($req_ids->getResult(Query::HYDRATE_SCALAR) as $doc_id) {
                $doc_ids[] = strval($doc_id['doc_id']);
            }
            
            $req = $doctrine->getEntityManager()->createQuery("SELECT wtdoc FROM WikiTagBundle:Document wtdoc WHERE wtdoc.externalId NOT IN (:doc_ids)");
            $req->setParameter('doc_ids', $doc_ids);
            foreach ($req->getResult() as $wtdoc) {
                $output->writeln("DELETE : ".$wtdoc->getId());
                $doctrine->getEntityManager()->remove($wtdoc);
            }
            $doctrine->getEntityManager()->flush();
        }

        $output->writeln(strval(count($doclist)) ." documents imported.");
    }
}