ClosureTreeRepository.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 - The node from which we'll count its children
  26. * @param boolean $direct - true to count only direct children
  27. * @return integer
  28. */
  29. public function childCount( $node, $direct = false )
  30. {
  31. $meta = $this->getClassMetadata();
  32. $id = $this->getIdFromEntity( $node );
  33. $qb = $this->getQueryBuilder();
  34. $qb->select( 'COUNT( c.id )' )
  35. ->from( $meta->rootEntityName, 'c' )
  36. ->where( 'c.ancestor = :node_id' )
  37. ->andWhere( 'c.ancestor != c.descendant' );
  38. if ( $direct === true )
  39. {
  40. $qb->andWhere( 'c.depth = 1' );
  41. }
  42. $qb->setParameter( 'node_id', $id );
  43. return $qb->getQuery()->getSingleScalarResult();
  44. }
  45. protected function getQueryBuilder()
  46. {
  47. $qb = $this->_em->createQueryBuilder();
  48. return $qb;
  49. }
  50. protected function getIdFromEntity( $node )
  51. {
  52. $meta = $this->_em->getClassMetadata( get_class( $node ) );
  53. $nodeID = $meta->getSingleIdentifierFieldName();
  54. $refProp = $meta->getReflectionProperty( $nodeID );
  55. $id = $refProp->getValue( $node );
  56. return $id;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. protected function validates()
  62. {
  63. // Temporarily solution to validation problem with this class
  64. return true;
  65. }
  66. }