OrderItemExistValidator::validate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
cc 4
nc 4
nop 2
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\Validator\Cart;
14
15
use Doctrine\Common\Collections\Criteria;
16
use Sylius\Component\Core\Model\OrderInterface;
17
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
18
use Symfony\Component\Validator\Constraint;
19
use Symfony\Component\Validator\ConstraintValidator;
20
21
final class OrderItemExistValidator extends ConstraintValidator
22
{
23
    /** @var OrderRepositoryInterface */
24
    private $cartRepository;
25
26
    public function __construct(OrderRepositoryInterface $cartRepository)
27
    {
28
        $this->cartRepository = $cartRepository;
29
    }
30
31
    public function validate($request, Constraint $constraint): void
32
    {
33
        $cart = $this->cartRepository->findOneBy([
34
            'tokenValue' => $request->cartId,
35
            'state' => OrderInterface::STATE_CART,
36
        ]);
37
38
        if (null === $cart) {
39
            return;
40
        }
41
42
        if (!isset($request->cartItem)) {
43
            $this->context->addViolation($constraint->message);
44
45
            return;
46
        }
47
48
        $orderItem = $cart->getItems()->matching(
49
            Criteria::create()
50
                ->where(
51
                    Criteria::expr()->eq('id', $request->cartItem->item_id)
52
                )
53
        )->first();
54
55
        if (false === $orderItem) {
56
            $this->context->addViolation($constraint->message);
57
        }
58
    }
59
}
60