Skip to content
This repository was archived by the owner on Apr 20, 2022. It is now read-only.

Commit a7259db

Browse files
committed
refactor default settings and implement allowed settings
1 parent 7e0224d commit a7259db

File tree

2 files changed

+55
-13
lines changed

2 files changed

+55
-13
lines changed

README.md

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,37 @@ $user->settings()->forget('some.setting');
7777
```
7878

7979
##### 6.) Set the default settings for a new model.
80+
81+
If you define `$defaultSettings` as an array property on your model, we will use its value as the default settings for
82+
any new models that are created *without* settings.
83+
84+
_User.php_
85+
```
86+
use Cklmercer\ModelSettings\HasSettings;
87+
use Illuminate\Foundation\Auth\User as Authenticatable;
88+
89+
class User extends Authenticatable
90+
{
91+
use HasSettings;
92+
93+
/**
94+
* The model's default settings.
95+
*
96+
* @var array
97+
*/
98+
protected $defaultSettings = [
99+
'homepage' => '/profile'
100+
];
101+
102+
// truncated for brevity..
103+
}
104+
```
105+
106+
##### 7.) Specify the settings that are allowed.
107+
108+
If you define `$allowedSettings` as an array property then only settings which match a value within
109+
the `$allowedSettings` array will be saved on the model.
110+
80111
_User.php_
81112
```
82113
use Cklmercer\ModelSettings\HasSettings;
@@ -87,18 +118,11 @@ class User extends Authenticatable
87118
use HasSettings;
88119
89120
/**
90-
* Set the model's default settings.
91-
*
92-
* @return void
121+
* The model's allowed settings.
122+
*
123+
* @var array
93124
*/
94-
protected function setDefaultSettings()
95-
{
96-
$this->settings = [
97-
'some' => [
98-
'setting' => true
99-
]
100-
];
101-
}
125+
protected $allowedSettings = ['homepage'];
102126
103127
// truncated for brevity..
104128
}

src/HasSettings.php

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,28 @@ trait HasSettings
1212
public static function bootHasSettings()
1313
{
1414
self::creating(function ($model) {
15-
if (method_exists($model, 'setDefaultSettings')) {
16-
$model->setDefaultSettings();
15+
if ( ! $model->settings) {
16+
$model->settings = $model->getDefaultSettings();
1717
}
1818
});
19+
20+
self::saving(function ($model) {
21+
if (property_exists($model, 'allowedSettings') && is_array($model->allowedSettings)) {
22+
$model->settings = array_only($model->settings, $model->allowedSettings);
23+
}
24+
});
25+
}
26+
27+
/**
28+
* Get the model's default settings.
29+
*
30+
* @return array
31+
*/
32+
public function getDefaultSettings()
33+
{
34+
return (isset($this->defaultSettings) && is_array($this->defaultSettings))
35+
? $this->defaultSettings
36+
: [];
1937
}
2038

2139
/**

0 commit comments

Comments
 (0)