Completed
Push — master ( 94a5eb...cfd896 )
by Albert
03:49
created

SymfonyValidatorExtension::error()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nastoletni\Code\Twig;
6
7
use Symfony\Component\Validator\ConstraintViolationInterface;
8
use Symfony\Component\Validator\ConstraintViolationListInterface;
9
use Twig_SimpleFunction;
10
11
class SymfonyValidatorExtension extends \Twig_Extension
12
{
13
    /**
14
     * {@inheritdoc}
15
     */
16 1
    public function getFunctions(): array
17
    {
18
        return [
19 1
            new Twig_SimpleFunction('error', [$this, 'error']),
20
        ];
21
    }
22
23
    /**
24
     * Yields all error messages from given field.
25
     *
26
     * @param string                                $field
27
     * @param ConstraintViolationListInterface|null $errors
28
     *
29
     * @return iterable
30
     */
31 2
    public function error(string $field, ?ConstraintViolationListInterface $errors): iterable
32
    {
33 2
        if (is_null($errors)) {
34 1
            return;
35
        }
36
37
        /** @var ConstraintViolationInterface $error */
38 1
        foreach ($errors as $error) {
39 1
            if ($error->getPropertyPath() == $field) {
40 1
                yield $error->getMessage();
41
            }
42
        }
43 1
    }
44
}
45