Completed
Push — master ( 92f2fd...10a92d )
by Paweł
20s
created

PutItemsToCartAction::__invoke()   B

Complexity

Conditions 9
Paths 42

Size

Total Lines 56
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 7.1584
c 0
b 0
f 0
cc 9
eloc 30
nc 42
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\ConstraintViolationListInterface;
22
use Symfony\Component\Validator\Validator\ValidatorInterface;
23
24
final class PutItemsToCartAction
25
{
26
    /** @var ViewHandlerInterface */
27
    private $viewHandler;
28
29
    /** @var CommandBus */
30
    private $bus;
31
32
    /** @var ValidatorInterface */
33
    private $validator;
34
35
    /** @var CartViewRepositoryInterface */
36
    private $cartQuery;
37
38
    /** @var string */
39
    private $validationErrorViewClass;
40
41
    public function __construct(
42
        ViewHandlerInterface $viewHandler,
43
        CommandBus $bus,
44
        ValidatorInterface $validator,
45
        CartViewRepositoryInterface $cartQuery,
46
        string $validationErrorViewClass
47
    ) {
48
        $this->viewHandler = $viewHandler;
49
        $this->bus = $bus;
50
        $this->validator = $validator;
51
        $this->cartQuery = $cartQuery;
52
        $this->validationErrorViewClass = $validationErrorViewClass;
53
    }
54
55
    public function __invoke(Request $request): Response
56
    {
57
        /** @var ConstraintViolationListInterface[] $validationResults */
58
        $validationResults = [];
59
        $commandRequests = [];
60
        $commandsToExecute = [];
61
        $token = $request->attributes->get('token');
62
63
        foreach ($request->request->all() as $item) {
64
            $item['token'] = $token;
65
            $commandRequests[] = $this->provideCommandRequest($item);
66
        }
67
68
        foreach ($commandRequests as $commandRequest) {
69
            $validationResult = $this->validator->validate($commandRequest);
70
71
            if (0 === count($validationResult)) {
72
                $commandsToExecute[] = $commandRequest->getCommand();
73
            }
74
75
            $validationResults[] = $validationResult;
76
        }
77
78
        if (!$this->isValid($validationResults)) {
79
            /** @var ValidationErrorView $errorMessage */
80
            $errorMessage = new $this->validationErrorViewClass();
81
82
            $errorMessage->code = Response::HTTP_BAD_REQUEST;
83
            $errorMessage->message = 'Validation failed';
84
85
            foreach ($validationResults as $validationResult) {
86
                $errors = [];
87
88
                /** @var ConstraintViolationInterface $result */
89
                foreach ($validationResult as $result) {
90
                    $errors[$result->getPropertyPath()][] = $result->getMessage();
91
                }
92
93
                $errorMessage->errors[] = $errors;
94
            }
95
96
            return $this->viewHandler->handle(View::create($errorMessage, Response::HTTP_BAD_REQUEST));
97
        }
98
99
        foreach ($commandsToExecute as $commandToExecute) {
100
            $this->bus->handle($commandToExecute);
101
        }
102
103
        try {
104
            return $this->viewHandler->handle(
105
                View::create($this->cartQuery->getOneByToken($token), Response::HTTP_CREATED)
106
            );
107
        } catch (\InvalidArgumentException $exception) {
108
            throw new BadRequestHttpException($exception->getMessage());
109
        }
110
    }
111
112
    /**
113
     * @param array $item
114
     *
115
     * @return PutOptionBasedConfigurableItemToCartRequest|PutSimpleItemToCartRequest|PutVariantBasedConfigurableItemToCartRequest
116
     */
117
    private function provideCommandRequest(array $item)
118
    {
119
        if (!isset($item['variantCode']) && !isset($item['options'])) {
120
            return PutSimpleItemToCartRequest::fromArray($item);
121
        }
122
123
        if (isset($item['variantCode']) && !isset($item['options'])) {
124
            return PutVariantBasedConfigurableItemToCartRequest::fromArray($item);
125
        }
126
127
        if (!isset($item['variantCode']) && isset($item['options'])) {
128
            return PutOptionBasedConfigurableItemToCartRequest::fromArray($item);
129
        }
130
131
        throw new NotFoundHttpException('Variant not found for given configuration');
132
    }
133
134
    private function isValid(array $validationResults): bool
135
    {
136
        foreach ($validationResults as $validationResult) {
137
            if (0 !== count($validationResult)) {
138
                return false;
139
            }
140
        }
141
142
        return true;
143
    }
144
}
145