Completed
Pull Request — master (#11)
by Laurens
02:56 queued 01:11
created

ProductBuilder::buildFromArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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 8
    public function __construct(
20
        CategoryBuilderInterface $categoryBuilder,
21
        ImageBuilderInterface $imageBuilder,
22
        VariantBuilderInterface $variantBuilder
23
    ) {
24 8
        $this->categoryBuilder = $categoryBuilder;
25 8
        $this->imageBuilder = $imageBuilder;
26 8
        $this->variantBuilder = $variantBuilder;
27 8
    }
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 $purchase) {
36 3
            $products[] = $this->build($purchase);
37
        }
38
39 3
        return $products;
40
    }
41
42 3
    public function buildFromArray(array $data): ProductCollection
43
    {
44 3
        $productCollection = new ProductCollection();
45
46 3
        foreach ($data as $product) {
47 3
            $productCollection->add($this->build($product));
48
        }
49
50 3
        return $productCollection;
51
    }
52
53 6
    private function build(array $data): Product
54
    {
55 6
        return Product::create(
56 6
            Uuid::fromString($data['uuid']),
57 6
            $this->categoryBuilder->buildFromArray($data['categories']),
58 6
            $data['name'],
59 6
            $data['description'],
60 6
            $this->imageBuilder->buildFromArray($data['imageLookupKeys']),
61 6
            $this->variantBuilder->buildFromArray($data['variants']),
62 6
            $data['externalReference'],
63 6
            $data['etag'],
64 6
            new DateTime($data['updated']),
65 6
            Uuid::fromString($data['updatedBy']),
66 6
            new DateTime($data['created']),
67 6
            (float) $data['vatPercentage']
68
        );
69
    }
70
}
71