Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
65.38% covered (warning)
65.38%
17 / 26
60.00% covered (warning)
60.00%
3 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ItemsDTO
65.38% covered (warning)
65.38%
17 / 26
60.00% covered (warning)
60.00%
3 / 5
9.03
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 toArray
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 fromRequest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 populateStorages
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
2.98
 populateProducts
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace Domain\Item\DTOs;
4
5use App\Models\Product\Product;
6use App\Models\Storage\Storage;
7use Domain\Shared\Interfaces\DataTransferObjectInterface;
8use Illuminate\Foundation\Http\FormRequest;
9
10readonly final class ItemsDTO implements DataTransferObjectInterface
11{
12    /** @var ItemDTO[] */
13    public array $storages, $products;
14
15    public function __construct(array $args)
16    {
17        $this->products = $args['products'] ?? [];
18        $this->storages = $args['storages'] ?? [];
19    }
20
21    public function toArray(): array
22    {
23        return [
24            'storages' => $this->storages,
25            'products' => $this->products,
26        ];
27    }
28
29    public static function fromRequest(FormRequest $request): ItemsDTO
30    {
31        return new self([
32            'storages' => self::populateStorages($request->validated('storages') ?? []),
33            'products' => self::populateProducts($request->validated('products') ?? []),
34        ]);
35    }
36
37    /**
38     * @param array $args
39     * @return array
40     */
41    private static function populateStorages(array $args): array
42    {
43        $storages = [];
44        foreach ($args as $storage) {
45            $storages[] = new ItemDTO([
46                'target' => Storage::find($storage['id']),
47                'amount' => $storage['amount'],
48                'production_order' => $storage['production_order'],
49            ]);
50        }
51        return $storages;
52    }
53
54    /**
55     * @param array $args
56     * @return array
57     */
58    private static function populateProducts(array $args): array
59    {
60        $products = [];
61        foreach ($args as $product) {
62            $products[] = new ItemDTO([
63                'target' => Product::find($product['id']),
64                'amount' => $product['amount'],
65                'production_order' => $product['production_order'],
66            ]);
67        }
68        return $products;
69    }
70}