Completed
Push — master ( a0d808...22db96 )
by Giancarlos
03:50
created

TwigBuilder::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Giansalex
5
 * Date: 09/08/2017
6
 * Time: 19:23
7
 */
8
9
namespace Greenter\Xml\Builder;
10
11
use Greenter\Xml\Exception\ValidationException;
12
use Symfony\Component\Validator\Validation;
13
14
/**
15
 * Class TwigBuilder
16
 * @package Greenter\Xml\Builder
17
 */
18
class TwigBuilder
19
{
20
    /**
21
     * @var \Twig_Environment
22
     */
23
    protected $twig;
24
25
    /**
26
     * TwigBuilder constructor.
27
     * @param array $options [optional] Recommended: 'cache' => '/dir/cache'
28
     */
29 94
    public function __construct($options = [])
30
    {
31 94
        $this->initTwig($options);
32 94
    }
33
34
    /**
35
     * Get Content XML from template.
36
     *
37
     * @param string $template
38
     * @param object $doc
39
     * @return string
40
     */
41 94
    public function render($template, $doc)
42
    {
43 94
        $this->validate($doc);
44
45 58
        return $this->twig->render($template, [
46
            'doc' => $doc
47 58
        ]);
48
    }
49
50 94
    private function initTwig($options)
51
    {
52 94
        $loader = new \Twig_Loader_Filesystem(__DIR__ . '/../Templates');
53 94
        $numFilter = new \Twig_SimpleFilter('n_format', function ($number, $decimals = 2) {
54 48
            return number_format($number, $decimals, '.', '');
55 94
        });
56 94
        $twig = new \Twig_Environment($loader, $options);
57 94
        $twig->addFilter($numFilter);
58
59 94
        $this->twig = $twig;
60 94
    }
61
62
    /**
63
     * Validate Entity.
64
     *
65
     * @param object $entity
66
     * @throws ValidationException
67
     */
68 94
    public function validate($entity)
69
    {
70
        // TODO: init validator one time.
71 94
        $validator = Validation::createValidatorBuilder()
72 94
            ->addMethodMapping('loadValidatorMetadata')
73 94
            ->getValidator();
74
75 94
        $errs = $validator->validate($entity);
76 94
        if ($errs->count() > 0) {
77 36
            throw new ValidationException($errs);
78
        }
79
    }
80
}