Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
ItemStoreService
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 2
5.39
0.00% covered (danger)
0.00%
0 / 1
 store
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 linkItem
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
1<?php
2
3namespace Domain\Item\Services;
4
5use Throwable;
6use Illuminate\Support\Facades\DB;
7
8use App\Events\ServiceProcessed;
9
10use App\Models\Item\Item;
11use App\Models\Product\Product;
12use App\Models\Storage\Storage;
13use App\Models\User;
14
15use Domain\Integration\Services\IntegrationStoreService;
16use Domain\Item\DTOs\ItemDTO;
17use Domain\Item\DTOs\ItemWarehouseDTO;
18use Domain\Item\Interfaces\HasItemsInterface;
19use Domain\Item\DTOs\ItemProductDTO;
20
21readonly 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}