-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathForeignFieldQueryExtension.php
335 lines (277 loc) · 8.37 KB
/
ForeignFieldQueryExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<?php
namespace lenz\craft\utils\foreignField;
use Craft;
use craft\db\ActiveRecord;
use craft\elements\db\ElementQuery;
use craft\elements\db\ElementQueryInterface;
use craft\events\CancelableEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\Db;
use craft\helpers\Json;
use Exception;
use Yii;
use yii\base\Event;
/**
* Class ForeignFieldQueryExtension
*/
class ForeignFieldQueryExtension
{
/**
* @phpstan-var bool
*/
public bool $enableEagerLoad;
/**
* @phpstan-var bool
*/
public bool $enableJoin;
/**
* @phpstan-var ForeignField
*/
public ForeignField $field;
/**
* @phpstan-var array|null
*/
public ?array $filters;
/**
* @phpstan-var ElementQuery
*/
public ElementQuery $query;
/**
* @phpstan-var ForeignFieldQueryExtension[]
*/
private static array $INSTANCES = array();
/**
* ForeignFieldQueryExtension constructor.
* @phpstan-param array $config
*/
public final function __construct(array $config) {
self::$INSTANCES[] = $this;
Yii::configure($this, $config);
$this->query->on(
ElementQuery::EVENT_AFTER_PREPARE,
[$this, 'onAfterPrepare']
);
}
/**
* @phpstan-return void
*/
public function onAfterPrepare(): void {
$enableEagerLoad = (
$this->enableEagerLoad && (
!empty($this->filters) ||
!static::isCountQuery($this->query)
)
);
if ($enableEagerLoad || $this->enableJoin) {
$this->attachJoin();
}
if ($enableEagerLoad) {
$this->attachEagerLoad();
}
}
// Protected methods
// -----------------
/**
* @phpstan-param array $options
* @phpstan-return $this
*/
protected function applyOptions(array $options): static {
$this->enableEagerLoad = $this->enableEagerLoad || $options['enableEagerLoad'];
$this->enableJoin = $this->enableJoin || $options['enableJoin'];
if (is_array($options['filters'])) {
$this->filters = is_array($this->filters)
? array_merge($this->filters, $options['filters'])
: $options['filters'];
}
return $this;
}
/**
* @phpstan-return void
*/
protected function attachEagerLoad(): void {
$this->query->query->addSelect([
'field:' . $this->field->handle => $this->getJsonExpression(),
]);
}
/**
* @phpstan-return void
*/
protected function attachJoin(): void {
/** @var ActiveRecord $recordClass */
$recordClass = $this->field::recordClass();
$tableName = $recordClass::tableName();
$handle = $this->field->handle;
$fieldId = $this->field->id;
$query = $this->query->query;
$subQuery = $this->query->subQuery;
$conditions = [
"[[$handle.elementId]] = [[elements.id]]",
"[[$handle.fieldId]] = $fieldId"
];
if ($this->field::hasPerSiteRecords()) {
$conditions[] = "[[$handle.siteId]] = [[elements_sites.siteId]]";
}
$conditionsList = implode(' AND ', $conditions);
$query->leftJoin($tableName . ' ' . $handle, $conditionsList);
$subQuery->leftJoin($tableName . ' ' . $handle, $conditionsList);
if (is_array($this->filters)) {
foreach ($this->filters as $name => $filter) {
$subQuery->andWhere(Db::parseParam("[[$handle.$name]]", $filter));
}
}
}
/**
* @phpstan-return string
*/
protected function getJsonExpression(): string {
$attributes = $this->field::recordModelAttributes();
$handle = $this->field->handle;
$fields = [];
foreach ($attributes as $attribute) {
$fields[] = '"' . $attribute . '"';
$fields[] = "[[$handle.$attribute]]";
}
$fieldsList = implode(', ', $fields);
$jsonFunction = Craft::$app->getDb()->getIsMysql()
? 'json_object'
: 'json_build_object';
return "IF([[$handle.id]] IS NULL, NULL, $jsonFunction($fieldsList))";
}
// Static public methods
// ---------------------
/**
* @phpstan-param ElementQueryInterface $query
* @phpstan-param ForeignField $field
* @phpstan-param array $options
* @phpstan-return ForeignFieldQueryExtension|void|null
* @throws Exception
* @noinspection PhpUnused (API)
*/
static public function attachTo(ElementQueryInterface $query, ForeignField $field, array $options = []) {
if (!($query instanceof ElementQuery)) {
return;
}
$filters = ArrayHelper::getValue($options, 'filters');
$forceEagerLoad = !!ArrayHelper::getValue($options, 'forceEagerLoad', false);
$forceJoin = !!ArrayHelper::getValue($options, 'forceJoin', false);
$enableEagerLoad = static::enableEagerLoad($query, $field) || $forceEagerLoad;
$enableJoin = static::enableJoin($query, $field) || $filters || $forceJoin;
if ($enableEagerLoad || $enableJoin) {
$options = [
'enableEagerLoad' => $enableEagerLoad,
'enableJoin' => $enableJoin,
'field' => $field,
'filters' => $filters,
'query' => $query,
];
foreach (self::$INSTANCES as $instance) {
if ($instance->query === $query) {
return $instance->applyOptions($options);
}
}
return new static($options);
}
return null;
}
/**
* @phpstan-param ElementQuery $query
* @phpstan-return bool
*/
static public function isCountQuery(ElementQuery $query): bool {
return (
count($query->select) == 1 &&
reset($query->select) == 'COUNT(*)'
);
}
// Static protected methods
// ------------------------
/**
* @phpstan-param ElementQuery $query
* @phpstan-param ForeignField $field
* @phpstan-return bool
*/
static protected function enableEagerLoad(ElementQuery $query, ForeignField $field): bool {
$handle = $field->handle;
if ($query->with == $handle) {
$query->with = null;
return true;
}
if (is_array($query->with) && in_array($handle, $query->with)) {
ArrayHelper::removeValue($query->with, $handle);
return true;
}
return false;
}
/**
* @phpstan-param ElementQuery $query
* @phpstan-param ForeignField $field
* @phpstan-return bool
*/
static protected function enableJoin(ElementQuery $query, ForeignField $field): bool {
$values = array_merge(
is_array($query->orderBy) ? $query->orderBy : [$query->orderBy],
is_array($query->groupBy) ? $query->groupBy : [$query->groupBy],
[Json::encode($query->where)]
);
$values = array_filter(
array_merge(array_values($values), array_keys($values)),
fn($value) => is_string($value) && !empty($value)
);
foreach ($values as $value) {
if (str_contains($value, $field->handle)) {
return true;
}
}
return false;
}
/**
* @phpstan-return void
*/
static public function init(): void {
static $isInitialized;
if (isset($isInitialized)) return;
$isInitialized = true;
Event::on(ElementQuery::class, ElementQuery::EVENT_BEFORE_PREPARE, function(CancelableEvent $event) {
$query = $event->sender;
if (!($query instanceof ElementQuery) || !$query->withCustomFields) {
return;
}
$fieldAttributes = $query->getBehavior('customFields');
$fieldLayouts = Craft::$app->getFields()->getLayoutsByType($query->elementType);
$fields = array_filter(array_unique(array_reduce($fieldLayouts,
fn($fields, $fieldLayout) => array_merge($fields, $fieldLayout->getCustomFields()),
[])),
fn($field) => $field instanceof ForeignField
);
foreach ($fields as $field) {
$queryClass = $field::queryExtensionClass();
$handle = $field->handle;
$filter = $fieldAttributes->$handle ?? null;
$queryClass::attachTo($query, $field, [
'filters' => $queryClass::prepareQueryFilter($field, $filter),
]);
}
});
}
/**
* @phpstan-param ForeignField $field
* @phpstan-param mixed $value
* @phpstan-return array|null
* @throws Exception
*/
static function prepareQueryFilter(ForeignField $field, mixed $value): ?array {
if (empty($value)) {
return null;
}
if (!is_array($value)) {
throw new Exception("The query value for the field $field->handle must be an array.");
}
$attributes = $field::recordModelAttributes();
foreach ($value as $attribute => $condition) {
if (!in_array($attribute, $attributes)) {
throw new Exception("The query for the field $field->handle refers to an unknown field '$attribute'.");
}
}
return $value;
}
}