| 1 | <?php |
||
| 7 | trait Preferenceable |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * Preferences morph. |
||
| 11 | * |
||
| 12 | * @return Illuminate\Database\Eloquent\Relations\MorphMany |
||
| 13 | */ |
||
| 14 | 1 | public function preferences() |
|
| 15 | { |
||
| 16 | 1 | return $this->morphMany(Preference::class, 'preferenceable'); |
|
|
|
|||
| 17 | } |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Get or set preference value. |
||
| 21 | * |
||
| 22 | * @param mixed $key |
||
| 23 | * @param mixed $value |
||
| 24 | * @param string $type |
||
| 25 | * |
||
| 26 | * @return mixed Value. |
||
| 27 | */ |
||
| 28 | 1 | public function pref($key, $value = null, $type = 'string') |
|
| 29 | { |
||
| 30 | 1 | if (isset($value)) { |
|
| 31 | $this->preferences()->updateOrCreate(['key' => $key], ['value' => $this->cast($value, $type), |
||
| 32 | 'type' => $type, ]); |
||
| 33 | |||
| 34 | return $value; |
||
| 35 | } |
||
| 36 | 1 | $default = Preference::getDefault($this, $key); |
|
| 37 | |||
| 38 | 1 | return($pref = $this->preferences()->forKey($key)->first()) ? $pref->value() : $default->value(); |
|
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Cast value. |
||
| 43 | * |
||
| 44 | * @param mixed $value |
||
| 45 | * @param mixed $type |
||
| 46 | * |
||
| 47 | * @return mixed Value. |
||
| 48 | */ |
||
| 49 | private function cast($value, $type) |
||
| 68 | } |
||
| 69 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.