1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bankiru\Seo\Destination\Compiler; |
4
|
|
|
|
5
|
|
|
use Bankiru\Seo\CompiledLink; |
6
|
|
|
use Bankiru\Seo\Context\ContextExtractor; |
7
|
|
|
use Bankiru\Seo\Destination\CompilableLinkInterface; |
8
|
|
|
use Bankiru\Seo\Destination\DestinationCompiler; |
9
|
|
|
use Bankiru\Seo\Destination\DestinationNormalizer; |
10
|
|
|
use Bankiru\Seo\DestinationInterface; |
11
|
|
|
use Bankiru\Seo\Exception\DestinationException; |
12
|
|
|
|
13
|
|
|
abstract class AbstractCompiler implements DestinationCompiler |
14
|
|
|
{ |
15
|
|
|
/** @var ContextExtractor */ |
16
|
|
|
private $extractor; |
17
|
|
|
/** @var \Twig_Environment */ |
18
|
|
|
private $twig; |
19
|
|
|
/** @var DestinationNormalizer */ |
20
|
|
|
private $normalizer; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* AbstractCompiler constructor. |
24
|
|
|
* |
25
|
|
|
* @param DestinationNormalizer $normalizer |
26
|
|
|
* @param \Twig_Environment $twig |
27
|
|
|
*/ |
28
|
1 |
|
public function __construct(DestinationNormalizer $normalizer, \Twig_Environment $twig = null) |
29
|
|
|
{ |
30
|
1 |
|
$this->extractor = new ContextExtractor(); |
31
|
1 |
|
$this->twig = $twig ?: new \Twig_Environment(new \Twig_Loader_Array([])); |
32
|
1 |
|
$this->normalizer = $normalizer; |
33
|
1 |
|
} |
34
|
|
|
|
35
|
|
|
/** {@inheritdoc} */ |
36
|
1 |
|
final public function compile(DestinationInterface $destination, $title = null, array $attributes = []) |
37
|
|
|
{ |
38
|
1 |
|
$href = $this->getHrefTemplate($destination->getRoute()); |
39
|
1 |
|
$items = array_map([$this, 'normalize'], iterator_to_array($destination)); |
40
|
|
|
|
41
|
|
|
try { |
42
|
1 |
|
return new CompiledLink( |
43
|
1 |
|
$href->compile($items), |
44
|
1 |
|
$this->twig->createTemplate($title)->render($this->extractor->extractContext($destination)), |
45
|
|
|
$attributes |
46
|
1 |
|
); |
47
|
|
|
} catch (\Twig_Error $error) { |
48
|
|
|
throw new DestinationException( |
49
|
|
|
'Error rendering destination title: ' . $error->getMessage(), |
50
|
|
|
$error->getCode(), |
51
|
|
|
$error |
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Allows replace twig via DI |
58
|
|
|
* |
59
|
|
|
* @param \Twig_Environment $twig |
60
|
|
|
*/ |
61
|
|
|
public function setTwig(\Twig_Environment $twig) |
62
|
|
|
{ |
63
|
|
|
$this->twig = $twig; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $route |
68
|
|
|
* |
69
|
|
|
* @return CompilableLinkInterface |
70
|
|
|
*/ |
71
|
|
|
abstract protected function getHrefTemplate($route); |
72
|
|
|
|
73
|
1 |
|
private function normalize($item) |
74
|
|
|
{ |
75
|
1 |
|
if (!$this->normalizer->supports($item)) { |
76
|
|
|
throw DestinationException::normalizationFailed($item); |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return $this->normalizer->normalize($item); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|