No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

113 líneas
2.7KB

  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 count(): string
  38. {
  39. return $this->query->getQuery()
  40. ->getSingleScalarResult();
  41. }
  42. public function findOne()
  43. {
  44. return $this->query->getQuery()
  45. ->setMaxResults(1)
  46. ->getOneOrNullResult();
  47. }
  48. public function find(): array
  49. {
  50. return $this->query->getQuery()->getResult();
  51. }
  52. public function limit(int $maxResults)
  53. {
  54. return $this->query->setMaxResults($maxResults);
  55. }
  56. public function paginate(int $page = 1, int $limit = 20)
  57. {
  58. return $this->paginator->paginate($this->query->getQuery(), $page, $limit);
  59. }
  60. public function getRepository(): ServiceEntityRepository
  61. {
  62. return $this->repository;
  63. }
  64. protected function populateDqlId(&$data)
  65. {
  66. if (is_string($data)) {
  67. $words = explode(' ', $data);
  68. foreach ($words as $k => $v) {
  69. if (isset($v[0]) && '.' === $v[0]) {
  70. $words[$k] = $this->id . $v;
  71. }
  72. }
  73. $data = implode(' ', $words);
  74. } elseif (is_array($data)) {
  75. foreach ($data as $k => $v) {
  76. $this->populateDqlId($data[$k]);
  77. }
  78. }
  79. return $data;
  80. }
  81. public function orderBy(string $field, string $sort = 'ASC'): self
  82. {
  83. if (substr($field, 0, 1) === '.') {
  84. return $this->addOrderBy($field, $sort);
  85. } else {
  86. return $this->addOrderBy('.' . $field, $sort);
  87. }
  88. }
  89. }