Completed
Pull Request — master (#22)
by Matthias
04:29
created

ProductBundleCreator::addProductsToSlot()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace solutionDrive\SyliusProductBundlesPlugin\Service;
6
7
use solutionDrive\SyliusProductBundlesPlugin\Entity\ProductBundleInterface;
8
use solutionDrive\SyliusProductBundlesPlugin\Entity\ProductBundleSlotInterface;
9
use Sylius\Component\Core\Model\ProductInterface;
10
use Sylius\Component\Resource\Factory\FactoryInterface;
11
12
class ProductBundleCreator
13
{
14
    /** @var FactoryInterface */
15
    private $productBundleFactory;
16
17
    /** @var FactoryInterface */
18
    private $productBundleSlotFactory;
19
20
    /** @var ProductBundleInterface */
21
    private $productBundle;
22
23
    public function __construct(
24
        FactoryInterface $productBundleFactory,
25
        FactoryInterface $productBundleSlotFactory
26
    ) {
27
        $this->productBundleFactory = $productBundleFactory;
28
        $this->productBundleSlotFactory = $productBundleSlotFactory;
29
    }
30
31
    public function createProductBundle(string $productBundleName): self
32
    {
33
        $this->productBundle = $this->productBundleFactory->createNew();
34
        $this->productBundle->setName($productBundleName);
35
36
        return $this;
37
    }
38
39
    public function getProductBundle(): ProductBundleInterface
40
    {
41
        return $this->productBundle;
42
    }
43
44
    public function addSlot(string $slotName, array $options = [], array $products = []): self
45
    {
46
        /** @var ProductBundleSlotInterface $slot */
47
        $slot = $this->productBundleSlotFactory->createNew();
48
        $slot->setName($slotName);
49
        $slot->setBundle($this->productBundle);
50
        $this->applyOptionsToSlot($options, $slot);
51
        $this->addProductsToSlot($products, $slot);
52
53
        $this->productBundle->addSlot($slot);
54
55
        return $this;
56
    }
57
58
    private function applyOptionsToSlot(array $options, ProductBundleSlotInterface $slot): void
59
    {
60
        if (isset($options['position'])) {
61
            $slot->setPosition($options['position']);
62
        }
63
    }
64
65
    private function addProductsToSlot(array $products, ProductBundleSlotInterface $slot): void
66
    {
67
        foreach ($products as $product) {
68
            $this->addProductToSlot($product, $slot);
69
        }
70
    }
71
72
    private function addProductToSlot(ProductInterface $product, ProductBundleSlotInterface $slot): void
73
    {
74
        $slot->addProduct($product);
75
    }
76
}
77