Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| HasHiddenAttributes | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
6 | |
100.00% |
1 / 1 |
| initializeHasHiddenAttributes | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| setupHidden | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace DevToolbelt\LaravelEloquentPlus\Concerns; |
| 6 | |
| 7 | /** |
| 8 | * Trait for automatic hidden attributes setup. |
| 9 | * |
| 10 | * Automatically hides soft delete columns (deleted_at and deleted_by) |
| 11 | * from array/JSON serialization output. |
| 12 | * |
| 13 | * @package DevToolbelt\LaravelEloquentPlus\Concerns |
| 14 | */ |
| 15 | trait HasHiddenAttributes |
| 16 | { |
| 17 | /** |
| 18 | * Initialize the HasHiddenAttributes trait. |
| 19 | * |
| 20 | * @return void |
| 21 | */ |
| 22 | protected function initializeHasHiddenAttributes(): void |
| 23 | { |
| 24 | $this->setupHidden(); |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Set up default hidden attributes for serialization. |
| 29 | * |
| 30 | * Automatically hides soft delete columns (deleted_at and deleted_by) |
| 31 | * from array/JSON output. Custom hidden attributes defined in the model |
| 32 | * are preserved and merged with these defaults. |
| 33 | * |
| 34 | * @return void |
| 35 | */ |
| 36 | private function setupHidden(): void |
| 37 | { |
| 38 | $defaultHidden = []; |
| 39 | |
| 40 | if ($this->hasAttribute(static::DELETED_AT)) { |
| 41 | $defaultHidden[] = static::DELETED_AT; |
| 42 | } |
| 43 | |
| 44 | if ($this->hasAttribute(static::DELETED_BY)) { |
| 45 | $defaultHidden[] = static::DELETED_BY; |
| 46 | } |
| 47 | |
| 48 | if ($this->usesExternalId()) { |
| 49 | $defaultHidden[] = $this->primaryKey; |
| 50 | |
| 51 | if ($this->hasAttribute($this->getExternalIdColumn())) { |
| 52 | $defaultHidden[] = $this->getExternalIdColumn(); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | $this->hidden = array_unique([...$defaultHidden, ...$this->hidden]); |
| 57 | } |
| 58 | } |