|
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
|
2 |
|
public function __construct($options = []) |
|
30
|
|
|
{ |
|
31
|
2 |
|
$this->initTwig($options); |
|
32
|
2 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Get Content XML from template. |
|
36
|
|
|
* |
|
37
|
|
|
* @param string $template |
|
38
|
|
|
* @param object $doc |
|
39
|
|
|
* @return string |
|
40
|
|
|
*/ |
|
41
|
2 |
|
public function render($template, $doc) |
|
42
|
|
|
{ |
|
43
|
2 |
|
$this->validate($doc); |
|
44
|
|
|
|
|
45
|
2 |
|
return $this->twig->render($template, [ |
|
46
|
|
|
'doc' => $doc |
|
47
|
2 |
|
]); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
2 |
|
private function initTwig($options) |
|
51
|
|
|
{ |
|
52
|
2 |
|
$loader = new \Twig_Loader_Filesystem(__DIR__ . '/../Templates'); |
|
53
|
2 |
|
$numFilter = new \Twig_SimpleFilter('n_format', function ($number, $decimals = 2) { |
|
54
|
2 |
|
return number_format($number, $decimals, '.', ''); |
|
55
|
2 |
|
}); |
|
56
|
2 |
|
$twig = new \Twig_Environment($loader, $options); |
|
57
|
2 |
|
$twig->addFilter($numFilter); |
|
58
|
|
|
|
|
59
|
2 |
|
$this->twig = $twig; |
|
60
|
2 |
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Validate Entity. |
|
64
|
|
|
* |
|
65
|
|
|
* @param object $entity |
|
66
|
|
|
* @throws ValidationException |
|
67
|
|
|
*/ |
|
68
|
2 |
|
public function validate($entity) |
|
69
|
|
|
{ |
|
70
|
|
|
// TODO: init validator one time. |
|
71
|
2 |
|
$validator = Validation::createValidatorBuilder() |
|
72
|
2 |
|
->addMethodMapping('loadValidatorMetadata') |
|
73
|
2 |
|
->getValidator(); |
|
74
|
|
|
|
|
75
|
2 |
|
$errs = $validator->validate($entity); |
|
76
|
2 |
|
if ($errs->count() > 0) { |
|
77
|
|
|
throw new ValidationException($errs); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
} |