Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
87.50% |
21 / 24 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| AddressReplicateService | |
87.50% |
21 / 24 |
|
50.00% |
1 / 2 |
3.02 | |
0.00% |
0 / 1 |
| clone | |
82.35% |
14 / 17 |
|
0.00% |
0 / 1 |
2.02 | |||
| cloneChildren | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
| 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\DTOs\AddressReplicateDTO; |
| 9 | use Domain\Transferable\Services\TransferableStoreService; |
| 10 | use Exception; |
| 11 | use Illuminate\Support\Facades\DB; |
| 12 | |
| 13 | readonly class AddressReplicateService |
| 14 | { |
| 15 | /** |
| 16 | * @param AddressReplicateDTO $addressReplicateDTO |
| 17 | * @param Address $address |
| 18 | * @param User $user |
| 19 | * @return Address |
| 20 | * @throws Exception |
| 21 | */ |
| 22 | public function clone(AddressReplicateDTO $addressReplicateDTO, Address $address, User $user): Address |
| 23 | { |
| 24 | |
| 25 | try { |
| 26 | $newOrder = Address::query() |
| 27 | ->where('parent_id', $address->parent?->getKey()) |
| 28 | ->withTrashed() |
| 29 | ->max('order') + 1; |
| 30 | |
| 31 | DB::beginTransaction(); |
| 32 | $newAddress = $address->replicate(); |
| 33 | $newAddress->fill($addressReplicateDTO->toArray()); |
| 34 | $newAddress->setAttribute('order', $newOrder); |
| 35 | $newAddress->save(); |
| 36 | |
| 37 | (new TransferableStoreService())->store($newAddress); |
| 38 | |
| 39 | $this->cloneChildren($address, $newAddress); |
| 40 | |
| 41 | DB::commit(); |
| 42 | } catch (Exception $exception) { |
| 43 | DB::rollBack(); |
| 44 | throw $exception; |
| 45 | } |
| 46 | |
| 47 | ServiceProcessed::dispatch(self::class, $user); |
| 48 | return $newAddress; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * @param Address $address |
| 53 | * @param Address $newAddress |
| 54 | * @return void |
| 55 | */ |
| 56 | public function cloneChildren(Address $address, Address $newAddress): void |
| 57 | { |
| 58 | $address->children->each(function (Address $children) use ($newAddress) { |
| 59 | $newChildren = $children->replicate(); |
| 60 | $newChildren->parent()->associate($newAddress); |
| 61 | $newChildren->save(); |
| 62 | (new TransferableStoreService())->store($newChildren); |
| 63 | |
| 64 | $this->cloneChildren($children, $newChildren); |
| 65 | }); |
| 66 | |
| 67 | } |
| 68 | } |