TwigSyntaxValidator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 2
Metric Value
wmc 9
c 2
b 1
f 2
lcom 1
cbo 4
dl 0
loc 42
ccs 23
cts 23
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B validate() 0 22 6
A getEnvironment() 0 9 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