partkeepr

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

commit 0d9fe21c5ce25fc72bcf9639c4517b04b7f3e156
parent 93d50f1211e9169f1dfe5291ecd51bee3dce5e55
Author: Felicitus <felicitus@felicitus.org>
Date:   Wed,  7 Oct 2015 17:21:01 +0200

Added category service

Diffstat:
Asrc/PartKeepr/CategoryBundle/Services/CategoryService.php | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+), 0 deletions(-)

diff --git a/src/PartKeepr/CategoryBundle/Services/CategoryService.php b/src/PartKeepr/CategoryBundle/Services/CategoryService.php @@ -0,0 +1,68 @@ +<?php +namespace PartKeepr\CategoryBundle\Services; + + +use Doctrine\ORM\EntityManager; +use Gedmo\Tree\Entity\Repository\AbstractTreeRepository; +use PartKeepr\CategoryBundle\Entity\AbstractCategory; +use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException; + +class CategoryService +{ + /** + * @var AbstractTreeRepository + */ + private $entityRepository; + + /** + * @var EntityManager + */ + private $entityManager; + + private $entityClass; + + public function __construct(EntityManager $entityManager, $entityClass) + { + $this->entityRepository = $entityManager->getRepository($entityClass); + $this->entityManager = $entityManager; + $this->entityClass = $entityClass; + } + + /** + * Returns the root node for a tree + * + * @return AbstractCategory + * @throws RootNodeNotFoundException + */ + public function getRootNode() + { + $rootNodes = $this->entityRepository->getRootNodes(); + + if (count($rootNodes) == 0) { + throw new RootNodeNotFoundException(); + } + + $rootNode = reset($rootNodes); + + return $rootNode; + } + + /** + * Creates the root node for a tree if it doesn't exist + */ + public function ensureRootNodeExists() + { + try { + $this->getRootNode(); + } catch (RootNodeNotFoundException $e) { + /** + * @var AbstractCategory $rootNode + */ + $rootNode = new $this->entityClass; + $rootNode->setName("Root Category"); + + $this->entityManager->persist($rootNode); + $this->entityManager->flush(); + } + } +}