-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathAddress.php
More file actions
594 lines (510 loc) · 14.8 KB
/
Address.php
File metadata and controls
594 lines (510 loc) · 14.8 KB
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
<?php
declare(strict_types=1);
namespace CraftCms\Cms\Address\Elements;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressInterface;
use CommerceGuys\Addressing\Country\Country;
use CommerceGuys\Addressing\Subdivision\SubdivisionUpdater;
use Craft;
use craft\base\NestedElementInterface;
use craft\base\NestedElementTrait;
use craft\elements\conditions\addresses\AddressCondition;
use CraftCms\Cms\Address\Addresses;
use CraftCms\Cms\Address\Models\Address as AddressModel;
use CraftCms\Cms\Address\Validation\AddressRules;
use CraftCms\Cms\Cms;
use CraftCms\Cms\Database\Table;
use CraftCms\Cms\Element\Actions\Copy;
use CraftCms\Cms\Element\Conditions\Contracts\ElementConditionInterface;
use CraftCms\Cms\Element\Element;
use CraftCms\Cms\Element\Queries\AddressQuery;
use CraftCms\Cms\FieldLayout\FieldLayout;
use CraftCms\Cms\Shared\Concerns\HasNames;
use CraftCms\Cms\Twig\Attributes\AllowedInSandbox;
use CraftCms\Cms\User\Elements\User;
use CraftCms\Cms\Validation\Attributes\Ruleset;
use Deprecated;
use Override;
use yii\base\InvalidConfigException;
use function CraftCms\Cms\t;
#[Ruleset(AddressRules::class)]
class Address extends Element implements AddressInterface, NestedElementInterface
{
use HasNames;
use NestedElementTrait;
/**
* @since 5.0.0
*/
public const string GQL_TYPE_NAME = 'Address';
#[Override]
public static function displayName(): string
{
return t('Address');
}
#[Override]
public static function lowerDisplayName(): string
{
return t('address');
}
#[Override]
public static function pluralDisplayName(): string
{
return t('Addresses');
}
#[Override]
public static function pluralLowerDisplayName(): string
{
return t('addresses');
}
#[Override]
public static function trackChanges(): bool
{
return true;
}
#[Override]
public static function hasTitles(): bool
{
return true;
}
#[Override]
public static function hasStatuses(): bool
{
return false;
}
#[Override]
public static function createCondition(): ElementConditionInterface
{
return Craft::createObject(AddressCondition::class, [self::class]);
}
#[Override]
protected static function defineActions(string $source): array
{
return [
Copy::class,
];
}
#[Override]
protected static function defineTableAttributes(): array
{
return array_merge(parent::defineTableAttributes(), [
'country' => ['label' => t('Country')],
]);
}
#[Override]
protected function attributeHtml(string $attribute): string
{
return match ($attribute) {
'country' => $this->getCountry()->getName(),
default => parent::attributeHtml($attribute),
};
}
#[Override]
protected static function defineSortOptions(): array
{
return [
[
'label' => t('Label'),
'orderBy' => 'title',
'attribute' => 'title',
],
[
'label' => t('Country'),
'orderBy' => 'countryCode',
'attribute' => 'country',
],
[
'label' => t('Date Created'),
'orderBy' => 'dateCreated',
'defaultDir' => 'desc',
],
[
'label' => t('Date Updated'),
'orderBy' => 'dateUpdated',
'defaultDir' => 'desc',
],
[
'label' => t('ID'),
'orderBy' => 'id',
],
];
}
/**
* @return AddressQuery The newly created [[AddressQuery]] instance.
*/
#[Override]
public static function find(): AddressQuery
{
return new AddressQuery;
}
#[Override]
protected static function defineSearchableAttributes(): array
{
return self::addressAttributes();
}
/**
* Returns all attributes
*
* @return string[]
*/
public static function addressAttributes(): array
{
return [
'countryCode',
'administrativeArea',
'locality',
'dependentLocality',
'postalCode',
'sortingCode',
'addressLine1',
'addressLine2',
'addressLine3',
'organization',
'organizationTaxId',
'fullName',
];
}
/**
* Returns an address attribute label.
*/
#[Deprecated(message: 'in 4.3.0. [[\craft\services\Addresses::getFieldLabel()]] should be used instead.')]
public static function addressAttributeLabel(string $attribute, string $countryCode): ?string
{
if (! AddressField::exists($attribute)) {
return null;
}
/** @phpstan-var AddressField::* $attribute */
return app(Addresses::class)->getFieldLabel($attribute, $countryCode);
}
/**
* @var string Two-letter country code
*
* @see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
*/
#[AllowedInSandbox]
public string $countryCode;
/**
* @var string|null Administrative area
*/
#[AllowedInSandbox]
public ?string $administrativeArea = null;
/**
* @var string|null Locality
*/
#[AllowedInSandbox]
public ?string $locality = null;
/**
* @var string|null Dependent locality
*/
#[AllowedInSandbox]
public ?string $dependentLocality = null;
/**
* @var string|null Postal code
*/
#[AllowedInSandbox]
public ?string $postalCode = null;
/**
* @var string|null Sorting code
*/
#[AllowedInSandbox]
public ?string $sortingCode = null;
/**
* @var string|null First line of the address
*/
#[AllowedInSandbox]
public ?string $addressLine1 = null;
/**
* @var string|null Second line of the address
*/
#[AllowedInSandbox]
public ?string $addressLine2 = null;
/**
* @var string|null Third line of the address
*
* @since 5.0.0
*/
#[AllowedInSandbox]
public ?string $addressLine3 = null;
/**
* @var string|null Organization name
*/
#[AllowedInSandbox]
public ?string $organization = null;
/**
* @var string|null Organization tax ID
*/
#[AllowedInSandbox]
public ?string $organizationTaxId = null;
/**
* @var string|null Latitude
*/
#[AllowedInSandbox]
public ?string $latitude = null;
/**
* @var string|null Longitude
*/
#[AllowedInSandbox]
public ?string $longitude = null;
#[Override]
public function init(): void
{
parent::init();
if (! isset($this->countryCode)) {
$this->countryCode = Cms::config()->defaultCountryCode;
}
$this->normalizeNames();
}
#[Override]
public function setAttributes($values, $safeOnly = true): void
{
// Don't even allow setting a blank country code
if (array_key_exists('countryCode', $values) && empty($values['countryCode'])) {
unset($values['countryCode']);
}
if (array_key_exists('firstName', $values) || array_key_exists('lastName', $values)) {
// Unset fullName so NameTrait::prepareNamesForSave() can set it
$this->fullName = null;
} elseif (array_key_exists('fullName', $values)) {
// Unset firstName and lastName so NameTrait::prepareNamesForSave() can set them
$this->firstName = $this->lastName = null;
}
parent::setAttributes($values, $safeOnly);
}
#[Override]
public function getAttributeLabel($attribute): string
{
if (AddressField::exists($attribute)) {
/** @phpstan-var AddressField::* $attribute */
return app(Addresses::class)->getFieldLabel($attribute, $this->countryCode);
}
return match ($attribute) {
'title' => t('Label'),
'organizationTaxId' => t('Organization Tax ID'),
'fullName' => t('Full Name'),
'firstName' => t('First Name'),
'lastName' => t('Last Name'),
'latitude' => t('Latitude'),
'longitude' => t('Longitude'),
default => parent::getAttributeLabel($attribute),
};
}
/**
* Returns whether the address belongs to the currently logged-in user.
*
* @since 4.5.13
*/
public function getBelongsToCurrentUser(): bool
{
$owner = $this->getOwner();
return $owner instanceof User && $owner->getIsCurrent();
}
#[AllowedInSandbox]
public function getCountryCode(): string
{
return $this->countryCode;
}
/**
* Returns a [[Country]] object representing the address’ country.
*
* @since 5.3.0
*/
#[AllowedInSandbox]
public function getCountry(): Country
{
return app(Addresses::class)->getCountryRepository()->get($this->countryCode, app()->getLocale());
}
#[AllowedInSandbox]
public function getAdministrativeArea(): ?string
{
return $this->administrativeArea;
}
#[AllowedInSandbox]
public function getLocality(): ?string
{
return $this->locality;
}
#[AllowedInSandbox]
public function getDependentLocality(): ?string
{
return $this->dependentLocality;
}
#[AllowedInSandbox]
public function getPostalCode(): ?string
{
return $this->postalCode;
}
#[AllowedInSandbox]
public function getSortingCode(): ?string
{
return $this->sortingCode;
}
#[AllowedInSandbox]
public function getAddressLine1(): ?string
{
return $this->addressLine1;
}
#[AllowedInSandbox]
public function getAddressLine2(): ?string
{
return $this->addressLine2;
}
#[AllowedInSandbox]
public function getAddressLine3(): ?string
{
return $this->addressLine3;
}
#[AllowedInSandbox]
public function getOrganization(): ?string
{
return $this->organization;
}
#[AllowedInSandbox]
public function getGivenName(): ?string
{
return $this->firstName;
}
#[AllowedInSandbox]
public function getAdditionalName(): ?string
{
return null;
}
#[AllowedInSandbox]
public function getFamilyName(): ?string
{
return $this->lastName;
}
#[AllowedInSandbox]
public function getLocale(): string
{
return app()->getLocale();
}
/**
* @since 3.3.0
*/
#[Override]
public function getGqlTypeName(): string
{
return self::GQL_TYPE_NAME;
}
/**
* Returns whether the element's `title` attribute should be validated
*/
#[Override]
public function shouldValidateTitle(): bool
{
$titleField = $this->getFieldLayout()->getField('title');
return $titleField->required && $titleField->showInForm($this);
}
#[Override]
public function beforeValidate(): bool
{
$usedFields = array_unique([
...app(Addresses::class)->getUsedFields($this->countryCode),
'fullName',
'latLong',
'organizationTaxId',
'organization',
'countryCode',
]);
$nullFields = array_filter(
array_diff(self::addressAttributes(), $usedFields),
fn (string $attribute) => ! in_array($attribute, ['givenName', 'familyName', 'additionalName']),
);
foreach ($nullFields as $field) {
$this->$field = null;
}
return parent::beforeValidate();
}
#[Override]
public function getUiLabel(): string
{
return $this->title ?? '';
}
#[Override]
public function getChipLabelHtml(): string
{
$html = (string) parent::getChipLabelHtml();
if ($html !== '') {
return $html;
}
return t('Untitled {type}', [
'type' => self::lowerDisplayName(),
]);
}
#[Override]
protected function cacheTags(): array
{
$tags = [];
if (isset($this->fieldId)) {
$tags[] = "field:$this->fieldId";
}
return $tags;
}
#[Override]
public function beforeSave(bool $isNew): bool
{
// commerceguys/addressing 2.0.x - remap changed subdivision IDs
// update the subdivision ID to its ISO code where available
if (isset($this->countryCode)) {
if (isset($this->administrativeArea)) {
$this->administrativeArea = SubdivisionUpdater::updateValue(
$this->countryCode,
$this->administrativeArea,
);
}
// Andorra is the only country with remapped localities.
if ($this->countryCode == 'AD' && isset($this->locality)) {
$this->locality = SubdivisionUpdater::updateValue(
$this->countryCode,
$this->locality,
);
}
}
return parent::beforeSave($isNew);
}
/**
* @throws InvalidConfigException
*/
#[Override]
public function afterSave(bool $isNew): void
{
if (! $isNew) {
$model = AddressModel::find($this->id);
if (! $model) {
throw new InvalidConfigException("Invalid address ID: $this->id");
}
} else {
$model = new AddressModel;
$model->id = $this->id;
}
$this->prepareNamesForSave();
$model->fieldId = $this->fieldId;
$model->primaryOwnerId = $this->getPrimaryOwnerId();
$model->countryCode = $this->countryCode;
$model->administrativeArea = $this->administrativeArea;
$model->locality = $this->locality;
$model->dependentLocality = $this->dependentLocality;
$model->postalCode = $this->postalCode;
$model->sortingCode = $this->sortingCode;
$model->addressLine1 = $this->addressLine1;
$model->addressLine2 = $this->addressLine2;
$model->addressLine3 = $this->addressLine3;
$model->organization = $this->organization;
$model->organizationTaxId = $this->organizationTaxId;
$model->fullName = $this->fullName;
$model->firstName = $this->firstName;
$model->lastName = $this->lastName;
$model->latitude = $this->latitude;
$model->longitude = $this->longitude;
// Capture the dirty attributes from the record
$dirtyAttributes = array_keys($model->getDirty());
$model->save();
$this->setDirtyAttributes($dirtyAttributes);
$this->saveOwnership($isNew, Table::ADDRESSES);
parent::afterSave($isNew);
}
#[Override]
public function getFieldLayout(): FieldLayout
{
return app(Addresses::class)->getFieldLayout();
}
}