BarcodeValidator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 22
rs 9.6111
cc 5
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Loevgaard\SyliusBarcodePlugin\Validator;
6
7
use InvalidArgumentException;
8
use Loevgaard\SyliusBarcodePlugin\Validator\Constraint\Barcode;
9
use function Safe\sprintf;
10
use Symfony\Component\Validator\Constraint;
11
use Symfony\Component\Validator\ConstraintValidator;
12
use violuke\Barcodes\BarcodeValidator as ActualBarcodeValidator;
13
14
class BarcodeValidator extends ConstraintValidator
15
{
16
    public function validate($value, Constraint $constraint): void
17
    {
18
        // custom constraints should ignore null and empty values to allow
19
        // other constraints (NotBlank, NotNull, etc.) take care of that
20
        if ('' === $value || null === $value) {
21
            return;
22
        }
23
24
        if (!$constraint instanceof Barcode) {
25
            throw new InvalidArgumentException(sprintf('This validator only supports the %s constraint', Barcode::class));
26
        }
27
28
        $validator = new ActualBarcodeValidator($value);
29
        $valid = (bool) $validator->isValid();
30
31
        if (!$valid) {
32
            $this->context->buildViolation($constraint->message)
33
                ->setParameter('{{ string }}', $value)
34
                ->addViolation();
35
        }
36
37
        unset($validator);
38
    }
39
}
40