improve dynamic docs. create and lad class dynamically
authorymh <ymh.work@gmail.com>
Fri, 04 Nov 2011 11:56:59 +0100
changeset 23 b435f8055cb4
parent 22 99c15cfe420b
child 24 cd389bf882f1
improve dynamic docs. create and lad class dynamically
Command/CreateFullTextIndexesCommand.php
Command/GenerateDocumentClassCommand.php
Command/SyncDocumentsCommand.php
DependencyInjection/Configuration.php
DependencyInjection/WikiTagExtension.php
Entity/DocumentRepository.php
Listener/DocumentListener.php
Model/Document.php
Model/DocumentInterface.php
Resources/config/doctrine/Document.orm.yml
Resources/config/doctrine/DocumentTag.orm.yml
Resources/config/services.yml
--- a/Command/CreateFullTextIndexesCommand.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Command/CreateFullTextIndexesCommand.php	Fri Nov 04 11:56:59 2011 +0100
@@ -43,37 +43,10 @@
             $simulate = true;
         }
         
-        $sql_code = "";
-        $fields = $this->getContainer()->getParameter('wiki_tag.fields');
-        $def_columns = array();
-        foreach ( $fields as $name => $field_def)
-        {
-            if(isset($field_def['type']))
-            {
-                $type = $field_def['type'];
-            }
-            if(!isset($type) || is_null($type) || strlen($type) == 0)
-            {
-                $type = "text";
-            }
-            
-            if($type === 'text')
-            {
-                $def_column = "$name(4096)";
-            }
-            else
-            {
-                $def_column = $name;
-            }
-            $def_columns[] = $def_column;
-            
-            $sql_code .= "ALTER IGNORE TABLE wikitag_document DROP INDEX ${name}_document_fulltext_idx;\n";
-            $sql_code .= "ALTER TABLE wikitag_document ADD FULLTEXT INDEX ${name}_document_fulltext_idx ($def_column);\n";
-        }
+
+        $schema_utils = $this->getContainer()->get("wikitag.shema_utils");
         
-        $sql_code .= "ALTER IGNORE TABLE wikitag_document DROP INDEX all_document_fulltext_idx;\n";
-        $sql_code .= "ALTER TABLE wikitag_document ADD FULLTEXT INDEX all_document_fulltext_idx (".join(",", $def_columns).");\n";
-        
+        $sql_code = implode(";".PHP_EOL, $schema_utils->createFullTextIndexes());
         
         if($simulate)
         {
--- a/Command/GenerateDocumentClassCommand.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Command/GenerateDocumentClassCommand.php	Fri Nov 04 11:56:59 2011 +0100
@@ -16,10 +16,6 @@
 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Input\InputOption;
 use Symfony\Component\Console\Output\OutputInterface;
-use Mandango\Mondator\Definition\Definition;
-use Mandango\Mondator\Definition\Property;
-use Mandango\Mondator\Definition\Method;
-use Mandango\Mondator\Dumper;
 
 class GenerateDocumentClassCommand extends ContainerAwareCommand
 {
@@ -42,32 +38,9 @@
             $path = realpath($this->getContainer()->get('kernel')->getRootDir()."/../src");
         }
         
-        $definition = new Definition('IRI\Bundle\WikiTagBundle\Entity\Document');
-        
-        $definition->setParentClass('\IRI\Bundle\WikiTagBundle\Model\Document');
+        $schema_utils = $this->getContainer()->get("wikitag.shema_utils");
         
-        $fields = $this->getContainer()->getParameter('wiki_tag.fields');
-        foreach ( $fields as $name => $field_def)
-        {
-            $property = new Property("private", $name, NULL);
-            $definition->addProperty($property);
-            
-            $get_method = new Method("public", "get".ucfirst($name), NULL, <<<EOF
-                return \$this->$name;
-EOF
-            );
-            $definition->addMethod($get_method);
-            
-            $set_method = new Method("public", "set".ucfirst($name), "\$$name", <<<EOF
-                \$this->$name = \$$name;
-EOF
-            );
-            $definition->addMethod($set_method);
-            
-        }
-                
-        $dumper = new Dumper($definition);
-        $classCode = $dumper->dump();
+        $classCode = $schema_utils->generateDocumentClass();
         
         if($input->getOption('simulate'))
         {
--- a/Command/SyncDocumentsCommand.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Command/SyncDocumentsCommand.php	Fri Nov 04 11:56:59 2011 +0100
@@ -27,13 +27,12 @@
         $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');
+        $class = $this->getContainer()->getParameter('wiki_tag.document_class');
         $clear = $input->getOption('clear');
      
         
@@ -52,25 +51,14 @@
         //TODO : write progress
         $doclist = $rep->findAll();
         foreach ($doclist as $doc) {
-            $output->writeln("TITLE : ".$doc->getTitle());
-            $docrep->writeDocument($doc);
+            $docrep->writeDocument($doc, $this->getContainer()->getParameter('wiki_tag.document_id_column'), $this->getContainer()->getParameter('wiki_tag.fields'));
         }
         $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);
-            }
+            $req = $doctrine->getEntityManager()->createQuery("DELETE WikiTagBundle:Document wtdoc WHERE wtdoc.externalId NOT IN (SELECT doc FROM $class doc)");
+            $req->getResult();
             $doctrine->getEntityManager()->flush();
         }
 
--- a/DependencyInjection/Configuration.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/DependencyInjection/Configuration.php	Fri Nov 04 11:56:59 2011 +0100
@@ -41,6 +41,12 @@
                                     ->then(function($v) { return intval($v); })
                                 ->end()
                             ->end()
+                            ->scalarNode('weight')->defaultValue(1.0)
+                                ->beforeNormalization()
+                                    ->ifString()
+                                    ->then(function($v) { return floatval($v); })
+                                ->end()
+                            ->end()
                             ->scalarNode('accessor')->end()
                         ->end()
                     ->end()
--- a/DependencyInjection/WikiTagExtension.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/DependencyInjection/WikiTagExtension.php	Fri Nov 04 11:56:59 2011 +0100
@@ -40,7 +40,10 @@
         }
         $container->setParameter("wiki_tag.document_id_column", $document_id);
         
-        $container->setParameter("wiki_tag.fields", $config['fields']);
+        $fields = $config['fields'];
+        $container->setParameter("wiki_tag.fields", $fields);
+        $fields['tagsStr'] = array("type"=>"text");
+        $container->setParameter("wiki_tag.fields_all", $fields);
         $container->setParameter("wiki_tag.route_for_documents_by_tag", $config['route_for_documents_by_tag']);
     }
 }
--- a/Entity/DocumentRepository.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Entity/DocumentRepository.php	Fri Nov 04 11:56:59 2011 +0100
@@ -136,14 +136,15 @@
     
     function writeDocument($document,  $document_id_column, $fields)
     {
-        # get document from id
+        // get document from id
+         
         $docid = $this->reflectionGetField($document, $document_id_column);
         $baseDocument = $this->findOneByExternalId($docid);
     
         if(is_null($baseDocument))
         {
             $baseDocument = new Document();
-            $baseDocument->setExternalId($docid);
+            $baseDocument->setExternalId($document);
         }
         
         foreach ($fields as $name => $field_def) {
@@ -184,4 +185,17 @@
         }
     }
     
+    function updateTagsStr($document)
+    {
+        $tags_str = array();
+        foreach($document->getTags() as $tag)
+        {
+            $tags_str[] = $tag->getTag()->getLabel();
+        }
+        
+        $document->setTagsStr(implode(",",$tags_str));
+        
+        $this->getEntityManager()->flush();
+    }
+        
 }
\ No newline at end of file
--- a/Listener/DocumentListener.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Listener/DocumentListener.php	Fri Nov 04 11:56:59 2011 +0100
@@ -10,16 +10,12 @@
 
 namespace IRI\Bundle\WikiTagBundle\Listener;
 
-use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs;
-
 use Doctrine\ORM\Tools\ToolEvents;
 
 use Doctrine\Common\EventSubscriber;
 use Doctrine\ORM\Events;
 use Doctrine\ORM\Event\LifecycleEventArgs;
-use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
 use Doctrine\ORM\Event\PreUpdateEventArgs;
-use IRI\Bundle\WikiTagBundle\Model\DocumentInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 
 
@@ -58,8 +54,7 @@
         Events::postPersist,
         Events::postUpdate,
         Events::preRemove,
-        Events::loadClassMetadata,
-        ToolEvents::postGenerateSchemaTable,
+        Events::postRemove,
         );
     }
     
@@ -86,7 +81,17 @@
         $class = $this->getContainer()->getParameter("wiki_tag.document_class");
         if (is_a($entity, $class))
         {
-            $this->container->get('doctrine')->getRepository("WikiTagBundle:Document")->removeDocument($entity);
+            $this->container->get('doctrine')->getRepository("WikiTagBundle:Document")->removeDocument($entity, $this->getContainer()->getParameter("wiki_tag.document_id_column"));
+        }
+    }
+    
+    public function postRemove(LifecycleEventArgs $args)
+    {
+        $entity = $args->getEntity();
+        if (is_a($entity, "IRI\Bundle\WikiTagBundle\Model\DocumentTagInterface"))
+        {
+            $doc = $entity->getDocument();
+            $this->getContainer()->get('doctrine')->getRepository("WikiTagBundle:Document")->updateTagsStr($doc);
         }
     }
     
@@ -103,87 +108,19 @@
             $logger->debug("treating document : " . $entity->getTitle());
             $this->container->get('doctrine')->getRepository("WikiTagBundle:Document")->writeDocument($entity, $this->getContainer()->getParameter("wiki_tag.document_id_column"), $this->getContainer()->getParameter("wiki_tag.fields"));
         }
+        elseif (is_a($entity, "IRI\Bundle\WikiTagBundle\Model\DocumentTagInterface"))
+        {
+            $doc = $entity->getDocument();
+            $this->getContainer()->get('doctrine')->getRepository("WikiTagBundle:Document")->updateTagsStr($doc);
+        }
+        elseif (is_a($entity, "IRI\Bundle\WikiTagBundle\Model\TagInterface"))
+        {
+            foreach($entity->getDocuments() as $doctag)
+            {
+                $this->getContainer()->get('doctrine')->getRepository("WikiTagBundle:Document")->updateTagsStr($doctag->getDocument());
+            }
+        }
         
     }
     
-    /**
-     *
-     * Enter description here ...
-     * @param LoadClassMetadataEventArgs $args
-     */
-    public function loadClassMetadata(LoadClassMetadataEventArgs $args)
-    {
-        
-        $document_class = $this->container->getParameter('wiki_tag.document_class');
-        $metadata = $args->getClassMetadata();
-        if($metadata->name === "IRI\\Bundle\\WikiTagBundle\\Entity\\Document")
-        {
-            $logger = $this->container->get('logger');
-            $logger->debug("DocumentListener: Add ExternalId Mapping");
-            $document_id_column = $this->container->getParameter('wiki_tag.document_id_column');
-            $logger->debug("DocumentListener: external id def : " . print_r($document_id_column, true));
-            $target_metadata = $args->getEntityManager()->getClassMetadata($document_class);
-            $mapping = array_replace(array(), $target_metadata->getFieldMapping($document_id_column));
-            $mapping['fieldName'] = 'externalId';
-            $mapping['columnName'] = 'external_id';
-            $mapping['id'] = false;
-            $metadata->mapField($mapping);
-/*            $metadata->mapOneToOne(array(
-                'targetEntity' => $document_class,
-                'fieldName' => 'externalId',
-                'joinColumns' => array(0=>array(
-                    'name' => 'external_id',
-                    'referencedColumnName' => $document_id_column
-                )),
-            ));*/
-            
-            //map the fields
-            $fields = $this->container->getParameter('wiki_tag.fields');
-            $def_columns = array();
-            foreach ( $fields as $name => $field_def)
-            {
-                if(isset($field_def['type']))
-                {
-                    $type = $field_def['type'];
-                }
-                if(!isset($type) || is_null($type) || strlen($type) == 0)
-                {
-                    $type = "text";
-                }
-                $mapping = array('fieldName' => $name, 'type' => $type);
-                if($type == 'string')
-                {
-                    if(isset($field_def['length']))
-                    {
-                        $length = $field_def['length'];
-                    }
-                    if(!isset($length))
-                    {
-                        $length = 1024;
-                    }
-                    elseif (!is_int($length))
-                    {
-                        $length = intval($length);
-                    }
-                    $mapping['length'] = $length;
-                }
-                $metadata->mapField($mapping);
-                                
-            }
-        }
-    }
-    
-    
-    public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $args)
-    {
-        $logger = $this->container->get('logger');
-        $logger->debug("Generate schema table ".$args->getClassTable()->getName());
-        
-        #if($args->getClassMetadata()->name === "IRI\\Bundle\\WikiTagBundle\\Entity\\Document")
-        #{
-        #    $args->getClassTable()->addOption('engine','MyISAM');
-        #}
-    }
-    
-    
 }
\ No newline at end of file
--- a/Model/Document.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Model/Document.php	Fri Nov 04 11:56:59 2011 +0100
@@ -35,6 +35,11 @@
      */
     protected $tags;
     
+    /**
+     * @var string tagsStr
+     */
+    protected $tagsStr;
+    
     
     /**
      * Get id
@@ -78,7 +83,7 @@
     
     /**
      * TODO: (non-PHPdoc)
-     * @see IRI\Bundle\WikiTagBundle\Model.BaseDocumentInterface::getExternalId()
+     * @see IRI\Bundle\WikiTagBundle\Model.DocumentInterface::getExternalId()
      */
     function getExternalId()
     {
@@ -87,11 +92,30 @@
     
     /**
      * TODO: (non-PHPdoc)
-     * @see IRI\Bundle\WikiTagBundle\Model.BaseDocumentInterface::getTags()
+     * @see IRI\Bundle\WikiTagBundle\Model.DocumentInterface::getTags()
      */
     function getTags()
     {
         return $this->tags;
     }
     
+    /**
+     * TODO: (non-PHPdoc)
+     * @see IRI\Bundle\WikiTagBundle\Model.DocumentInterface::setTagsStr()
+     */
+    function setTagsStr($tagsStr)
+    {
+        $this->tagsStr = $tagsStr;
+    }
+
+    /**
+    * TODO: (non-PHPdoc)
+    * @see IRI\Bundle\WikiTagBundle\Model.DocumentInterface::getTagsStr()
+    */
+    function getTagsStr()
+    {
+        return $this->tagsStr;
+    }
+    
+
 }
--- a/Model/DocumentInterface.php	Fri Oct 28 14:57:11 2011 +0200
+++ b/Model/DocumentInterface.php	Fri Nov 04 11:56:59 2011 +0100
@@ -50,6 +50,18 @@
      */
     function getManualOrder();
     
-    
+    /**
+     * Get tagsStr
+     *
+     * @return string
+     */
+    function getTagsStr();
     
+    /**
+     * Set tagsStr
+     *
+     * @param $tagsStr
+     */
+    function setTagsStr($tagsStr);
+        
 }
--- a/Resources/config/doctrine/Document.orm.yml	Fri Oct 28 14:57:11 2011 +0200
+++ b/Resources/config/doctrine/Document.orm.yml	Fri Nov 04 11:56:59 2011 +0100
@@ -3,7 +3,7 @@
   repositoryClass: IRI\Bundle\WikiTagBundle\Entity\DocumentRepository
   table: wikitag_document
   options:
-    engine: MyISAM
+    type: MyISAM
   fields:
     id:
       type: integer
@@ -13,8 +13,17 @@
     manualOrder:
       type: boolean
       column: manual_order
+    tagsStr:
+        type: text
+        column: tags_str
+        nullable: true
   oneToMany:
     tags:
       targetEntity: DocumentTag
       mappedBy: document
+      cascade: [ "remove" ]
+  indexes:
+    tags_str_document_fulltext_idx:
+        columns: ["tags_str"]
+            
   lifecycleCallbacks: {  }
--- a/Resources/config/doctrine/DocumentTag.orm.yml	Fri Oct 28 14:57:11 2011 +0200
+++ b/Resources/config/doctrine/DocumentTag.orm.yml	Fri Nov 04 11:56:59 2011 +0100
@@ -28,7 +28,7 @@
         name: tag_id
         referencedColumnName: id
         nullable: false
-        onDelete: CASCADE
+        onDelete: cascade
     document:
       targetEntity: Document
       inversedBy: tags
@@ -36,5 +36,4 @@
         name: document_id
         referencedColumnName: id
         nullable: false
-        onDelete: CASCADE
   lifecycleCallbacks: {  }
--- a/Resources/config/services.yml	Fri Oct 28 14:57:11 2011 +0200
+++ b/Resources/config/services.yml	Fri Nov 04 11:56:59 2011 +0100
@@ -1,14 +1,28 @@
 parameters:
 #    wiki_tag.example.class: IRI\Bundle\WikiTagBundle\Example
     wiki_tag.document_listener.class: IRI\Bundle\WikiTagBundle\Listener\DocumentListener
+    wiki_tag.wiki_tag_document_listener.class: IRI\Bundle\WikiTagBundle\Listener\WikiTagDocumentListener
+    wiki_tag.shema_utils.class: IRI\Bundle\WikiTagBundle\Utils\SchemaUtils
+
 
 services:
+
     wiki_tag.document_listener:
         class: %wiki_tag.document_listener.class%
         arguments: [@service_container]
         tags:
             - { name: doctrine.event_subscriber, connection: default }
 
+    wiki_tag.wiki_tag_document_listener:
+        class: %wiki_tag.wiki_tag_document_listener.class%
+        arguments: [@service_container]
+        tags:
+            - { name: doctrine.event_subscriber, connection: default }
+
+    wiki_tag.shema_utils:
+        class: %wiki_tag.shema_utils.class%
+        arguments: [@service_container]
+
 #    wiki_tag.example:
 #        class: %wiki_tag.example.class%
 #        arguments: [@service_id, "plain_value", %parameter%]