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
|
|
|
} |