partkeepr

fork of partkeepr
git clone https://git.e1e0.net/partkeepr.git
Log | Files | Refs | Submodules | README | LICENSE

CategoryPathListener.php (2172B)


      1 <?php
      2 
      3 namespace PartKeepr\FootprintBundle\Listeners;
      4 
      5 use Doctrine\ORM\EntityManager;
      6 use Doctrine\ORM\Event\OnFlushEventArgs;
      7 use PartKeepr\FootprintBundle\Entity\FootprintCategory;
      8 use Symfony\Component\DependencyInjection\Container;
      9 use Symfony\Component\DependencyInjection\ContainerAware;
     10 
     11 class CategoryPathListener extends ContainerAware
     12 {
     13     public function __construct(Container $container)
     14     {
     15         $this->setContainer($container);
     16     }
     17 
     18     /**
     19      * Updates the child category paths when their parent name has changed.
     20      *
     21      * @param OnFlushEventArgs $eventArgs The event arguments as given by Doctrine
     22      */
     23     public function onFlush(OnFlushEventArgs $eventArgs)
     24     {
     25         $entityManager = $eventArgs->getEntityManager();
     26         $uow = $entityManager->getUnitOfWork();
     27 
     28         foreach ($uow->getScheduledEntityInsertions() as $updated) {
     29             if ($updated instanceof FootprintCategory) {
     30                 $this->updateCategoryPaths($updated, $eventArgs);
     31             }
     32         }
     33 
     34         foreach ($uow->getScheduledEntityUpdates() as $updated) {
     35             if ($updated instanceof FootprintCategory) {
     36                 $this->updateCategoryPaths($updated, $eventArgs);
     37             }
     38         }
     39     }
     40 
     41     /**
     42      * Recursively updates the category paths.
     43      *
     44      * @param FootprintCategory $footprintCategory The footprint category to update
     45      * @param EntityManager     $entityManager     The entity manager
     46      */
     47     public function updateCategoryPaths(FootprintCategory $footprintCategory, OnFlushEventArgs $eventArgs)
     48     {
     49         $entityManager = $eventArgs->getEntityManager();
     50         $pathSeparator = $this->container->getParameter('partkeepr.category.path_separator');
     51 
     52         $footprintCategory->setCategoryPath($footprintCategory->generateCategoryPath($pathSeparator));
     53 
     54         $entityManager->getUnitOfWork()->recomputeSingleEntityChangeSet(
     55             $entityManager->getClassMetadata(get_class($footprintCategory)),
     56             $footprintCategory
     57         );
     58 
     59         foreach ($footprintCategory->getChildren() as $child) {
     60             $this->updateCategoryPaths($child, $eventArgs);
     61         }
     62     }
     63 }