ProductAssociationsToLinksTransformer::transform()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 9.1608
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project.
7
 * You can find more information about us on https://bitbag.io and write us
8
 * an email on [email protected].
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusVueStorefrontPlugin\Sylius\Transformer\SyliusProduct;
14
15
use BitBag\SyliusVueStorefrontPlugin\Document\Product\ProductLinks;
16
use BitBag\SyliusVueStorefrontPlugin\Document\Product\ProductLinks\Link;
17
use Doctrine\Common\Collections\Collection;
18
use Sylius\Component\Core\Model\ProductInterface;
19
use Sylius\Component\Product\Model\ProductAssociationInterface;
20
21
final class ProductAssociationsToLinksTransformer implements ProductAssociationsToLinksTransformerInterface
22
{
23
    /** @param Collection|ProductAssociationInterface[] $syliusProductAssociations */
24
    public function transform(Collection $syliusProductAssociations): ProductLinks
25
    {
26
        $productLinks = [];
27
        $productLinkPosition = 1;
28
29
        foreach ($syliusProductAssociations as $syliusProductAssociation) {
30
            $syliusProductAssociationOwnerCode = $syliusProductAssociation->getOwner()->getCode();
31
32
            if (null === $syliusProductAssociation->getAssociatedProducts()) {
33
                continue;
34
            }
35
36
            /** @var ProductInterface $product */
37
            foreach ($syliusProductAssociation->getAssociatedProducts() as $product) {
38
                $productLinks[] = new Link(
39
                    $syliusProductAssociationOwnerCode,
40
                    $this->renameAssociationType($syliusProductAssociation->getType()->getCode()),
41
                    $productLinkPosition,
42
                    $product->getCode(),
43
                    count($product->getVariants()) > 1 ? 'configurable' : 'simple'
44
                );
45
46
                ++$productLinkPosition;
47
            }
48
        }
49
50
        return new ProductLinks($productLinks);
51
    }
52
53
    private function renameAssociationType(string $syliusAssociationTypeCode): string
54
    {
55
        switch ($syliusAssociationTypeCode) {
56
            case 'similar_products':
57
                return 'related';
58
            case 'xyz':
59
                return 'associated';
60
            case 'up-sell':
61
            default:
62
                return 'upsell';
63
        }
64
    }
65
}
66