Failed Conditions
Pull Request — master (#132)
by Łukasz
03:03
created

PutOptionBasedConfigurableItemToCartHandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 119
Duplicated Lines 32.77 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 11
dl 39
loc 119
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 15 15 1
B handle() 24 24 1
A getVariant() 0 10 3
A areOptionsMatched() 0 10 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Sylius\ShopApiPlugin\Handler;
4
5
use Doctrine\Common\Persistence\ObjectManager;
6
use Sylius\Component\Core\Factory\CartItemFactoryInterface;
7
use Sylius\Component\Core\Model\OrderItemInterface;
8
use Sylius\Component\Core\Model\ProductVariantInterface;
9
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
10
use Sylius\Component\Core\Repository\ProductRepositoryInterface;
11
use Sylius\Component\Order\Modifier\OrderItemQuantityModifierInterface;
12
use Sylius\Component\Order\Processor\OrderProcessorInterface;
13
use Sylius\Component\Product\Model\ProductInterface;
14
use Sylius\ShopApiPlugin\Command\PutOptionBasedConfigurableItemToCart;
15
use Webmozart\Assert\Assert;
16
17
final class PutOptionBasedConfigurableItemToCartHandler
18
{
19
    /**
20
     * @var OrderRepositoryInterface
21
     */
22
    private $cartRepository;
23
24
    /**
25
     * @var ProductRepositoryInterface
26
     */
27
    private $productRepository;
28
29
    /**
30
     * @var CartItemFactoryInterface
31
     */
32
    private $cartItemFactory;
33
34
    /**
35
     * @var OrderItemQuantityModifierInterface
36
     */
37
    private $orderItemModifier;
38
39
    /**
40
     * @var OrderProcessorInterface
41
     */
42
    private $orderProcessor;
43
44
    /**
45
     * @var ObjectManager
46
     */
47
    private $manager;
48
49
    /**
50
     * @param OrderRepositoryInterface $cartRepository
51
     * @param ProductRepositoryInterface $productRepository
52
     * @param CartItemFactoryInterface $cartItemFactory
53
     * @param OrderItemQuantityModifierInterface $orderItemModifier
54
     * @param OrderProcessorInterface $orderProcessor
55
     * @param ObjectManager $manager
56
     */
57 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
        OrderRepositoryInterface $cartRepository,
59
        ProductRepositoryInterface $productRepository,
60
        CartItemFactoryInterface $cartItemFactory,
61
        OrderItemQuantityModifierInterface $orderItemModifier,
62
        OrderProcessorInterface $orderProcessor,
63
        ObjectManager $manager
64
    ) {
65
        $this->cartRepository = $cartRepository;
66
        $this->productRepository = $productRepository;
67
        $this->cartItemFactory = $cartItemFactory;
68
        $this->orderItemModifier = $orderItemModifier;
69
        $this->orderProcessor = $orderProcessor;
70
        $this->manager = $manager;
71
    }
72
73
74
    /**
75
     * @param PutOptionBasedConfigurableItemToCart $putConfigurableItemToCart
76
     */
77 View Code Duplication
    public function handle(PutOptionBasedConfigurableItemToCart $putConfigurableItemToCart)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
    {
79
        $cart = $this->cartRepository->findOneBy(['tokenValue' => $putConfigurableItemToCart->orderToken()]);
80
81
        Assert::notNull($cart, 'Cart has not been found');
82
83
        /** @var ProductInterface $product */
84
        $product = $this->productRepository->findOneByCode($putConfigurableItemToCart->product());
85
86
        Assert::notNull($product, 'Product has not been found');
87
88
        $productVariant = $this->getVariant($putConfigurableItemToCart->options(), $product);
89
90
        /** @var OrderItemInterface $cartItem */
91
        $cartItem = $this->cartItemFactory->createForCart($cart);
0 ignored issues
show
Documentation introduced by
$cart is of type object|null, but the function expects a object<Sylius\Component\...e\Model\OrderInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
92
        $cartItem->setVariant($productVariant);
0 ignored issues
show
Bug introduced by
It seems like $productVariant defined by $this->getVariant($putCo...t->options(), $product) on line 88 can be null; however, Sylius\Component\Core\Mo...Interface::setVariant() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
93
        $this->orderItemModifier->modify($cartItem, $putConfigurableItemToCart->quantity());
94
95
        $cart->addItem($cartItem);
96
97
        $this->orderProcessor->process($cart);
0 ignored issues
show
Documentation introduced by
$cart is of type object|null, but the function expects a object<Sylius\Component\...r\Model\OrderInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
98
99
        $this->manager->persist($cart);
0 ignored issues
show
Bug introduced by
It seems like $cart defined by $this->cartRepository->f...mToCart->orderToken())) on line 79 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
100
    }
101
102
    /**
103
     * @param array $options
104
     * @param ProductInterface $product
105
     *
106
     * @return null|ProductVariantInterface
107
     */
108
    private function getVariant(array $options, ProductInterface $product)
109
    {
110
        foreach ($product->getVariants() as $variant) {
111
            if ($this->areOptionsMatched($options, $variant)) {
112
                return $variant;
113
            }
114
        }
115
116
        throw new \InvalidArgumentException('Variant could not be resolved');
117
    }
118
119
    /**
120
     * @param array $options
121
     * @param ProductVariantInterface $variant
122
     *
123
     * @return bool
124
     */
125
    private function areOptionsMatched(array $options, ProductVariantInterface $variant)
126
    {
127
        foreach ($variant->getOptionValues() as $optionValue) {
128
            if (!isset($options[$optionValue->getOptionCode()]) || $optionValue->getCode() !== $options[$optionValue->getOptionCode()]) {
129
                return false;
130
            }
131
        }
132
133
        return true;
134
    }
135
}
136