Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
83.33% |
15 / 18 |
|
33.33% |
1 / 3 |
CRAP | |
0.00% |
0 / 1 |
| AddressDeleteService | |
83.33% |
15 / 18 |
|
33.33% |
1 / 3 |
11.56 | |
0.00% |
0 / 1 |
| delete | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
4.03 | |||
| hasChildrenWithItems | |
66.67% |
4 / 6 |
|
0.00% |
0 / 1 |
4.59 | |||
| deleteChildren | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Domain\Address\Services; |
| 4 | |
| 5 | use App\Events\ServiceProcessed; |
| 6 | use App\Models\Address\Address; |
| 7 | use App\Models\User; |
| 8 | use Domain\Address\Exceptions\AddressWithItemException; |
| 9 | use Exception; |
| 10 | |
| 11 | readonly class AddressDeleteService |
| 12 | { |
| 13 | /** |
| 14 | * @param Address $address |
| 15 | * @param User $user |
| 16 | * @return void |
| 17 | * @throws Exception |
| 18 | */ |
| 19 | public function delete(Address $address, User $user): void |
| 20 | { |
| 21 | if ($address->items()->exists()) { |
| 22 | throw new AddressWithItemException(__('This address has related items')); |
| 23 | } |
| 24 | |
| 25 | if ($this->hasChildrenWithItems($address)) { |
| 26 | throw new AddressWithItemException(__('This address has children who have related items')); |
| 27 | } |
| 28 | |
| 29 | $address->delete(); |
| 30 | |
| 31 | if($address->children){ |
| 32 | $this->deleteChildren($address); |
| 33 | } |
| 34 | |
| 35 | ServiceProcessed::dispatch(self::class, $user); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @param $address |
| 40 | * @return bool |
| 41 | */ |
| 42 | protected function hasChildrenWithItems($address): bool |
| 43 | { |
| 44 | foreach ($address->children as $child) { |
| 45 | if ($child->items()->exists()) { |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | if ($this->hasChildrenWithItems($child)) { |
| 50 | return true; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return false; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * @param $address |
| 59 | */ |
| 60 | private function deleteChildren($address) |
| 61 | { |
| 62 | foreach ($address->children as $child) { |
| 63 | $child->delete(); |
| 64 | |
| 65 | if($child->children){ |
| 66 | $this->deleteChildren($child); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | } |