QueryBuilder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <?php
  2. namespace Michel\PaperORM\Query;
  3. use InvalidArgumentException;
  4. use LogicException;
  5. use Michel\PaperORM\Cache\EntityMemcachedCache;
  6. use Michel\PaperORM\Entity\EntityInterface;
  7. use Michel\PaperORM\EntityManagerInterface;
  8. use Michel\PaperORM\Hydrator\ArrayHydrator;
  9. use Michel\PaperORM\Hydrator\EntityHydrator;
  10. use Michel\PaperORM\Hydrator\ReadOnlyEntityHydrator;
  11. use Michel\PaperORM\Mapper\ColumnMapper;
  12. use Michel\PaperORM\Mapper\EntityMapper;
  13. use Michel\PaperORM\Mapping\Column\Column;
  14. use Michel\PaperORM\Mapping\Column\JoinColumn;
  15. use Michel\PaperORM\Mapping\OneToMany;
  16. use Michel\PaperORM\Platform\PlatformInterface;
  17. use Michel\PaperORM\Schema\SchemaInterface;
  18. use Michel\SqlMapper\QL\JoinQL;
  19. final class QueryBuilder
  20. {
  21. public const HYDRATE_OBJECT = 'object';
  22. public const HYDRATE_OBJECT_READONLY = 'readonly';
  23. public const HYDRATE_ARRAY = 'array';
  24. private PlatformInterface $platform;
  25. private SchemaInterface $schema;
  26. private EntityMemcachedCache $cache;
  27. private AliasGenerator $aliasGenerator;
  28. private array $select = [];
  29. private array $where = [];
  30. private array $rawWhere = [];
  31. private array $orderBy = [];
  32. private array $joins = [];
  33. private array $joinsAlreadyAdded = [];
  34. private ?int $firstResult = null;
  35. private ?int $maxResults = null;
  36. private array $params = [];
  37. public function __construct(EntityManagerInterface $em)
  38. {
  39. $this->platform = $em->getPlatform();
  40. $this->schema = $this->platform->getSchema();;
  41. $this->cache = $em->getCache();
  42. $this->aliasGenerator = new AliasGenerator();
  43. }
  44. public function getResultIterator(string $hydrationMode = self::HYDRATE_OBJECT): iterable
  45. {
  46. foreach ($this->buildSqlQuery()->getResultIterator() as $item) {
  47. yield $this->hydrate([$item], $hydrationMode)[0];
  48. }
  49. }
  50. public function getArrayResult(): array
  51. {
  52. return $this->getResult(self::HYDRATE_ARRAY);
  53. }
  54. public function getResult(string $hydrationMode = self::HYDRATE_OBJECT): array
  55. {
  56. return $this->hydrate($this->buildSqlQuery()->getResult(), $hydrationMode);
  57. }
  58. public function getOneOrNullResult(string $hydrationMode = self::HYDRATE_OBJECT)
  59. {
  60. $item = $this->buildSqlQuery()->getOneOrNullResult();
  61. if ($item === null) {
  62. return null;
  63. }
  64. return $this->hydrate([$item], $hydrationMode)[0];
  65. }
  66. public function getCountResult(): int
  67. {
  68. return $this->buildSqlQuery()->count();
  69. }
  70. public function select(string $entityName, array $properties = []): self
  71. {
  72. $this->select = [
  73. 'table' => $this->getTableName($entityName),
  74. 'entityName' => $entityName,
  75. 'alias' => $this->aliasGenerator->generateAlias($entityName),
  76. 'properties' => $properties
  77. ];
  78. return $this;
  79. }
  80. public function getPrimaryAlias(): string
  81. {
  82. if (empty($this->select)) {
  83. throw new LogicException('Select must be called before getPrimaryAlias');
  84. }
  85. return $this->select['alias'];
  86. }
  87. public function getPrimaryEntityName(): string
  88. {
  89. if (empty($this->select)) {
  90. throw new LogicException('Select must be called before getPrimaryEntityName');
  91. }
  92. return $this->select['entityName'];
  93. }
  94. public function where(string ...$expressions): self
  95. {
  96. foreach ($expressions as $expression) {
  97. $this->where[] = $expression;
  98. }
  99. return $this;
  100. }
  101. public function rawWhere(string $sql): self
  102. {
  103. if (empty($this->select)) {
  104. throw new LogicException('Select must be called before rawWhere()');
  105. }
  106. $this->rawWhere[] = $sql;
  107. return $this;
  108. }
  109. public function orderBy(string $sort, string $order = 'ASC'): self
  110. {
  111. $this->orderBy[] = [
  112. 'sort' => $sort,
  113. 'order' => $order
  114. ];
  115. return $this;
  116. }
  117. public function setParams(array $params): self
  118. {
  119. $this->params = $params;
  120. return $this;
  121. }
  122. public function setParam(string $name, $value): self
  123. {
  124. $this->params[$name] = $value;
  125. return $this;
  126. }
  127. public function resetWhere(): self
  128. {
  129. $this->where = [];
  130. $this->rawWhere = [];
  131. return $this;
  132. }
  133. public function resetOrderBy() : self
  134. {
  135. $this->orderBy = [];
  136. return $this;
  137. }
  138. public function resetParams(): self
  139. {
  140. $this->params = [];
  141. return $this;
  142. }
  143. public function leftJoin(string $fromAliasOrEntityName, string $targetEntityName, ?string $property = null): self
  144. {
  145. return $this->join('LEFT', $fromAliasOrEntityName, $targetEntityName, $property);
  146. }
  147. public function innerJoin(string $fromAliasOrEntityName, string $targetEntityName, ?string $property = null): self
  148. {
  149. return $this->join('INNER', $fromAliasOrEntityName, $targetEntityName, $property);
  150. }
  151. public function joinSelect(string ...$columns): self
  152. {
  153. if (empty($this->joins)) {
  154. throw new LogicException(
  155. 'You must call the innerJoin() or leftJoin() method first to define columns to select'
  156. );
  157. }
  158. $index = \array_key_last($this->joins);
  159. $this->joins[$index]['columnsToSelect'] = $columns;
  160. return $this;
  161. }
  162. public function setFirstResult(?int $firstResult): self
  163. {
  164. if ($this->select === []) {
  165. throw new LogicException(
  166. 'You must call the select() method first to define the main table for the query '
  167. );
  168. }
  169. $this->firstResult = $firstResult;
  170. return $this;
  171. }
  172. public function setMaxResults(?int $maxResults): self
  173. {
  174. if ($this->select === []) {
  175. throw new LogicException(
  176. 'You must call the select() method first to define the main table for the query '
  177. );
  178. }
  179. $this->maxResults = $maxResults;
  180. return $this;
  181. }
  182. private function join(string $type, string $fromAliasOrEntityName, string $targetEntityName, ?string $property = null): self
  183. {
  184. if (class_exists($fromAliasOrEntityName)) {
  185. $fromAliases = $this->getAliasesFromEntityName($fromAliasOrEntityName);
  186. } else {
  187. $fromAliases = [$fromAliasOrEntityName];
  188. }
  189. /**
  190. * @comment IS security , we need to check if the join is already added !!!
  191. */
  192. $key = md5(sprintf('%s.%s.%s.%s', $type,$fromAliasOrEntityName, $targetEntityName, $property));
  193. if (in_array($key, $this->joinsAlreadyAdded)) {
  194. return $this;
  195. }
  196. $this->joinsAlreadyAdded[] = $key;
  197. foreach ($fromAliases as $fromAlias) {
  198. $fromEntityName = $this->getEntityNameFromAlias($fromAlias);
  199. $columns = $this->getRelationsColumns($fromEntityName, $targetEntityName, $property);
  200. foreach ($columns as $column) {
  201. $alias = $this->aliasGenerator->generateAlias($targetEntityName);
  202. $this->joins[$alias] = [
  203. 'type' => $type,
  204. 'alias' => $alias,
  205. 'targetEntity' => $targetEntityName,
  206. 'targetTable' => $this->getTableName($targetEntityName),
  207. 'columnsToSelect' => null,
  208. 'fromEntityName' => $fromEntityName,
  209. 'fromTable' => $this->getTableName($fromEntityName),
  210. 'fromAlias' => $fromAlias,
  211. 'column' => $column,
  212. 'property' => $property,
  213. 'isOneToMany' => $column instanceof OneToMany
  214. ];
  215. }
  216. }
  217. return $this;
  218. }
  219. private function convertPropertiesToColumns(string $entityName, array $properties): array
  220. {
  221. $columns = [];
  222. foreach ($properties as $property) {
  223. if ($property instanceof Column) {
  224. $propertyName = $property->getProperty();
  225. } elseif (is_string($property)) {
  226. $propertyName = $property;
  227. } else {
  228. throw new InvalidArgumentException("Property {$property} not found in class " . $entityName);
  229. }
  230. $column = ColumnMapper::getColumnByProperty($entityName, $propertyName);
  231. if ($column === null) {
  232. throw new InvalidArgumentException("Property {$propertyName} not found in class " . $entityName);
  233. }
  234. $columns[] = $this->schema->quote($column->getName());
  235. }
  236. return $columns;
  237. }
  238. /**
  239. * @param string $entityName
  240. * @param string $targetEntityName
  241. * @param string|null $property
  242. * @return array<int,JoinColumn|OneToMany>
  243. */
  244. private function getRelationsColumns(string $entityName, string $targetEntityName, ?string $property = null): array
  245. {
  246. $relationsColumns = [];
  247. foreach (ColumnMapper::getColumns($entityName) as $column) {
  248. if ($column instanceof JoinColumn) {
  249. $relationsColumns[$column->getProperty()] = $column;
  250. }
  251. }
  252. foreach (ColumnMapper::getOneToManyRelations($entityName) as $column) {
  253. $relationsColumns[$column->getProperty()] = $column;
  254. }
  255. if ($relationsColumns === []) {
  256. throw new InvalidArgumentException("Entity {$targetEntityName} not found in class " . $entityName);
  257. }
  258. $columns = [];
  259. if ($property) {
  260. $column = $relationsColumns[$property] ?? null;
  261. if ($column) {
  262. $columns[] = $column;
  263. }
  264. } else {
  265. foreach ($relationsColumns as $column) {
  266. if ($column->getTargetEntity() === $targetEntityName) {
  267. $columns[] = $column;
  268. }
  269. }
  270. }
  271. if ($columns === []) {
  272. throw new InvalidArgumentException("Entity {$targetEntityName} not found in class " . $entityName);
  273. }
  274. return $columns;
  275. }
  276. private function getTableName(string $entityName): string
  277. {
  278. return EntityMapper::getTable($entityName);
  279. }
  280. public function buildSqlQuery(): JoinQL
  281. {
  282. if ($this->select === []) {
  283. throw new LogicException('No query specified');
  284. }
  285. $properties = $this->select['properties'];
  286. $entityName = $this->select['entityName'];
  287. $alias = $this->select['alias'];
  288. $table = $this->select['table'];
  289. if ($properties === []) {
  290. $properties = ColumnMapper::getColumns($entityName);
  291. }
  292. $columns = $this->convertPropertiesToColumns($entityName, $properties);
  293. $primaryKey = ColumnMapper::getPrimaryKeyColumnName($entityName);
  294. $primaryKeyQuoted = $this->schema->quote($primaryKey);
  295. if (!in_array($primaryKeyQuoted, $columns)) {
  296. $columns[] = $primaryKeyQuoted;
  297. }
  298. if ($columns[0] !== $primaryKeyQuoted) {
  299. $columns = array_unique([$primaryKeyQuoted, ...$columns]);
  300. }
  301. $joinQl = new JoinQL($this->platform->getConnection()->getPdo(), $primaryKey, $this->platform->getMaxLength());
  302. $joinQl->select($this->schema->quote($table), $alias, $columns);
  303. foreach ($this->joins as $join) {
  304. $fromAlias = $join['fromAlias'];
  305. $targetTable = $join['targetTable'];
  306. $targetEntity = $join['targetEntity'];
  307. $columnsToSelect = $join['columnsToSelect'];
  308. $alias = $join['alias'];
  309. /**
  310. * @var JoinColumn|OneToMany $column
  311. */
  312. $column = $join['column'];
  313. $isOneToMany = $join['isOneToMany'];
  314. $type = $join['type'];
  315. $name = null;
  316. $columns = [];
  317. if ($join['columnsToSelect'] === null) {
  318. $columns = $this->convertPropertiesToColumns($targetEntity, ColumnMapper::getColumns($targetEntity));
  319. }elseif (!empty($columnsToSelect)) {
  320. $columns = $this->convertPropertiesToColumns($targetEntity, $columnsToSelect);
  321. }
  322. if (!empty($columns)) {
  323. $joinQl->addSelect($alias, $columns);
  324. }
  325. $criteria = [];
  326. if ($column instanceof JoinColumn) {
  327. $criteria = [$column->getName() => $column->getReferencedColumnName()];
  328. $name = $column->getName();
  329. } elseif ($column instanceof OneToMany) {
  330. $criteria = $column->getCriteria();
  331. $mappedBy = $column->getMappedBy(); //@todo VOIR SI RENDRE OBLIGATOIRE : A DISCUTER !!!
  332. if ($mappedBy) {
  333. $columnMappedBy = ColumnMapper::getColumnByProperty($targetEntity, $mappedBy);
  334. if (!$columnMappedBy instanceof JoinColumn) {
  335. throw new InvalidArgumentException("Property mapped by {$mappedBy} not found in class " . $targetEntity);
  336. }
  337. $name = $columnMappedBy->getName();
  338. $criteria = $criteria + [$columnMappedBy->getReferencedColumnName() => $columnMappedBy->getName()];
  339. }
  340. }
  341. $joinConditions = [];
  342. $targetTable = $this->schema->quote($targetTable);
  343. foreach ($criteria as $key => $value) {
  344. $value = "$alias.$value";
  345. $joinConditions[] = "$fromAlias.$key = $value";
  346. }
  347. if ($type === 'LEFT') {
  348. $joinQl->leftJoin($fromAlias, $targetTable, $alias, $joinConditions, $isOneToMany, $column->getProperty(), $name);
  349. } elseif ($type === 'INNER') {
  350. $joinQl->innerJoin($fromAlias, $targetTable, $alias, $joinConditions, $isOneToMany, $column->getProperty(), $name);
  351. }
  352. }
  353. foreach ($this->where as $where) {
  354. $joinQl->where($this->resolveExpression($where));
  355. }
  356. foreach ($this->rawWhere as $rawWhere) {
  357. $joinQl->where($rawWhere);
  358. }
  359. foreach ($this->orderBy as $orderBy) {
  360. $joinQl->orderBy($this->resolveExpression($orderBy['sort']), $orderBy['order']);
  361. }
  362. foreach ($this->params as $key => $value) {
  363. if ($value instanceof EntityInterface) {
  364. $value = $value->getPrimaryKeyValue();
  365. }elseif (is_iterable($value)) {
  366. $values = [];
  367. foreach ($value as $v) {
  368. if ($v instanceof EntityInterface) {
  369. $values[] = $v->getPrimaryKeyValue();
  370. }else {
  371. $values[] = $v;
  372. }
  373. }
  374. $value = implode(',', $values);
  375. }
  376. $joinQl->setParam($key, $value);
  377. }
  378. if ($this->maxResults) {
  379. $joinQl->setMaxResults($this->maxResults);
  380. }
  381. if ($this->firstResult) {
  382. $joinQl->setFirstResult($this->firstResult);
  383. }
  384. return $joinQl;
  385. }
  386. public function getAliasesFromEntityName(string $entityName, string $property = null): array
  387. {
  388. $aliases = [];
  389. if (isset($this->select['entityName']) && $this->select['entityName'] === $entityName) {
  390. $aliases[] = $this->select['alias'];
  391. }
  392. foreach ($this->joins as $keyAsAlias => $join) {
  393. if ($join['targetEntity'] === $entityName && $join['property'] === $property) {
  394. $aliases[] = $keyAsAlias;
  395. }
  396. }
  397. if ($aliases === []) {
  398. throw new LogicException('Alias not found for ' . $entityName);
  399. }
  400. return $aliases;
  401. }
  402. private function getEntityNameFromAlias(string $alias): string
  403. {
  404. if (isset($this->select['alias']) && $this->select['alias'] === $alias) {
  405. return $this->select['entityName'];
  406. }
  407. $entityName = null;
  408. foreach ($this->joins as $keyAsAlias => $join) {
  409. if ($keyAsAlias === $alias) {
  410. $entityName = $join['targetEntity'];
  411. break;
  412. }
  413. }
  414. if ($entityName === null) {
  415. throw new LogicException('Entity name not found for ' . $alias);
  416. }
  417. return $entityName;
  418. }
  419. private function hydrate(array $data, string $hydrationMode): array
  420. {
  421. if ($hydrationMode === self::HYDRATE_OBJECT) {
  422. $hydrator = new EntityHydrator($this->schema, $this->cache);
  423. } elseif ($hydrationMode === self::HYDRATE_OBJECT_READONLY) {
  424. $hydrator = new ReadOnlyEntityHydrator($this->schema);
  425. } else {
  426. $hydrator = new ArrayHydrator($this->schema);
  427. }
  428. $collection = [];
  429. foreach ($data as $item) {
  430. $collection[] = $hydrator->hydrate($this->select['entityName'], $item);
  431. }
  432. return $collection;
  433. }
  434. private function resolveExpression(string $expression): string
  435. {
  436. $aliases = AliasDetector::detect($expression);
  437. foreach ($aliases as $alias => $properties) {
  438. $fromEntityName = $this->getEntityNameFromAlias($alias);
  439. foreach ($properties as $property) {
  440. $column = ColumnMapper::getColumnByProperty($fromEntityName, $property);
  441. if ($column === null) {
  442. throw new InvalidArgumentException(sprintf('Property %s not found in class %s or is a collection and cannot be used in an expression', $property, $fromEntityName));
  443. }
  444. $expression = str_replace($alias . '.' . $property, $this->schema->quote($alias) . '.'.$this->schema->quote($column->getName()), $expression);
  445. }
  446. }
  447. return $expression;
  448. }
  449. }