partkeepr

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

CategoryService.php (1738B)


      1 <?php
      2 
      3 namespace PartKeepr\CategoryBundle\Services;
      4 
      5 use Doctrine\ORM\EntityManager;
      6 use Gedmo\Tree\Entity\Repository\AbstractTreeRepository;
      7 use PartKeepr\CategoryBundle\Entity\AbstractCategory;
      8 use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException;
      9 
     10 class CategoryService
     11 {
     12     /**
     13      * @var AbstractTreeRepository
     14      */
     15     private $entityRepository;
     16 
     17     /**
     18      * @var EntityManager
     19      */
     20     private $entityManager;
     21 
     22     private $entityClass;
     23 
     24     public function __construct(EntityManager $entityManager, $entityClass)
     25     {
     26         $this->entityRepository = $entityManager->getRepository($entityClass);
     27         $this->entityManager = $entityManager;
     28         $this->entityClass = $entityClass;
     29     }
     30 
     31     /**
     32      * Returns the root node for a tree.
     33      *
     34      * @throws RootNodeNotFoundException
     35      *
     36      * @return AbstractCategory
     37      */
     38     public function getRootNode()
     39     {
     40         $rootNodes = $this->entityRepository->getRootNodes();
     41 
     42         if (count($rootNodes) == 0) {
     43             throw new RootNodeNotFoundException();
     44         }
     45 
     46         $rootNode = reset($rootNodes);
     47 
     48         return $rootNode;
     49     }
     50 
     51     public function getEntityClass()
     52     {
     53         return $this->entityClass;
     54     }
     55 
     56     /**
     57      * Creates the root node for a tree if it doesn't exist.
     58      */
     59     public function ensureRootNodeExists()
     60     {
     61         try {
     62             $this->getRootNode();
     63         } catch (RootNodeNotFoundException $e) {
     64             /**
     65              * @var AbstractCategory
     66              */
     67             $rootNode = new $this->entityClass();
     68             $rootNode->setName('Root Category');
     69 
     70             $this->entityManager->persist($rootNode);
     71             $this->entityManager->flush();
     72         }
     73     }
     74 }