|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Bancer\NativeQueryMapper\ORM; |
| 6 | + |
| 7 | +use Cake\Database\StatementInterface; |
| 8 | +use Cake\ORM\Table; |
| 9 | + |
| 10 | +/** |
| 11 | + * Wrapper around a prepared SQL statement that executes it |
| 12 | + * and hydrates the result set into CakePHP entities using |
| 13 | + * a mapping strategy inferred from column aliases. |
| 14 | + * |
| 15 | + * This class is created via `prepareNativeStatement()` and |
| 16 | + * `mapNativeStatement()` in the `NativeSQLMapperTrait`. |
| 17 | + */ |
| 18 | +class NativeQueryResultMapper |
| 19 | +{ |
| 20 | + /** |
| 21 | + * The root table used to determine entity classes, |
| 22 | + * associations, and hydration rules. |
| 23 | + * |
| 24 | + * @var \Cake\ORM\Table |
| 25 | + */ |
| 26 | + protected Table $rootTable; |
| 27 | + |
| 28 | + /** |
| 29 | + * The prepared PDO statement to be executed. |
| 30 | + * |
| 31 | + * @var \Cake\Database\StatementInterface |
| 32 | + */ |
| 33 | + protected StatementInterface $stmt; |
| 34 | + |
| 35 | + /** |
| 36 | + * Whether the statement has already been executed. |
| 37 | + * |
| 38 | + * @var bool |
| 39 | + */ |
| 40 | + protected bool $isExecuted; |
| 41 | + |
| 42 | + /** |
| 43 | + * Custom mapping strategy used to hydrate entities. |
| 44 | + * If null, a MappingStrategy will be automatically built |
| 45 | + * based on detected column aliases. |
| 46 | + * |
| 47 | + * @var array<string,mixed>|null |
| 48 | + */ |
| 49 | + protected $mapStrategy = null; |
| 50 | + |
| 51 | + /** |
| 52 | + * Constructor. |
| 53 | + * |
| 54 | + * @param \Cake\ORM\Table $rootTable The root table instance. |
| 55 | + * @param \Cake\Database\StatementInterface $stmt The prepared statement. |
| 56 | + */ |
| 57 | + public function __construct(Table $rootTable, StatementInterface $stmt) |
| 58 | + { |
| 59 | + $this->rootTable = $rootTable; |
| 60 | + $this->stmt = $stmt; |
| 61 | + $this->isExecuted = false; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Provide a custom mapping strategy instead of relying |
| 66 | + * on automatic alias inference. |
| 67 | + * |
| 68 | + * The structure must match the output of MappingStrategy::toArray(). |
| 69 | + * |
| 70 | + * @param array<string,mixed> $strategy Mapping configuration. |
| 71 | + * @return $this |
| 72 | + */ |
| 73 | + public function setMappingStrategy(array $strategy): self |
| 74 | + { |
| 75 | + $this->mapStrategy = $strategy; |
| 76 | + return $this; |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * Execute the SQL statement if not executed yet, fetch all rows, |
| 81 | + * build (or use) the mapping strategy, and hydrate the result set |
| 82 | + * into entities. |
| 83 | + * |
| 84 | + * @return \Cake\Datasource\EntityInterface[] Hydrated entity list. |
| 85 | + */ |
| 86 | + public function all(): array |
| 87 | + { |
| 88 | + if (!$this->isExecuted) { |
| 89 | + $this->stmt->execute(); |
| 90 | + $this->isExecuted = true; |
| 91 | + } |
| 92 | + $rows = $this->stmt->fetchAll(\PDO::FETCH_ASSOC); |
| 93 | + if (!$rows) { |
| 94 | + return []; |
| 95 | + } |
| 96 | + $aliasMap = []; |
| 97 | + if ($this->mapStrategy === null) { |
| 98 | + $aliases = $this->extractAliases($rows); |
| 99 | + $strategy = new MappingStrategy($this->rootTable, $aliases); |
| 100 | + $this->mapStrategy = $strategy->build()->toArray(); |
| 101 | + $aliasMap = $strategy->getAliasMap(); |
| 102 | + } |
| 103 | + $hydrator = new RecursiveEntityHydrator($this->rootTable, $this->mapStrategy, $aliasMap); |
| 104 | + return $hydrator->hydrateMany($rows); |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * Extract column aliases used in the SQL result set. |
| 109 | + * |
| 110 | + * Each column must follow `{Alias}__{column}` format. |
| 111 | + * Throws UnknownAliasException if the alias format is invalid. |
| 112 | + * |
| 113 | + * @param array<int,array<string,mixed>|mixed> $rows Result set rows. |
| 114 | + * @return string[] Sorted list of unique aliases. |
| 115 | + * |
| 116 | + * @throws \InvalidArgumentException If the first row is not an array. |
| 117 | + * @throws \Bancer\NativeQueryMapper\ORM\UnknownAliasException |
| 118 | + * If a column does not follow expected alias format. |
| 119 | + */ |
| 120 | + protected function extractAliases(array $rows): array |
| 121 | + { |
| 122 | + $firstRow = $rows[0] ?? []; |
| 123 | + if (!is_array($firstRow)) { |
| 124 | + throw new \InvalidArgumentException('First element of the result set is not an array'); |
| 125 | + } |
| 126 | + $keys = array_keys($firstRow); |
| 127 | + $aliases = []; |
| 128 | + foreach ($keys as $key) { |
| 129 | + if (!is_string($key) || !str_contains($key, '__')) { |
| 130 | + throw new UnknownAliasException("Column '$key' must use an alias in the format {Alias}__$key"); |
| 131 | + } |
| 132 | + [$alias, $field] = explode('__', $key, 2); |
| 133 | + if (mb_strlen($alias) <= 0 || mb_strlen($field) <= 0) { |
| 134 | + $message = "Alias '$key' is invalid. Column alias must use {Alias}__{column_name} format"; |
| 135 | + throw new UnknownAliasException($message); |
| 136 | + } |
| 137 | + $aliases[] = $alias; |
| 138 | + } |
| 139 | + sort($aliases); |
| 140 | + return $aliases; |
| 141 | + } |
| 142 | +} |
0 commit comments