1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace BRKFun\NotificationOptions\Traits; |
5
|
|
|
|
6
|
|
|
use BRKFun\NotificationOptions\Models\NotificationOption; |
7
|
|
|
|
8
|
|
|
trait HasNotificationOptions |
9
|
|
|
{ |
10
|
|
|
public $token; |
11
|
|
|
|
12
|
|
|
public function setToken() |
13
|
|
|
{ |
14
|
|
|
$this->token = tokenSetter(); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function initializeHasNotificationOptions() |
18
|
|
|
{ |
19
|
|
|
$this->setToken(); |
20
|
|
|
$this->with[] = 'notificationOptions'; |
|
|
|
|
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function saveNotificationOptions($key, $value) |
24
|
|
|
{ |
25
|
|
|
$this |
26
|
|
|
->notificationOptions() |
27
|
|
|
->updateOrCreate( |
28
|
|
|
[ |
29
|
|
|
'key' => $key, |
30
|
|
|
], |
31
|
|
|
[ |
32
|
|
|
'value' => $value, |
33
|
|
|
'token' => $this->token, |
34
|
|
|
] |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function setNotificationOption($key) |
39
|
|
|
{ |
40
|
|
|
$this |
41
|
|
|
->notificationOptions() |
42
|
|
|
->create( |
43
|
|
|
[ |
44
|
|
|
'key' => $key, |
45
|
|
|
'value' => config('notification-option.defaultValue', 1), |
46
|
|
|
'token' => $this->token, |
47
|
|
|
] |
48
|
|
|
); |
49
|
|
|
$this->load('notificationOptions'); |
|
|
|
|
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function notificationOptions() |
53
|
|
|
{ |
54
|
|
|
return $this->morphMany(config('notification-option.model', NotificationOption::class), 'notifiable'); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function __get($key) |
58
|
|
|
{ |
59
|
|
|
if (substr($key, 0, 5) === 'wants') { |
60
|
|
|
$wantWhat = lcfirst(substr($key, 5)); |
61
|
|
|
$data = $this->notificationOptions->where('key', $wantWhat)->first(); |
|
|
|
|
62
|
|
|
if ($data) { |
63
|
|
|
return $data->value; |
64
|
|
|
} |
65
|
|
|
$this->setNotificationOption($wantWhat); |
66
|
|
|
return $this->notificationOptions->where('key', $wantWhat)->first()->value; |
|
|
|
|
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return parent::__get($key); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function __set($name, $value) |
73
|
|
|
{ |
74
|
|
|
if (substr($name, 0, 5) === 'wants') { |
75
|
|
|
$setName = lcfirst(substr($name, 5)); |
76
|
|
|
$this->saveNotificationOptions($setName, $value); |
77
|
|
|
unset($this->$name); |
78
|
|
|
return $this; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return parent::__set($name, $value); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
Since your code implements the magic getter
_get
, this function will be called for any read access on an undefined variable. You can add the@property
annotation to your class or interface to document the existence of this variable.If the property has read access only, you can use the @property-read annotation instead.
Of course, you may also just have mistyped another name, in which case you should fix the error.
See also the PhpDoc documentation for @property.