ClosureTreeRepository.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Gedmo\Tree\Entity\Repository;
  3. use Gedmo\Tree\AbstractTreeRepository,
  4. Doctrine\ORM\Query,
  5. Gedmo\Tree\Strategy,
  6. Gedmo\Tree\Strategy\ORM\Closure,
  7. Doctrine\ORM\Proxy\Proxy;
  8. /**
  9. * The ClosureTreeRepository has some useful functions
  10. * to interact with Closure tree. Repository uses
  11. * the strategy used by listener
  12. *
  13. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @package Gedmo.Tree.Entity.Repository
  16. * @subpackage ClosureRepository
  17. * @link http://www.gediminasm.org
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. class ClosureTreeRepository extends AbstractTreeRepository
  21. {
  22. /**
  23. * Counts the children of given TreeNode
  24. *
  25. * @param object $node - if null counts all records in tree
  26. * @param boolean $direct - true to count only direct children
  27. * @return integer
  28. */
  29. public function childCount( $node = null, $direct = false )
  30. {
  31. $meta = $this->getClassMetadata();
  32. $qb = $this->_em->createQueryBuilder();
  33. $config = $this->listener->getConfiguration( $this->_em, $meta->name );
  34. $closureMeta = $this->_em->getClassMetadata( $config[ 'closure' ] );
  35. $table = $closureMeta->getTableName();
  36. $nodeID = $meta->getSingleIdentifierFieldName();
  37. $id = $meta->getReflectionProperty( $nodeID )->getValue( $node );
  38. $qb->select( 'COUNT( c.id )' )
  39. ->from( $table, 'c' )
  40. ->where( 'c.ancestor = :node_id' );
  41. if ( $direct === true )
  42. {
  43. $qb->andWhere( 'c.depth = 1' );
  44. }
  45. $qb->setParameter( 'node_id', $id );
  46. return $qb->getQuery()->getSingleScalarResult();
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function validates()
  52. {
  53. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::CLOSURE;
  54. }
  55. }