Completed
Pull Request — master (#262)
by Gorka
02:43
created

resolveSelectAttribute()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sylius\ShopApiPlugin\Factory;
6
7
use Sylius\Component\Product\Model\ProductAttributeTranslationInterface;
8
use Sylius\Component\Product\Model\ProductAttributeValueInterface;
9
use Sylius\ShopApiPlugin\View\ProductAttributeValueView;
10
11
final class ProductAttributeValueViewFactory implements ProductAttributeValueViewFactoryInterface
12
{
13
    /** @var string */
14
    private $productAttributeValueViewClass;
15
16
    public function __construct(string $productAttributeValueViewClass)
17
    {
18
        $this->productAttributeValueViewClass = $productAttributeValueViewClass;
19
    }
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function create(ProductAttributeValueInterface $productAttributeValue, string $locale): ProductAttributeValueView
25
    {
26
        /** @var ProductAttributeValueView $productAttributeValueView */
27
        $productAttributeValueView = new $this->productAttributeValueViewClass();
28
29
        $productAttributeValueView->code = $productAttributeValue->getCode();
30
31
        if ($productAttributeValue->getType() === 'select') {
32
            $productAttributeValueView->value = $this->resolveSelectAttribute($productAttributeValue);
33
        } else {
34
            $productAttributeValueView->value = $productAttributeValue->getValue();
35
        }
36
37
        $productAttribute = $productAttributeValue->getAttribute();
38
39
        /** @var ProductAttributeTranslationInterface $productAttributeTranslation */
40
        $productAttributeTranslation = $productAttribute->getTranslation($locale);
41
        $productAttributeValueView->name = $productAttributeTranslation->getName();
42
43
        return $productAttributeValueView;
44
    }
45
46
    private function resolveSelectAttribute(ProductAttributeValueInterface $productAttributeValue)
47
    {
48
        $configuration = $productAttributeValue->getAttribute()->getConfiguration();
49
50
        if (!isset($configuration['choices'])
51
            || count($configuration['choices']) === 0
52
            || count($productAttributeValue->getValue()) === 0
53
            || !isset($configuration['choices'][$productAttributeValue->getValue()[0]])
54
        ) {
55
            return null;
56
        }
57
58
        return $configuration['choices'][$productAttributeValue->getValue()[0]];
59
    }
60
}
61