Completed
Push — master ( ec5411...629401 )
by Kamil
31:49 queued 16:57
created

ProductTaxonController::updatePositionsAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sylius\Bundle\CoreBundle\Controller;
15
16
use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
17
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
18
use Sylius\Component\Core\Model\ProductTaxonInterface;
19
use Sylius\Component\Resource\ResourceActions;
20
use Symfony\Component\HttpFoundation\JsonResponse;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpFoundation\Session\Session;
24
use Symfony\Component\HttpKernel\Exception\HttpException;
25
use Webmozart\Assert\Assert;
26
27
class ProductTaxonController extends ResourceController
28
{
29
    /**
30
     * @throws HttpException
31
     *
32
     * @deprecated This ajax action is deprecated and will be removed in Sylius 2.0 - use ProductTaxonController::updateProductTaxonsPositionsAction instead.
33
     */
34
    public function updatePositionsAction(Request $request): Response
35
    {
36
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
37
        $this->isGrantedOr403($configuration, ResourceActions::UPDATE);
38
        $productTaxons = $request->get('productTaxons');
39
40
        $this->validateCsrfProtection($request, $configuration);
41
42
        if ($this->shouldProductsPositionsBeUpdated($request, $productTaxons)) {
43
            /** @var ProductTaxonInterface $productTaxon */
44
            foreach ($productTaxons as $productTaxon) {
45
                try {
46
                    $this->updatePositions($productTaxon['position'], $productTaxon['id']);
47
                } catch (\InvalidArgumentException $exception) {
48
                    throw new HttpException(Response::HTTP_BAD_REQUEST, $exception->getMessage());
49
                }
50
51
                $this->manager->flush();
52
            }
53
        }
54
55
        return new JsonResponse();
56
    }
57
58
    public function updateProductTaxonsPositionsAction(Request $request): Response
59
    {
60
        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
61
        $this->isGrantedOr403($configuration, ResourceActions::UPDATE);
62
        $productTaxons = $request->get('productTaxons');
63
64
        $this->validateCsrfProtection($request, $configuration);
65
66
        if ($this->shouldProductsPositionsBeUpdated($request, $productTaxons)) {
67
            /** @var Session $session */
68
            $session = $request->getSession();
69
70
            /** @var ProductTaxonInterface $productTaxon */
71
            foreach ($productTaxons as $id => $position) {
72
                try {
73
                    $this->updatePositions($position, $id);
74
                } catch (\InvalidArgumentException $exception) {
75
                    $session->getFlashBag()->add('error', $exception->getMessage());
76
77
                    return $this->redirectHandler->redirectToReferer($configuration);
78
                }
79
            }
80
81
            $this->manager->flush();
82
        }
83
84
        return $this->redirectHandler->redirectToReferer($configuration);
85
    }
86
87
    private function validateCsrfProtection(Request $request, RequestConfiguration $configuration): void
88
    {
89
        if ($configuration->isCsrfProtectionEnabled() && !$this->isCsrfTokenValid('update-product-taxon-position', $request->request->get('_csrf_token'))) {
90
            throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid csrf token.');
91
        }
92
    }
93
94
    private function shouldProductsPositionsBeUpdated(Request $request, ?array $productTaxons): bool
95
    {
96
        return in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true) && null !== $productTaxons;
97
    }
98
99
    private function updatePositions(string $position, int $id): void
100
    {
101
        Assert::numeric($position, sprintf('The position "%s" is invalid.', $position));
102
103
        $productTaxonFromBase = $this->repository->findOneBy(['id' => $id]);
104
        $productTaxonFromBase->setPosition((int) $position);
105
    }
106
}
107