Completed
Branch add-single-product-endpoint (3e130a)
by Laurens
05:53 queued 02:51
created

ProductBuilder::buildSingleFromJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LauLamanApps\IzettleApi\Client\Product;
6
7
use DateTime;
8
use LauLamanApps\IzettleApi\API\Product\Product;
9
use LauLamanApps\IzettleApi\API\Product\ProductCollection;
10
use LauLamanApps\IzettleApi\Client\Universal\ImageBuilderInterface;
11
use Ramsey\Uuid\Uuid;
12
13
final class ProductBuilder implements ProductBuilderInterface
14
{
15
    private $imageBuilder;
16
    private $categoryBuilder;
17
    private $variantBuilder;
18
19 10
    public function __construct(
20
        CategoryBuilderInterface $categoryBuilder,
21
        ImageBuilderInterface $imageBuilder,
22
        VariantBuilderInterface $variantBuilder
23
    ) {
24 10
        $this->categoryBuilder = $categoryBuilder;
25 10
        $this->imageBuilder = $imageBuilder;
26 10
        $this->variantBuilder = $variantBuilder;
27 10
    }
28
29
    /**
30
     * @return Product[]
31
     */
32 3
    public function buildFromJson(string $json): array
33
    {
34 3
        $products = [];
35 3
        foreach (json_decode($json, true) as $productData) {
36 3
            $products[] = $this->build($productData);
37
        }
38
39 3
        return $products;
40
    }
41
42 2
    public function buildSingleFromJson(string $json): Product
43
    {
44 2
        return $this->build(json_decode($json, true));
45
    }
46
47 3
    public function buildFromArray(array $data): ProductCollection
48
    {
49 3
        $productCollection = new ProductCollection();
50
51 3
        foreach ($data as $product) {
52 3
            $productCollection->add($this->build($product));
53
        }
54
55 3
        return $productCollection;
56
    }
57
58 8
    private function build(array $data): Product
59
    {
60 8
        return Product::create(
61 8
            Uuid::fromString($data['uuid']),
62 8
            $this->categoryBuilder->buildFromArray($data['categories']),
63 8
            $data['name'],
64 8
            $data['description'],
65 8
            $this->imageBuilder->buildFromArray($data['imageLookupKeys']),
66 8
            $this->variantBuilder->buildFromArray($data['variants']),
67 8
            $data['externalReference'],
68 8
            $data['etag'],
69 8
            new DateTime($data['updated']),
70 8
            Uuid::fromString($data['updatedBy']),
71 8
            new DateTime($data['created']),
72 8
            (float) $data['vatPercentage']
73
        );
74
    }
75
}
76