Test Failed
Push — master ( 05d675...f4e7d7 )
by Giancarlos
04:02
created

TwigBuilder::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 1
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
     * Directorio de Cache para las template de Documentos.
22
     *
23
     * @var string
24
     */
25
    protected $dirCache;
26
27
    /**
28
     * Get Content XML from template.
29
     *
30
     * @param string $template
31
     * @param object $doc
32
     * @return string
33
     */
34 2
    public function render($template, $doc)
35
    {
36 2
        $this->validate($doc);
37
38 2
        $twig = $this->getRender();
39 2
        return $twig->render($template, [
40
            'doc' => $doc
41 2
        ]);
42
    }
43
44 2
    private function getRender()
45
    {
46
        //TODO: load render one time.
47 2
        $loader = new \Twig_Loader_Filesystem(__DIR__ . '/../Templates');
48 2
        $numFilter = new \Twig_SimpleFilter('n_format', function ($number, $decimals = 2) {
49 2
            return number_format($number, $decimals, '.', '');
50 2
        });
51 2
        $twig = new \Twig_Environment($loader, array(
52 2
            'cache' => $this->dirCache,
53 2
        ));
54 2
        $twig->addFilter($numFilter);
55
56 2
        return $twig;
57
    }
58
59
    /**
60
     * Validate Entity.
61
     *
62
     * @param object $entity
63
     * @throws ValidationException
64
     */
65 2
    public function validate($entity)
66
    {
67
        // TODO: init validator one time.
68 2
        $validator = Validation::createValidatorBuilder()
69 2
            ->addMethodMapping('loadValidatorMetadata')
70 2
            ->getValidator();
71
72 2
        $errs = $validator->validate($entity);
73 2
        if ($errs->count() > 0) {
74
            throw new ValidationException($errs);
75
        }
76 2
    }
77
78
    /**
79
     * Set argumentos.
80
     *
81
     * @param $params
82
     * @throws \Exception
83
     */
84
    public function addParameters($params)
85
    {
86
        if (!$params['cache_dir']) {
87
            return;
88
        }
89
90
        $this->dirCache = $params['cache_dir'];
91
    }
92
}