Completed
Pull Request — master (#290)
by
unknown
41:51
created

ProductVariantViewFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 6
dl 0
loc 46
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A create() 0 28 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sylius\SyliusShopApiPlugin\Factory;
6
7
use Sylius\Component\Core\Model\ChannelInterface;
8
use Sylius\Component\Core\Model\ProductVariantInterface;
9
use Sylius\ShopApiPlugin\View\ProductVariantView;
10
11
final class ProductVariantViewFactory implements ProductVariantViewFactoryInterface
12
{
13
    /** @var PriceViewFactoryInterface */
14
    private $priceViewFactory;
15
16
    /** @var string */
17
    private $productVariantViewClass;
18
19
    public function __construct(PriceViewFactoryInterface $priceViewFactory, string $productVariantViewClass)
20
    {
21
        $this->priceViewFactory = $priceViewFactory;
22
        $this->productVariantViewClass = $productVariantViewClass;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function create(ProductVariantInterface $variant, ChannelInterface $channel, string $locale): ProductVariantView
29
    {
30
        /** @var ProductVariantView $variantView */
31
        $variantView = new $this->productVariantViewClass();
32
33
        $channelPricing = $variant->getChannelPricingForChannel($channel);
34
        if (null === $channelPricing) {
35
            throw new ViewCreationException('Variant does not have pricing.');
36
        }
37
38
        $variantView->code = $variant->getCode();
39
        $variantView->name = $variant->getTranslation($locale)->getName();
40
        $variantView->price = $this->priceViewFactory->create(
41
            $channelPricing->getPrice(),
42
            $channel->getBaseCurrency()->getCode()
43
        );
44
45
        foreach ($variant->getOptionValues() as $optionValue) {
46
            $variantView->axis[] = $optionValue->getCode();
47
            $variantView->nameAxis[$optionValue->getCode()] = sprintf(
48
                '%s %s',
49
                $optionValue->getOption()->getTranslation($locale)->getName(),
50
                $optionValue->getTranslation($locale)->getValue()
51
            );
52
        }
53
54
        return $variantView;
55
    }
56
}
57