ClosureTreeRepository.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. $qb->andWhere('c.depth = 1');
  40. }
  41. $qb->setParameter('node_id', $id);
  42. return $qb->getQuery()->getSingleScalarResult();
  43. }
  44. protected function getQueryBuilder()
  45. {
  46. $qb = $this->_em->createQueryBuilder();
  47. return $qb;
  48. }
  49. protected function getIdFromEntity( $node )
  50. {
  51. $meta = $this->_em->getClassMetadata(get_class($node));
  52. $nodeID = $meta->getSingleIdentifierFieldName();
  53. $refProp = $meta->getReflectionProperty($nodeID);
  54. $id = $refProp->getValue($node);
  55. return $id;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function validates()
  61. {
  62. // Temporarily solution to validation problem with this class
  63. return true;
  64. }
  65. }