Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
75.00% |
12 / 16 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
| ItemStoreService | |
75.00% |
12 / 16 |
|
0.00% |
0 / 2 |
5.39 | |
0.00% |
0 / 1 |
| store | |
75.00% |
9 / 12 |
|
0.00% |
0 / 1 |
2.06 | |||
| linkItem | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
3.14 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Domain\Item\Services; |
| 4 | |
| 5 | use Throwable; |
| 6 | use Illuminate\Support\Facades\DB; |
| 7 | |
| 8 | use App\Events\ServiceProcessed; |
| 9 | |
| 10 | use App\Models\Item\Item; |
| 11 | use App\Models\Product\Product; |
| 12 | use App\Models\Storage\Storage; |
| 13 | use App\Models\User; |
| 14 | |
| 15 | use Domain\Integration\Services\IntegrationStoreService; |
| 16 | use Domain\Item\DTOs\ItemDTO; |
| 17 | use Domain\Item\DTOs\ItemWarehouseDTO; |
| 18 | use Domain\Item\Interfaces\HasItemsInterface; |
| 19 | use Domain\Item\DTOs\ItemProductDTO; |
| 20 | |
| 21 | readonly class ItemStoreService |
| 22 | { |
| 23 | /** |
| 24 | * @param ItemDTO|ItemWarehouseDTO|ItemProductDTO $itemsDTO |
| 25 | * @param HasItemsInterface $hasItems |
| 26 | * @param User $user |
| 27 | * @return Item |
| 28 | * @throws Throwable |
| 29 | */ |
| 30 | public function store(ItemDTO|ItemWarehouseDTO|ItemProductDTO $itemsDTO, HasItemsInterface $hasItems, User $user): Item |
| 31 | { |
| 32 | try { |
| 33 | DB::beginTransaction(); |
| 34 | |
| 35 | $item = new Item(); |
| 36 | $item->setAttribute('amount', $itemsDTO->amount); |
| 37 | $this->linkItem($itemsDTO, $item); |
| 38 | $hasItems->items()->save($item); |
| 39 | |
| 40 | (new IntegrationStoreService())->store($itemsDTO->itemIntegrationDTO, $item, $user); |
| 41 | |
| 42 | DB::commit(); |
| 43 | } catch (Throwable $throwable) { |
| 44 | DB::rollBack(); |
| 45 | throw $throwable; |
| 46 | } |
| 47 | |
| 48 | ServiceProcessed::dispatch(self::class, $user); |
| 49 | return $item; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * @param ItemDTO|ItemWarehouseDTO|ItemProductDTO $itemsDTO |
| 54 | * @param Item $item |
| 55 | * @return void |
| 56 | */ |
| 57 | private function linkItem(ItemDTO|ItemWarehouseDTO|ItemProductDTO $itemsDTO, Item $item): void |
| 58 | { |
| 59 | if ($itemsDTO->target instanceof Product) { |
| 60 | $item->product()->associate($itemsDTO->target); |
| 61 | } |
| 62 | |
| 63 | if ($itemsDTO->target instanceof Storage) { |
| 64 | $item->storage()->associate($itemsDTO->target); |
| 65 | } |
| 66 | } |
| 67 | } |