TwigSyntaxValidator::getEnvironment()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
namespace Boekkooi\Bundle\TwigJackBundle\Validator\Constraint;
3
4
use Symfony\Component\Validator\Constraint;
5
use Symfony\Component\Validator\ConstraintValidator;
6
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
7
8
/**
9
 * @author Warnar Boekkooi <[email protected]>
10
 */
11
class TwigSyntaxValidator extends ConstraintValidator
12
{
13
    protected $environment;
14
15 8
    public function __construct(\Twig_Environment $environment)
16
    {
17 8
        $this->environment = $environment;
18 8
    }
19
20 8
    public function validate($value, Constraint $constraint)
21
    {
22 8
        if (!$constraint instanceof TwigSyntax) {
23 1
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\TwigSyntax');
24
        }
25
26 7
        if ($value === '' || $value === null) {
27 2
            return;
28
        }
29
30 5
        $env = $this->getEnvironment($constraint);
31
        try {
32 5
            $tokeStream = $env->tokenize($value);
33 4
            if ($constraint->parse) {
34 3
                $env->parse($tokeStream);
35 2
            }
36 5
        } catch (\Twig_Error_Syntax $e) {
37 2
            $this->context->addViolation($constraint->message, array(
38 2
                '{{ value }}' => $this->formatValue($value),
39 2
            ));
40
        }
41 5
    }
42
43 5
    protected function getEnvironment(TwigSyntax $constraint)
44
    {
45 5
        $env = $constraint->environment;
46 5
        if ($env !== null) {
47 1
            return $env;
48
        }
49
50 4
        return $this->environment;
51
    }
52
}
53