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
ItemUpdateService
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 2
6.56
0.00% covered (danger)
0.00%
0 / 1
 update
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
3.14
 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;
6
7use Illuminate\Support\Facades\DB;
8
9use App\Events\ServiceProcessed;
10use App\Models\Item\Item;
11use App\Models\Product\Product;
12use App\Models\Storage\Storage;
13use App\Models\User;
14
15use Domain\Integration\Services\IntegrationUpdateService;
16use Domain\Item\DTOs\ItemDTO;
17use Domain\Item\DTOs\ItemProductDTO;
18
19readonly class ItemUpdateService
20{
21    /**
22     * @param ItemDTO $itemsDTO
23     * @param Item $item
24     * @param User $user
25     * @return Item
26     * @throws Throwable
27     */
28    public function update(ItemDTO|ItemProductDTO $itemsDTO, Item $item, User $user): Item
29    {
30        try {
31            DB::beginTransaction();
32
33            $item->fill($itemsDTO->toArray());
34            $this->linkItem($itemsDTO, $item);
35            if ($item->isDirty()) {
36                $item->save();
37            }
38
39            (new IntegrationUpdateService())->update($itemsDTO->itemIntegrationDTO, $item->integration, $user);
40
41            DB::commit();
42        } catch (Throwable $throwable) {
43            DB::rollBack();
44            throw $throwable;
45        }
46
47        ServiceProcessed::dispatch(self::class, $user);
48        return $item;
49    }
50
51    /**
52     * @param ItemDTO $itemsDTO
53     * @param Item $item
54     * @return void
55     */
56    private function linkItem(ItemDTO|ItemProductDTO $itemsDTO, Item $item): void
57    {
58        if ($itemsDTO->target instanceof Product) {
59            $item->product()->associate($itemsDTO->target);
60        }
61
62        if ($itemsDTO->target instanceof Storage) {
63            $item->storage()->associate($itemsDTO->target);
64        }
65    }
66}