ClosureTreeRepository.php 2.0 KB

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