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

PutItemsToCartAction   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 13

Importance

Changes 0
Metric Value
wmc 20
lcom 0
cbo 13
dl 0
loc 126
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
B __invoke() 0 56 9
B provideCommandRequest() 0 16 7
A isValid() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sylius\ShopApiPlugin\Controller\Cart;
6
7
use FOS\RestBundle\View\View;
8
use FOS\RestBundle\View\ViewHandlerInterface;
9
use League\Tactician\CommandBus;
10
use Sylius\ShopApiPlugin\Factory\ValidationErrorViewFactoryInterface;
11
use Sylius\ShopApiPlugin\View\ValidationErrorView;
12
use Sylius\ShopApiPlugin\ViewRepository\CartViewRepositoryInterface;
13
use Sylius\ShopApiPlugin\Request\PutOptionBasedConfigurableItemToCartRequest;
14
use Sylius\ShopApiPlugin\Request\PutSimpleItemToCartRequest;
15
use Sylius\ShopApiPlugin\Request\PutVariantBasedConfigurableItemToCartRequest;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
19
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
20
use Symfony\Component\Validator\ConstraintViolationInterface;
21
use Symfony\Component\Validator\Validator\ValidatorInterface;
22
23
final class PutItemsToCartAction
24
{
25
    /** @var ViewHandlerInterface */
26
    private $viewHandler;
27
28
    /** @var CommandBus */
29
    private $bus;
30
31
    /** @var ValidatorInterface */
32
    private $validator;
33
34
    /** @var ValidationErrorViewFactoryInterface */
35
    private $validationErrorViewFactory;
36
37
    /** @var CartViewRepositoryInterface */
38
    private $cartQuery;
39
40
    /** @var string */
41
    private $validationErrorViewClass;
42
43
    public function __construct(
44
        ViewHandlerInterface $viewHandler,
45
        CommandBus $bus,
46
        ValidatorInterface $validator,
47
        ValidationErrorViewFactoryInterface $validationErrorViewFactory,
48
        CartViewRepositoryInterface $cartQuery,
49
        string $validationErrorViewClass
50
    ) {
51
        $this->viewHandler = $viewHandler;
52
        $this->bus = $bus;
53
        $this->validator = $validator;
54
        $this->validationErrorViewFactory = $validationErrorViewFactory;
55
        $this->cartQuery = $cartQuery;
56
        $this->validationErrorViewClass = $validationErrorViewClass;
57
    }
58
59
    public function __invoke(Request $request): Response
60
    {
61
        $validationResults = [];
62
        $commandRequests = [];
63
        $commandsToExecute = [];
64
        $token = $request->attributes->get('token');
65
66
        foreach ($request->request->all() as $item) {
67
            $item['token'] = $token;
68
            $commandRequests[] = $this->provideCommandRequest($item);
69
        }
70
71
        foreach ($commandRequests as $commandRequest) {
72
            $validationResult = $this->validator->validate($commandRequest);
73
74
            if (0 === count($validationResult)) {
75
                $commandsToExecute[] = $commandRequest->getCommand();
76
            }
77
78
            $validationResults[] = $validationResult;
79
        }
80
81
        if (!$this->isValid($validationResults)) {
82
            /** @var ValidationErrorView $errorMessage */
83
            $errorMessage = new $this->validationErrorViewClass();
84
85
            $errorMessage->code = Response::HTTP_BAD_REQUEST;
86
            $errorMessage->message = 'Validation failed';
87
88
            /** @var ConstraintViolationInterface $result */
89
            foreach ($validationResults as $validationResult) {
90
                $iteration = 0;
0 ignored issues
show
Unused Code introduced by
$iteration is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
91
                $errors = [];
92
93
                foreach ($validationResult as $result) {
94
                    $errors[$result->getPropertyPath()][] = $result->getMessage();
95
                }
96
97
                $errorMessage->errors[] = $errors;
98
            }
99
100
            return $this->viewHandler->handle(View::create($errorMessage, Response::HTTP_BAD_REQUEST));
101
        }
102
103
        foreach ($commandsToExecute as $commandToExecute) {
104
            $this->bus->handle($commandToExecute);
105
        }
106
107
        try {
108
            return $this->viewHandler->handle(
109
                View::create($this->cartQuery->getOneByToken($token), Response::HTTP_CREATED)
110
            );
111
        } catch (\InvalidArgumentException $exception) {
112
            throw new BadRequestHttpException($exception->getMessage());
113
        }
114
    }
115
116
    /**
117
     * @param array $item
118
     *
119
     * @return PutOptionBasedConfigurableItemToCartRequest|PutSimpleItemToCartRequest|PutVariantBasedConfigurableItemToCartRequest
120
     */
121
    private function provideCommandRequest(array $item)
122
    {
123
        if (!isset($item['variantCode']) && !isset($item['options'])) {
124
            return PutSimpleItemToCartRequest::fromArray($item);
125
        }
126
127
        if (isset($item['variantCode']) && !isset($item['options'])) {
128
            return PutVariantBasedConfigurableItemToCartRequest::fromArray($item);
129
        }
130
131
        if (!isset($item['variantCode']) && isset($item['options'])) {
132
            return PutOptionBasedConfigurableItemToCartRequest::fromArray($item);
133
        }
134
135
        throw new NotFoundHttpException('Variant not found for given configuration');
136
    }
137
138
    private function isValid(array $validationResults): bool
139
    {
140
        foreach ($validationResults as $validationResult) {
141
            if (0 !== count($validationResult)) {
142
                return false;
143
            }
144
        }
145
146
        return true;
147
    }
148
}
149