QueryBuilder.php 16 KB

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