CategoryPathListener.php (2275B)
1 <?php 2 3 namespace PartKeepr\StorageLocationBundle\Listeners; 4 5 use Doctrine\ORM\EntityManager; 6 use Doctrine\ORM\Event\OnFlushEventArgs; 7 use PartKeepr\StorageLocationBundle\Entity\StorageLocationCategory; 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 StorageLocationCategory) { 30 $this->updateCategoryPaths($updated, $eventArgs); 31 } 32 } 33 34 foreach ($uow->getScheduledEntityUpdates() as $updated) { 35 if ($updated instanceof StorageLocationCategory) { 36 $this->updateCategoryPaths($updated, $eventArgs); 37 } 38 } 39 } 40 41 /** 42 * Recursively updates the category paths. 43 * 44 * @param StorageLocationCategory $storageLocationCategory The storage location category to update 45 * @param EntityManager $entityManager The entity manager 46 */ 47 public function updateCategoryPaths(StorageLocationCategory $storageLocationCategory, OnFlushEventArgs $eventArgs) 48 { 49 $entityManager = $eventArgs->getEntityManager(); 50 $pathSeparator = $this->container->getParameter('partkeepr.category.path_separator'); 51 52 $storageLocationCategory->setCategoryPath($storageLocationCategory->generateCategoryPath($pathSeparator)); 53 54 $entityManager->getUnitOfWork()->recomputeSingleEntityChangeSet( 55 $entityManager->getClassMetadata(get_class($storageLocationCategory)), 56 $storageLocationCategory 57 ); 58 59 foreach ($storageLocationCategory->getChildren() as $child) { 60 $this->updateCategoryPaths($child, $eventArgs); 61 } 62 } 63 }