signifly /
laravel-manageable
| 1 | <?php |
||||||
| 2 | |||||||
| 3 | namespace Signifly\Manageable; |
||||||
| 4 | |||||||
| 5 | use Illuminate\Database\Eloquent\Model; |
||||||
| 6 | use Illuminate\Database\Eloquent\Relations\BelongsTo; |
||||||
| 7 | use Illuminate\Support\Facades\Auth; |
||||||
| 8 | |||||||
| 9 | trait Manageable |
||||||
| 10 | { |
||||||
| 11 | public static function bootManageable(): void |
||||||
| 12 | { |
||||||
| 13 | static::creating(function (Model $model) { |
||||||
| 14 | $model->setManageable('created_by', 'creator'); |
||||||
| 15 | }); |
||||||
| 16 | |||||||
| 17 | static::updating(function (Model $model) { |
||||||
| 18 | $model->setManageable('updated_by', 'editor'); |
||||||
| 19 | }); |
||||||
| 20 | } |
||||||
| 21 | |||||||
| 22 | public function creator(): BelongsTo |
||||||
| 23 | { |
||||||
| 24 | return $this->belongsTo($this->getManageableUsersModel(), 'created_by'); |
||||||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||||||
| 25 | } |
||||||
| 26 | |||||||
| 27 | public function editor(): BelongsTo |
||||||
| 28 | { |
||||||
| 29 | return $this->belongsTo($this->getManageableUsersModel(), 'updated_by'); |
||||||
| 30 | } |
||||||
| 31 | |||||||
| 32 | public function hasCreator(): bool |
||||||
| 33 | { |
||||||
| 34 | return ! is_null($this->created_by); |
||||||
| 35 | } |
||||||
| 36 | |||||||
| 37 | public function hasEditor(): bool |
||||||
| 38 | { |
||||||
| 39 | return ! is_null($this->updated_by); |
||||||
| 40 | } |
||||||
| 41 | |||||||
| 42 | protected function setManageable(string $type, string $relation): void |
||||||
| 43 | { |
||||||
| 44 | $guard = $this->getManageableGuard(); |
||||||
| 45 | |||||||
| 46 | if ($guard->check()) { |
||||||
| 47 | $this->{$type} = $guard->id(); |
||||||
| 48 | $this->setRelation($relation, $guard->user()); |
||||||
|
0 ignored issues
–
show
It seems like
setRelation() must be provided by classes using this trait. How about adding it as abstract method to this trait?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
Loading history...
|
|||||||
| 49 | } |
||||||
| 50 | } |
||||||
| 51 | |||||||
| 52 | protected function getManageableUsersModel() |
||||||
| 53 | { |
||||||
| 54 | return method_exists($this, 'manageableUsersModel') |
||||||
| 55 | ? $this->manageableUsersModel() |
||||||
| 56 | : ($this->manageableUsersModel ?? config('auth.providers.users.model')); |
||||||
| 57 | } |
||||||
| 58 | |||||||
| 59 | protected function getManageableGuard() |
||||||
| 60 | { |
||||||
| 61 | $manageableGuardName = method_exists($this, 'manageableGuardName') |
||||||
| 62 | ? $this->manageableGuardName() |
||||||
| 63 | : ($this->manageableGuardName ?? config('auth.defaults.guard')); |
||||||
| 64 | |||||||
| 65 | return Auth::guard($manageableGuardName); |
||||||
| 66 | } |
||||||
| 67 | } |
||||||
| 68 |