-
Notifications
You must be signed in to change notification settings - Fork 635
/
ElementSources.php
535 lines (477 loc) · 19.6 KB
/
ElementSources.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\conditions\ConditionInterface;
use craft\base\ElementInterface;
use craft\base\PreviewableFieldInterface;
use craft\base\SortableFieldInterface;
use craft\db\CoalesceColumnsExpression;
use craft\errors\SiteNotFoundException;
use craft\events\DefineSourceSortOptionsEvent;
use craft\events\DefineSourceTableAttributesEvent;
use craft\fieldlayoutelements\CustomField;
use craft\helpers\ArrayHelper;
use craft\helpers\Cp;
use craft\helpers\StringHelper;
use craft\models\FieldLayout;
use Illuminate\Support\Collection;
use yii\base\Component;
/**
* The Element Sources service provides APIs for managing element indexes.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getElementSources()|`Craft::$app->elementSources`]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 4.0.0
*/
class ElementSources extends Component
{
/**
* @event DefineSourceTableAttributesEvent The event that is triggered when defining the available table attributes for a source.
*/
public const EVENT_DEFINE_SOURCE_TABLE_ATTRIBUTES = 'defineSourceTableAttributes';
/**
* @event DefineSourceSortOptionsEvent The event that is triggered when defining the available sort options for a source.
*/
public const EVENT_DEFINE_SOURCE_SORT_OPTIONS = 'defineSourceSortOptions';
public const TYPE_HEADING = 'heading';
public const TYPE_NATIVE = 'native';
public const TYPE_CUSTOM = 'custom';
public const CONTEXT_FIELD = 'field';
public const CONTEXT_INDEX = 'index';
public const CONTEXT_MODAL = 'modal';
public const CONTEXT_SETTINGS = 'settings';
/**
* Filters out any unnecessary headings from a given source list.
*
* @param array[] $sources
* @return array[]
*/
public static function filterExtraHeadings(array $sources): array
{
return array_values(array_filter($sources, function($source, $i) use ($sources) {
return (
$source['type'] !== self::TYPE_HEADING ||
(isset($sources[$i + 1]) && $sources[$i + 1]['type'] !== self::TYPE_HEADING)
);
}, ARRAY_FILTER_USE_BOTH));
}
/**
* Returns the element index sources in the custom groupings/order.
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $context The context
* @param bool $withDisabled Whether disabled sources should be included
* @return array[]
*/
public function getSources(string $elementType, string $context = self::CONTEXT_INDEX, bool $withDisabled = false): array
{
/** @var string|ElementInterface $elementType */
$nativeSources = $this->_nativeSources($elementType, $context);
$sourceConfigs = $this->_sourceConfigs($elementType);
if (!empty($sourceConfigs)) {
// Merge native source settings into the configs
$sources = [];
$indexedNativeSources = ArrayHelper::index(array_filter($nativeSources, fn($s) => $s['type'] === self::TYPE_NATIVE), 'key');
$nativeSourceKeys = [];
foreach ($sourceConfigs as $source) {
if ($source['type'] === self::TYPE_NATIVE) {
if (isset($indexedNativeSources[$source['key']])) {
if ($withDisabled || !($source['disabled'] ?? false)) {
$sources[] = $source + $indexedNativeSources[$source['key']];
$nativeSourceKeys[$source['key']] = true;
} else {
unset($indexedNativeSources[$source['key']]);
}
}
} else {
if ($source['type'] === self::TYPE_CUSTOM) {
if (!$this->_showCustomSource($source)) {
continue;
}
$source = $elementType::modifyCustomSource($source);
if (!$withDisabled && ($source['disabled'] ?? false)) {
continue;
}
}
$sources[] = $source;
}
}
// Make sure all native sources are accounted for
$missingSources = array_filter($nativeSources, fn($s) => (
$s['type'] === self::TYPE_NATIVE &&
isset($indexedNativeSources[$s['key']]) &&
!isset($nativeSourceKeys[$s['key']])
));
if (!empty($missingSources)) {
if (!empty($sources)) {
$sources[] = [
'type' => self::TYPE_HEADING,
'heading' => '',
];
}
array_push($sources, ...$missingSources);
}
} else {
$sources = $nativeSources;
}
// Normalize the site IDs
foreach ($sources as &$source) {
if (isset($source['sites'])) {
$sitesService = null;
$source['sites'] = array_filter(array_map(function(int|string $siteId) use (&$sitesService): ?int {
if (is_string($siteId) && StringHelper::isUUID($siteId)) {
$sitesService ??= Craft::$app->getSites();
try {
return $sitesService->getSiteByUid($siteId)->id;
} catch (SiteNotFoundException) {
return null;
}
}
return (int)$siteId;
}, $source['sites'] ?: []));
}
}
return $sources;
}
/**
* Returns whether the given custom source should be available for the current user.
*
* @param array $source
* @return bool
*/
private function _showCustomSource(array $source): bool
{
if (!isset($source['userGroups'])) {
// Show for everyone
return true;
}
$user = Craft::$app->getUser()->getIdentity();
if (!$user) {
return false;
}
if ($user->admin) {
return true;
}
if ($source['userGroups'] === false) {
return false;
}
foreach ($user->getGroups() as $group) {
if (in_array($group->uid, $source['userGroups'], true)) {
return true;
}
}
return false;
}
/**
* Returns the common table attributes that are available for a given element type, across all its sources.
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @return array[]
*/
public function getAvailableTableAttributes(string $elementType): array
{
/** @var string|ElementInterface $elementType */
/** @phpstan-var class-string<ElementInterface>|ElementInterface $elementType */
$attributes = $elementType::tableAttributes();
// Normalize
foreach ($attributes as $key => $info) {
if (!is_array($info)) {
$attributes[$key] = ['label' => $info];
} elseif (!isset($info['label'])) {
$attributes[$key]['label'] = '';
}
if (isset($attributes[$key]['icon']) && in_array($attributes[$key]['icon'], ['world', 'earth'])) {
$attributes[$key]['icon'] = Cp::earthIcon();
}
}
return $attributes;
}
/**
* Returns the attributes that should be shown for a given element type source.
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $sourceKey The element type source key
* @param string[]|null $customAttributes Custom attributes to show rather than the defaults
* @return array[]
*/
public function getTableAttributes(string $elementType, string $sourceKey, ?array $customAttributes = null): array
{
/** @var ElementInterface|string $elementType */
// If this is a source path, use the first segment
if (($slash = strpos($sourceKey, '/')) !== false) {
$sourceKey = substr($sourceKey, 0, $slash);
}
if ($sourceKey === '__IMP__') {
$sourceAttributes = $this->getTableAttributesForFieldLayouts($elementType::fieldLayouts(null));
} else {
$sourceAttributes = $this->getSourceTableAttributes($elementType, $sourceKey);
}
$availableAttributes = array_merge(
$this->getAvailableTableAttributes($elementType),
$sourceAttributes,
);
$attributeKeys = $customAttributes
?? $this->_sourceConfig($elementType, $sourceKey)['tableAttributes']
?? $elementType::defaultTableAttributes($sourceKey);
$attributes = [
// Start with the element type’s display name
['title', ['label' => $elementType::displayName()]],
];
if (is_array($attributeKeys)) {
foreach ($attributeKeys as $key) {
if (isset($availableAttributes[$key])) {
$attributes[] = [$key, $availableAttributes[$key]];
}
}
}
return $attributes;
}
/**
* @var array
* @see getFieldLayoutsForSource()
*/
private array $_fieldLayouts;
/**
* Returns all the field layouts available for the given element source.
*
* @param string $elementType
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $sourceKey
* @return FieldLayout[]
*/
public function getFieldLayoutsForSource(string $elementType, string $sourceKey): array
{
// Don't bother the element type for custom sources
if (str_starts_with($sourceKey, 'custom:')) {
return Craft::$app->getFields()->getLayoutsByType($elementType);
}
if (!isset($this->_fieldLayouts[$elementType][$sourceKey])) {
/** @var string|ElementInterface $elementType */
/** @phpstan-var class-string<ElementInterface>|ElementInterface $elementType */
$this->_fieldLayouts[$elementType][$sourceKey] = $elementType::fieldLayouts($sourceKey);
}
return $this->_fieldLayouts[$elementType][$sourceKey];
}
/**
* Returns additional sort options that should be available for a given element source.
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $sourceKey The element source key
* @return array[]
*/
public function getSourceSortOptions(string $elementType, string $sourceKey): array
{
$fieldLayouts = $this->getFieldLayoutsForSource($elementType, $sourceKey);
$sortOptions = $this->getSortOptionsForFieldLayouts($fieldLayouts);
// Fire a 'defineSourceSortOptions' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_SOURCE_SORT_OPTIONS)) {
$event = new DefineSourceSortOptionsEvent([
'elementType' => $elementType,
'source' => $sourceKey,
'sortOptions' => $sortOptions,
]);
$this->trigger(self::EVENT_DEFINE_SOURCE_SORT_OPTIONS, $event);
$sortOptions = $event->sortOptions;
}
// Combine duplicate attributes. If any attributes map to multiple sort
// options and each option has a string orderBy value, cmobine them
// with a CoalesceColumnsExpression.
return Collection::make($sortOptions)
->groupBy('attribute')
->map(function(Collection $group) {
$orderBys = $group->pluck('orderBy');
if ($orderBys->count() === 1 || $orderBys->doesntContain(fn($orderBy) => is_string($orderBy))) {
return $group->first();
}
$expression = new CoalesceColumnsExpression($orderBys->all());
return array_merge($group->first(), [
'orderBy' => $expression,
]);
})
->all();
}
/**
* Returns additional sort options that should be available for an element index source that includes the given
* field layouts.
*
* @param FieldLayout[] $fieldLayouts
* @return array[]
* @since 5.0.0
*/
public function getSortOptionsForFieldLayouts(array $fieldLayouts): array
{
$sortOptions = [];
foreach ($fieldLayouts as $fieldLayout) {
foreach ($fieldLayout->getCustomFieldElements() as $layoutElement) {
$field = $layoutElement->getField();
if ($field instanceof SortableFieldInterface) {
$sortOption = $field->getSortOption();
if (!isset($sortOption['attribute'])) {
$sortOption['attribute'] = $sortOption['orderBy'];
}
if (!isset($sortOption['defaultDir'])) {
$sortOption['defaultDir'] = 'asc';
}
$sortOptions[] = $sortOption;
}
}
}
return $sortOptions;
}
/**
* Returns any table attributes that should be available for a given source, in addition to the [[getAvailableTableAttributes()|common attributes]].
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $sourceKey The element source key
* @return array[]
*/
public function getSourceTableAttributes(string $elementType, string $sourceKey): array
{
if ($sourceKey === '__IMP__') {
return [];
}
$fieldLayouts = $this->getFieldLayoutsForSource($elementType, $sourceKey);
$attributes = $this->getTableAttributesForFieldLayouts($fieldLayouts);
// Fire a 'defineSourceTableAttributes' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_SOURCE_TABLE_ATTRIBUTES)) {
$event = new DefineSourceTableAttributesEvent([
'elementType' => $elementType,
'source' => $sourceKey,
'attributes' => $attributes,
]);
$this->trigger(self::EVENT_DEFINE_SOURCE_TABLE_ATTRIBUTES, $event);
return $event->attributes;
}
return $attributes;
}
/**
* Returns any table attributes that should be available for an element index source that includes the given
* field layouts.
*
* @param FieldLayout[] $fieldLayouts
* @return array[]
* @since 5.0.0
*/
public function getTableAttributesForFieldLayouts(array $fieldLayouts): array
{
$user = Craft::$app->getUser()->getIdentity();
$attributes = [];
/** @var CustomField[][] $groupedFieldElements */
$groupedFieldElements = [];
foreach ($fieldLayouts as $fieldLayout) {
foreach ($fieldLayout->getTabs() as $tab) {
// Factor in the user condition for non-admins
if ($user && !$user->admin && !($tab->getUserCondition()?->matchElement($user) ?? true)) {
continue;
}
foreach ($tab->getElements() as $layoutElement) {
if (!$layoutElement instanceof CustomField) {
continue;
}
$field = $layoutElement->getField();
if (
$field instanceof PreviewableFieldInterface &&
(!$user || $user->admin || ($layoutElement->getUserCondition()?->matchElement($user) ?? true))
) {
if ($layoutElement->handle === null) {
// The handle wasn't overridden, so combine it with any other instances (from other layouts)
// where the handle also wasn't overridden
$groupedFieldElements[$field->id][] = $layoutElement;
} else {
// The handle was overridden, so it gets its own table attribute
$attributes["fieldInstance:$layoutElement->uid"] = [
'label' => Craft::t('site', $field->name),
];
}
}
}
}
}
foreach ($groupedFieldElements as $fieldElements) {
$field = $fieldElements[0]->getField();
$labels = array_unique(array_map(fn(CustomField $layoutElement) => $layoutElement->label(), $fieldElements));
$attributes["field:$field->uid"] = [
'label' => count($labels) === 1 ? $labels[0] : Craft::t('site', $field->name),
];
}
return $attributes;
}
/**
* Returns the native sources for a given element type and context, normalized with `type` keys.
*
* @param string $elementType
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $context
* @return array[]
*/
private function _nativeSources(string $elementType, string $context): array
{
/** @var string|ElementInterface $elementType */
/** @phpstan-var class-string<ElementInterface>|ElementInterface $elementType */
$sources = $elementType::sources($context);
$normalized = [];
foreach ($sources as $source) {
if (!isset($source['type'])) {
if (array_key_exists('heading', $source)) {
$source['type'] = self::TYPE_HEADING;
} elseif (isset($source['key'])) {
$source['type'] = self::TYPE_NATIVE;
} else {
continue;
}
}
$this->normalizeNativeSource($source);
$normalized[] = $source;
}
return $normalized;
}
private function normalizeNativeSource(array &$source): void
{
if (isset($source['defaultFilter']) && $source['defaultFilter'] instanceof ConditionInterface) {
$source['defaultFilter'] = $source['defaultFilter']->getConfig();
}
if (isset($source['nested'])) {
foreach ($source['nested'] as &$nested) {
$this->normalizeNativeSource($nested);
}
}
}
/**
* Returns the source configs for a given element type.
*
* @param string $elementType The element type class
* @phpstan-param class-string<ElementInterface> $elementType
* @return array[]|null
*/
private function _sourceConfigs(string $elementType): ?array
{
return Craft::$app->getProjectConfig()->get(ProjectConfig::PATH_ELEMENT_SOURCES . ".$elementType");
}
/**
* Returns the source config for a given native source key.
*
* @param string $elementType
* @phpstan-param class-string<ElementInterface> $elementType
* @param string $sourceKey
* @return array|null
*/
private function _sourceConfig(string $elementType, string $sourceKey): ?array
{
$sourceConfigs = $this->_sourceConfigs($elementType);
if (empty($sourceConfigs)) {
return null;
}
return ArrayHelper::firstWhere($sourceConfigs, fn($s) => $s['type'] !== self::TYPE_HEADING && $s['key'] === $sourceKey);
}
}