-
Notifications
You must be signed in to change notification settings - Fork 639
/
Field.php
1278 lines (1131 loc) · 35.9 KB
/
Field.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\base;
use Craft;
use craft\db\Table as DbTable;
use craft\elements\db\ElementQueryInterface;
use craft\enums\AttributeStatus;
use craft\events\DefineFieldHtmlEvent;
use craft\events\DefineFieldKeywordsEvent;
use craft\events\FieldElementEvent;
use craft\events\FieldEvent;
use craft\gql\types\QueryArgument;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\ElementHelper;
use craft\helpers\Html;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\models\GqlSchema;
use craft\records\Field as FieldRecord;
use craft\validators\HandleValidator;
use craft\validators\UniqueValidator;
use DateTime;
use Exception;
use GraphQL\Type\Definition\Type;
use yii\base\Arrayable;
use yii\base\ErrorHandler;
use yii\base\InvalidArgumentException;
use yii\base\NotSupportedException;
use yii\db\ExpressionInterface;
use yii\db\Schema;
/**
* Field is the base class for classes representing fields in terms of objects.
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
abstract class Field extends SavableComponent implements FieldInterface, Iconic, Actionable
{
use FieldTrait;
// Events
// -------------------------------------------------------------------------
/**
* @event FieldElementEvent The event that is triggered before the element is saved.
*
* You may set [[\yii\base\ModelEvent::$isValid]] to `false` to prevent the element from getting saved.
*/
public const EVENT_BEFORE_ELEMENT_SAVE = 'beforeElementSave';
/**
* @event FieldElementEvent The event that is triggered after the element is saved.
*/
public const EVENT_AFTER_ELEMENT_SAVE = 'afterElementSave';
/**
* @event FieldElementEvent The event that is triggered after the element is fully saved and propagated to other sites.
* @since 3.2.0
*/
public const EVENT_AFTER_ELEMENT_PROPAGATE = 'afterElementPropagate';
/**
* @event FieldElementEvent The event that is triggered before the element is deleted.
*
* You may set [[\yii\base\ModelEvent::$isValid]] to `false` to prevent the element from getting deleted.
*/
public const EVENT_BEFORE_ELEMENT_DELETE = 'beforeElementDelete';
/**
* @event FieldElementEvent The event that is triggered after the element is deleted.
*/
public const EVENT_AFTER_ELEMENT_DELETE = 'afterElementDelete';
/**
* @event FieldElementEvent The event that is triggered before the element is restored.
*
* You may set [[\yii\base\ModelEvent::$isValid]] to `false` to prevent the element from getting restored.
*
* @since 3.1.0
*/
public const EVENT_BEFORE_ELEMENT_RESTORE = 'beforeElementRestore';
/**
* @event FieldElementEvent The event that is triggered after the element is restored.
* @since 3.1.0
*/
public const EVENT_AFTER_ELEMENT_RESTORE = 'afterElementRestore';
/**
* @event DefineFieldKeywordsEvent The event that is triggered when defining the field’s search keywords for an
* element.
*
* Note that you _must_ set [[Event::$handled]] to `true` if you want the field to accept your custom
* [[DefineFieldKeywordsEvent::$keywords|$keywords]] value.
*
* ```php
* Event::on(
* craft\fields\Lightswitch::class,
* craft\base\Field::EVENT_DEFINE_KEYWORDS,
* function(craft\events\DefineFieldKeywordsEvent $e
* ) {
* // @var craft\fields\Lightswitch $field
* $field = $e->sender;
*
* if ($field->handle === 'fooOrBar') {
* // Override the keywords depending on whether the lightswitch is enabled or not
* $e->keywords = $e->value ? 'foo' : 'bar';
* $e->handled = true;
* }
* });
* ```
*
* @since 3.5.0
*/
public const EVENT_DEFINE_KEYWORDS = 'defineKeywords';
/**
* @event DefineFieldHtmlEvent The event that is triggered when defining the field’s input HTML.
* @since 3.5.0
*/
public const EVENT_DEFINE_INPUT_HTML = 'defineInputHtml';
/**
* @event FieldEvent The event that is triggered after the field has been merged into another.
* @see afterMergeInto()
* @since 5.3.0
*/
public const EVENT_AFTER_MERGE_INTO = 'afterMergeInto';
/**
* @event FieldEvent The event that is triggered after another field has been merged into this one.
* @see afterMergeFrom()
* @since 5.3.0
*/
public const EVENT_AFTER_MERGE_FROM = 'afterMergeFrom';
// Translation methods
// -------------------------------------------------------------------------
public const TRANSLATION_METHOD_NONE = 'none';
public const TRANSLATION_METHOD_SITE = 'site';
public const TRANSLATION_METHOD_SITE_GROUP = 'siteGroup';
public const TRANSLATION_METHOD_LANGUAGE = 'language';
public const TRANSLATION_METHOD_CUSTOM = 'custom';
/**
* @inheritdoc
*/
public static function get(int|string $id): ?static
{
/** @phpstan-ignore-next-line */
return Craft::$app->getFields()->getFieldById($id);
}
/**
* @inheritdoc
*/
public static function icon(): string
{
return 'i-cursor';
}
/**
* @inheritdoc
*/
public static function isMultiInstance(): bool
{
return static::dbType() !== null;
}
/**
* @inheritdoc
*/
public static function isRequirable(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function supportedTranslationMethods(): array
{
if (static::dbType() === null) {
return [
self::TRANSLATION_METHOD_NONE,
];
}
return [
self::TRANSLATION_METHOD_NONE,
self::TRANSLATION_METHOD_SITE,
self::TRANSLATION_METHOD_SITE_GROUP,
self::TRANSLATION_METHOD_LANGUAGE,
self::TRANSLATION_METHOD_CUSTOM,
];
}
/**
* @inheritdoc
*/
public static function phpType(): string
{
return 'mixed';
}
/**
* @inheritdoc
*/
public static function dbType(): array|string|null
{
return Schema::TYPE_TEXT;
}
/**
* @inheritdoc
*/
public static function queryCondition(
array $instances,
mixed $value,
array &$params,
): array|string|ExpressionInterface|false|null {
$valueSql = static::valueSql($instances);
if ($valueSql === null) {
return false;
}
if (is_array($value) && isset($value['value'])) {
$caseInsensitive = $value['caseInsensitive'] ?? false;
$value = $value['value'];
} else {
$caseInsensitive = false;
}
return Db::parseParam($valueSql, $value, caseInsensitive: $caseInsensitive, columnType: Schema::TYPE_JSON);
}
/**
* Returns a coalescing value SQL expression for the given field instances.
*
* @param static[] $instances
* @param string|null $key The data key to fetch, if this field stores multiple values
* @return string|null
* @since 5.0.0
*/
protected static function valueSql(array $instances, string $key = null): ?string
{
$valuesSql = array_filter(
array_map(fn(self $field) => $field->getValueSql($key), $instances),
fn(?string $valueSql) => $valueSql !== null,
);
if (empty($valuesSql)) {
return null;
}
if (count($valuesSql) === 1) {
return reset($valuesSql);
}
return sprintf('COALESCE(%s)', implode(',', $valuesSql));
}
/**
* @var bool Whether the field handle’s uniqueness should be validated.
* @since 5.0.0
*/
public bool $validateHandleUniqueness = true;
/**
* @var bool|null Whether the field is fresh.
* @see isFresh()
* @see setIsFresh()
*/
private ?bool $_isFresh = null;
/**
* @var array<string,string|false>
* @see getValueSql()
*/
private array $_valueSql;
/**
* Constructor
*/
public function __construct($config = [])
{
// remove unused settings
unset($config['columnPrefix']);
parent::__construct($config);
}
/**
* Use the translated field name as the string representation.
*
* @return string
* @noinspection PhpInconsistentReturnPointsInspection
*/
public function __toString(): string
{
try {
return Craft::t('site', $this->name) ?: static::class;
} catch (Exception $e) {
ErrorHandler::convertExceptionToError($e);
}
}
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
// Validate the translation method
$supportedTranslationMethods = static::supportedTranslationMethods() ?: [self::TRANSLATION_METHOD_NONE];
if (!in_array($this->translationMethod, $supportedTranslationMethods, true)) {
$this->translationMethod = reset($supportedTranslationMethods);
}
if ($this->translationMethod !== self::TRANSLATION_METHOD_CUSTOM) {
$this->translationKeyFormat = null;
}
}
/**
* @inheritdoc
*/
public function attributes(): array
{
$names = parent::attributes();
ArrayHelper::removeValue($names, 'validateHandleUniqueness');
ArrayHelper::removeValue($names, 'layoutElement');
return $names;
}
/**
* @inheritdoc
*/
public function attributeLabels(): array
{
return [
'handle' => Craft::t('app', 'Handle'),
'name' => Craft::t('app', 'Name'),
];
}
/**
* @inheritdoc
*/
protected function defineRules(): array
{
$rules = parent::defineRules();
$rules[] = [['name', 'handle', 'translationMethod'], 'required'];
$rules[] = [
['translationMethod'],
'in',
'range' => [
self::TRANSLATION_METHOD_NONE,
self::TRANSLATION_METHOD_SITE,
self::TRANSLATION_METHOD_SITE_GROUP,
self::TRANSLATION_METHOD_LANGUAGE,
self::TRANSLATION_METHOD_CUSTOM,
],
];
$rules[] = [
['handle'],
HandleValidator::class,
'reservedWords' => [
'ancestors',
'archived',
'attributeLabel',
'attributes',
'awaitingFieldValues',
'behavior',
'behaviors',
'canSetProperties',
'canonical',
'children',
'contentTable',
'dateCreated',
'dateDeleted',
'dateLastMerged',
'dateUpdated',
'descendants',
'draftId',
'duplicateOf',
'enabled',
'enabledForSite',
'error',
'errorSummary',
'errors',
'fieldLayoutId',
'fieldValue',
'fieldValues',
'firstSave',
'hardDelete',
'hasMethods',
'icon',
'id',
'isNewForSite',
'isProvisionalDraft',
'language',
'level',
'lft',
'link',
'localized',
'localized',
'mergingCanonicalChanges',
'name', // global set-specific
'newSiteIds',
'next',
'nextSibling',
'owner',
'parent',
'parents',
'postDate', // entry-specific
'prev',
'prevSibling',
'previewing',
'propagateAll',
'propagating',
'ref',
'relatedToAssets',
'relatedToCategories',
'relatedToEntries',
'relatedToTags',
'relatedToUsers',
'resaving',
'revisionId',
'rgt',
'root',
'scenario',
'searchScore',
'siblings',
'site',
'siteId',
'siteSettingsId',
'slug',
'sortOrder',
'status',
'structureId',
'tempId',
'title',
'trashed',
'uid',
'updatingFromDerivative',
'uri',
'url',
'username', // user-specific
],
];
if ($this->validateHandleUniqueness) {
$rules[] = [
['handle'],
UniqueValidator::class,
'targetClass' => FieldRecord::class,
'targetAttribute' => ['handle', 'context'],
'message' => Craft::t('yii', '{attribute} "{value}" has already been taken.'),
];
}
// Only validate the ID if it’s not a new field
if (!$this->getIsNew()) {
$rules[] = [['id'], 'number', 'integerOnly' => true];
}
if ($this->translationMethod === self::TRANSLATION_METHOD_CUSTOM) {
$rules[] = [['translationKeyFormat'], 'required'];
}
return $rules;
}
/**
* @inheritdoc
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getUiLabel(): string
{
return Craft::t('site', $this->name);
}
/**
* @inheritdoc
*/
public function getHandle(): ?string
{
return $this->handle;
}
/**
* @inheritdoc
*/
public function getIcon(): ?string
{
return static::icon();
}
/**
* @inheritdoc
*/
public function getCpEditUrl(): ?string
{
return $this->id ? UrlHelper::cpUrl("settings/fields/edit/$this->id") : null;
}
/**
* @inheritdoc
*/
public function getActionMenuItems(): array
{
$items = [];
if (
$this->id &&
Craft::$app->getUser()->getIsAdmin() &&
Craft::$app->getConfig()->getGeneral()->allowAdminChanges
) {
$editId = sprintf('action-edit-%s', mt_rand());
$items[] = [
'id' => $editId,
'icon' => 'edit',
'label' => Craft::t('app', 'Edit'),
];
$view = Craft::$app->getView();
$view->registerJsWithVars(fn($id, $params) => <<<JS
$('#' + $id).on('click', () => {
new Craft.CpScreenSlideout('fields/edit-field', {
params: $params,
});
});
JS, [
$view->namespaceInputId($editId),
['fieldId' => $this->id],
]);
}
return $items;
}
/**
* @inheritdoc
*/
public function getOrientation(?ElementInterface $element): string
{
if (!Craft::$app->getIsMultiSite()) {
// Only one site so use its language
$locale = Craft::$app->getSites()->getPrimarySite()->getLocale();
} elseif (!$element || !$this->getIsTranslatable($element)) {
// Not translatable, so use the user’s language
$locale = Craft::$app->getLocale();
} else {
// Use the site’s language
$locale = $element->getSite()->getLocale();
}
return $locale->getOrientation();
}
/**
* @inheritdoc
*/
public function getIsTranslatable(?ElementInterface $element): bool
{
if ($this->translationMethod === self::TRANSLATION_METHOD_CUSTOM) {
return $element === null || $this->getTranslationKey($element) !== '';
}
return $this->translationMethod !== self::TRANSLATION_METHOD_NONE;
}
/**
* @inheritdoc
*/
public function getTranslationDescription(?ElementInterface $element): ?string
{
if (!$this->getIsTranslatable($element)) {
return null;
}
return ElementHelper::translationDescription($this->translationMethod);
}
/**
* @inheritdoc
*/
public function getTranslationKey(ElementInterface $element): string
{
return ElementHelper::translationKey($element, $this->translationMethod, $this->translationKeyFormat);
}
/**
* @inheritdoc
*/
public function getStatus(ElementInterface $element): ?array
{
if ($element->isFieldModified($this->handle)) {
return [
AttributeStatus::Modified,
Craft::t('app', 'This field has been modified.'),
];
}
if ($element->isFieldOutdated($this->handle)) {
return [
AttributeStatus::Outdated,
Craft::t('app', 'This field was updated in the Current revision.'),
];
}
return null;
}
/**
* @inheritdoc
*/
public function getInputId(): string
{
return Html::id($this->handle);
}
/**
* @inheritdoc
*/
public function getLabelId(): string
{
return sprintf('%s-label', $this->getInputId());
}
/**
* @inheritdoc
*/
public function useFieldset(): bool
{
return false;
}
/**
* @inheritdoc
*/
public function normalizeValue(mixed $value, ?ElementInterface $element): mixed
{
return $value;
}
/**
* @inheritdoc
*/
public function normalizeValueFromRequest(mixed $value, ?ElementInterface $element): mixed
{
return $this->normalizeValue($value, $element);
}
/**
* @inheritdoc
*/
public function getInputHtml(mixed $value, ?ElementInterface $element): string
{
$html = $this->inputHtml($value, $element, false);
// Fire a 'defineInputHtml' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_INPUT_HTML)) {
$event = new DefineFieldHtmlEvent([
'value' => $value,
'element' => $element,
'inline' => false,
'html' => $html,
]);
$this->trigger(self::EVENT_DEFINE_INPUT_HTML, $event);
return $event->html;
}
return $html;
}
/**
* @see InlineEditableFieldInterface::getInlineInputHtml()
* @since 5.0.0
*/
public function getInlineInputHtml(mixed $value, ?ElementInterface $element): string
{
$html = $this->inputHtml($value, $element, true);
// Fire a 'defineInputHtml' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_INPUT_HTML)) {
$event = new DefineFieldHtmlEvent([
'value' => $value,
'element' => $element,
'inline' => true,
'html' => $html,
]);
$this->trigger(self::EVENT_DEFINE_INPUT_HTML, $event);
return $event->html;
}
return $html;
}
/**
* Returns the field’s input HTML.
*
* @param mixed $value The field’s value. This will either be the [[normalizeValue()|normalized value]],
* raw POST data (i.e. if there was a validation error), or null
* @param ElementInterface|null $element The element the field is associated with, if there is one
* @param bool $inline Whether this is for an inline edit form.
* @return string The input HTML.
* @see getInputHtml()
* @since 3.5.0
*/
protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inline): string
{
return Html::textarea($this->handle, $value);
}
/**
* @inheritdoc
*/
public function getStaticHtml(mixed $value, ElementInterface $element): string
{
// Just return the input HTML with disabled inputs by default
Craft::$app->getView()->startJsBuffer();
$inputHtml = $this->getInputHtml($value, $element);
$inputHtml = preg_replace('/<(?:input|textarea|select)\s[^>]*/i', '$0 disabled', $inputHtml);
Craft::$app->getView()->clearJsBuffer();
return $inputHtml;
}
/**
* @inheritdoc
*/
public function getElementValidationRules(): array
{
return [];
}
/**
* @inheritdoc
*/
public function isValueEmpty(mixed $value, ElementInterface $element): bool
{
// Default to yii\validators\Validator::isEmpty()'s behavior
return $value === null || $value === [] || $value === '';
}
/**
* @inheritdoc
*/
public function getSearchKeywords(mixed $value, ElementInterface $element): string
{
// Fire a 'defineKeywords' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_KEYWORDS)) {
$event = new DefineFieldKeywordsEvent([
'value' => $value,
'element' => $element,
]);
$this->trigger(self::EVENT_DEFINE_KEYWORDS, $event);
if ($event->handled) {
return $event->keywords;
}
}
return $this->searchKeywords($value, $element);
}
/**
* Returns the search keywords that should be associated with this field.
*
* The keywords can be separated by commas and/or whitespace; it doesn’t really matter. [[\craft\services\Search]]
* will be able to find the individual keywords in whatever string is returned, and normalize them for you.
*
* @param mixed $value The field’s value
* @param ElementInterface $element The element the field is associated with, if there is one
* @return string A string of search keywords.
* @since 3.5.0
*/
protected function searchKeywords(mixed $value, ElementInterface $element): string
{
return StringHelper::toString($value, ' ');
}
/**
* @see PreviewableFieldInterface::getPreviewHtml()
* @since 5.0.0
*/
public function getPreviewHtml(mixed $value, ElementInterface $element): string
{
return ElementHelper::attributeHtml($value);
}
/**
* @see PreviewableFieldInterface::previewPlaceholderHtml()
* @since 5.5.0
*/
public function previewPlaceholderHtml(mixed $value, ?ElementInterface $element): string
{
if (!$this instanceof PreviewableFieldInterface) {
return '';
}
if ($value !== null) {
return $value;
}
if ($element !== null) {
return $element->getFieldValue($this->handle);
}
return $this->getUiLabel();
}
/**
* @see SortableFieldInterface::getSortOption()
* @since 3.2.0
*/
public function getSortOption(): array
{
$dbType = static::dbType();
if ($dbType === null || !isset($this->layoutElement)) {
throw new NotSupportedException('getSortOption() not supported by ' . $this->name);
}
$orderBy = $this->getValueSql();
// for mysql, we have to make sure text column type is cast to char, otherwise it won't be sorted correctly
// see https://github.com/craftcms/cms/issues/15609
$db = Craft::$app->getDb();
if ($db->getIsMysql() && is_string($dbType) && Db::parseColumnType($dbType) === Schema::TYPE_TEXT) {
$orderBy = "CAST($orderBy AS CHAR(255))";
}
// The attribute name should match the table attribute name,
// per ElementSources::getTableAttributesForFieldLayouts()
return [
'label' => Craft::t('site', $this->name),
'orderBy' => $orderBy,
'attribute' => isset($this->layoutElement->handle)
? "fieldInstance:{$this->layoutElement->uid}"
: "field:$this->uid",
];
}
/**
* @see MergeableFieldInterface::canMergeInto()
* @since 5.3.0
*/
public function canMergeInto(FieldInterface $persistingField, ?string &$reason): bool
{
// Go with whether the DB types are compatible by default
return Craft::$app->getFields()->areFieldTypesCompatible(static::class, $persistingField::class);
}
/**
* @see MergeableFieldInterface::canMergeFrom()
* @since 5.3.0
*/
public function canMergeFrom(FieldInterface $outgoingField, ?string &$reason): bool
{
// Go with whether the DB types are compatible by default
return Craft::$app->getFields()->areFieldTypesCompatible(static::class, $outgoingField::class);
}
/**
* @see MergeableFieldInterface::afterMergeInto()
* @since 5.3.0
*/
public function afterMergeInto(FieldInterface $persistingField)
{
// Fire an 'afterMergeInto' event
if ($this->hasEventHandlers(self::EVENT_AFTER_MERGE_INTO)) {
$this->trigger(self::EVENT_AFTER_MERGE_INTO, new FieldEvent(['field' => $persistingField]));
}
}
/**
* @see MergeableFieldInterface::afterMergeFrom()
* @since 5.3.0
*/
public function afterMergeFrom(FieldInterface $outgoingField)
{
if ($this instanceof RelationalFieldInterface) {
Db::update(DbTable::RELATIONS, ['fieldId' => $this->id], ['fieldId' => $outgoingField->id]);
}
// Fire an 'afterMergeFrom' event
if ($this->hasEventHandlers(self::EVENT_AFTER_MERGE_FROM)) {
$this->trigger(self::EVENT_AFTER_MERGE_FROM, new FieldEvent(['field' => $outgoingField]));
}
}
/**
* @inheritdoc
*/
public function serializeValue(mixed $value, ?ElementInterface $element): mixed
{
// If the object explicitly defines its savable value, use that
if ($value instanceof Serializable) {
return $value->serialize();
}
// If it's "arrayable", convert to array
if ($value instanceof Arrayable) {
return $value->toArray();
}
// Only DateTime objects and ISO-8601 strings should automatically be detected as dates
if ($value instanceof DateTime || DateTimeHelper::isIso8601($value)) {
return Db::prepareDateForDb($value);
}
return $value;
}
/**
* @inheritdoc
*/
public function copyValue(ElementInterface $from, ElementInterface $to): void
{
$value = $this->serializeValue($from->getFieldValue($this->handle), $from);
$to->setFieldValue($this->handle, $value);
}
/**
* @inheritdoc
*/
public function getElementConditionRuleType(): array|string|null
{
return null;
}
/**
* @inheritdoc
*/
public function getValueSql(?string $key = null): ?string
{
if (!isset($this->layoutElement)) {
return null;
}
$cacheKey = $key ?? '*';
$this->_valueSql[$cacheKey] ??= $this->_valueSql($key) ?? false;
return $this->_valueSql[$cacheKey] ?: null;
}
private function _valueSql(?string $key): ?string
{
$dbType = static::dbType();
if ($dbType === null) {
return null;
}
if ($key !== null && (!is_array($dbType) || !isset($dbType[$key]))) {
throw new InvalidArgumentException(sprintf('%s doesn’t store values under the key “%s”.', __CLASS__, $key));
}
$db = Craft::$app->getDb();
$qb = $db->getQueryBuilder();
$sql = $qb->jsonExtract('elements_sites.content', [$this->layoutElement->uid]);
if (is_array($dbType)) {
// Get the primary value by default
$key ??= array_key_first($dbType);
$dbType = $dbType[$key];
$sql = sprintf('COALESCE(%s, %s)', $qb->jsonExtract(
'elements_sites.content',
[$this->layoutElement->uid, $key],
), $sql);
}
$castType = null;
if ($db->getIsMysql()) {
// If the field uses an optimized DB type, cast it so its values can be indexed
// (see "Functional Key Parts" on https://dev.mysql.com/doc/refman/8.0/en/create-index.html)
$castType = match (Db::parseColumnType($dbType)) {
Schema::TYPE_CHAR,
Schema::TYPE_STRING,