Completed
Push — master ( 8f4e42...45ae1b )
by Igor
04:27
created

BarcodeValidator::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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