-
Notifications
You must be signed in to change notification settings - Fork 170
/
StoreLocationBehavior.php
61 lines (53 loc) · 1.38 KB
/
StoreLocationBehavior.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
<?php
namespace craft\commerce\behaviors;
use craft\commerce\records\Store;
use craft\elements\Address;
use craft\events\AuthorizationCheckEvent;
use craft\events\ModelEvent;
use RuntimeException;
use yii\base\Behavior;
class StoreLocationBehavior extends Behavior
{
/** @var Address */
public $owner;
/**
* @inheritdoc
*/
public function attach($owner)
{
if (!$owner instanceof Address) {
throw new RuntimeException('StoreLocationBehavior can only be attached to an Address element');
}
parent::attach($owner);
}
/**
* @inheritdoc
*/
public function events(): array
{
return [
Address::EVENT_AFTER_SAVE => 'saveStoreLocation',
Address::EVENT_AUTHORIZE_VIEW => 'authorize',
];
}
/**
* @param AuthorizationCheckEvent $event
* @return void
*/
public function authorize(AuthorizationCheckEvent $event)
{
$event->authorized = true;
}
/**
* @param ModelEvent $event
* @return void
*/
public function saveStoreLocation(ModelEvent $event): void
{
$address = $event->sender;
/** @var Store $store */
$store = Store::find()->one(); // we only have one store right now, and we assume it is the first one
$store->locationAddressId = $address->id;
$store->save();
}
}