Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
16 / 16 |
|
100.00% |
8 / 8 |
CRAP | |
100.00% |
1 / 1 |
| Entity | |
100.00% |
16 / 16 |
|
100.00% |
8 / 8 |
12 | |
100.00% |
1 / 1 |
| isNew | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| setNew | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| takeSnapshot | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| getDirtyFields | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |||
| isDirty | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| clearSnapshot | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| beforeSaveEvent | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| afterSaveEvent | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Dynart\Micro\Entities; |
| 4 | |
| 5 | abstract class Entity { |
| 6 | |
| 7 | const EVENT_BEFORE_SAVE = 'before_save'; |
| 8 | const EVENT_AFTER_SAVE = 'after_save'; |
| 9 | |
| 10 | private bool $__isNew = true; |
| 11 | private array $__snapshot = []; |
| 12 | private bool $__hasSnapshot = false; |
| 13 | |
| 14 | public function isNew(): bool { |
| 15 | return $this->__isNew; |
| 16 | } |
| 17 | |
| 18 | public function setNew(bool $value): void { |
| 19 | $this->__isNew = $value; |
| 20 | } |
| 21 | |
| 22 | public function takeSnapshot(array $data): void { |
| 23 | $this->__snapshot = $data; |
| 24 | $this->__hasSnapshot = true; |
| 25 | } |
| 26 | |
| 27 | public function getDirtyFields(array $currentData): array { |
| 28 | if (!$this->__hasSnapshot) { |
| 29 | return $currentData; |
| 30 | } |
| 31 | $dirty = []; |
| 32 | foreach ($currentData as $key => $value) { |
| 33 | if (!array_key_exists($key, $this->__snapshot) || $value !== $this->__snapshot[$key]) { |
| 34 | $dirty[$key] = $value; |
| 35 | } |
| 36 | } |
| 37 | return $dirty; |
| 38 | } |
| 39 | |
| 40 | public function isDirty(array $currentData): bool { |
| 41 | return $this->getDirtyFields($currentData) !== []; |
| 42 | } |
| 43 | |
| 44 | public function clearSnapshot(): void { |
| 45 | $this->__snapshot = []; |
| 46 | $this->__hasSnapshot = false; |
| 47 | } |
| 48 | |
| 49 | public function beforeSaveEvent(): string { |
| 50 | return get_class($this).'.'.self::EVENT_BEFORE_SAVE; |
| 51 | } |
| 52 | |
| 53 | public function afterSaveEvent(): string { |
| 54 | return get_class($this).'.'.self::EVENT_AFTER_SAVE; |
| 55 | } |
| 56 | } |