Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

94 lines
2.2KB

  1. <?php
  2. namespace Lc\SovBundle\Repository;
  3. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  4. use Doctrine\ORM\QueryBuilder;
  5. use Knp\Component\Pager\PaginatorInterface;
  6. abstract class AbstractRepositoryQuery
  7. {
  8. protected ServiceEntityRepository $repository;
  9. protected QueryBuilder $query;
  10. protected PaginatorInterface $paginator;
  11. protected string $id;
  12. public function __construct(ServiceEntityRepository $repository, string $id, PaginatorInterface $paginator = null)
  13. {
  14. $this->repository = $repository;
  15. $this->query = $repository->createQueryBuilder($id);
  16. $this->paginator = $paginator;
  17. $this->id = $id;
  18. }
  19. public function __call(string $name, $params): self
  20. {
  21. foreach ($params as $key => $value) {
  22. $this->populateDqlId($params[$key]);
  23. }
  24. call_user_func_array([$this->query, $name], $params);
  25. return $this;
  26. }
  27. public function create()
  28. {
  29. $class = get_called_class();
  30. return new $class($this->repository, $this->paginator);
  31. }
  32. public function call(callable $fn): self
  33. {
  34. $fn($this->query, $this);
  35. return $this;
  36. }
  37. public function findOne()
  38. {
  39. return $this->query->getQuery()
  40. ->setMaxResults(1)
  41. ->getOneOrNullResult()
  42. ;
  43. }
  44. public function find()
  45. {
  46. return $this->query->getQuery()->getResult();
  47. }
  48. public function paginate(int $page = 1, int $limit = 20)
  49. {
  50. return $this->paginator->paginate($this->query->getQuery(), $page, $limit);
  51. }
  52. public function getRepository(): ServiceEntityRepository
  53. {
  54. return $this->repository;
  55. }
  56. protected function populateDqlId(&$data)
  57. {
  58. if (is_string($data)) {
  59. $words = explode(' ', $data);
  60. foreach ($words as $k => $v) {
  61. if (isset($v[0]) && '.' === $v[0]) {
  62. $words[$k] = $this->id.$v;
  63. }
  64. }
  65. $data = implode(' ', $words);
  66. } elseif (is_array($data)) {
  67. foreach ($data as $k => $v) {
  68. $this->populateDqlId($data[$k]);
  69. }
  70. }
  71. return $data;
  72. }
  73. }