|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Palmtree\CanonicalUrlBundle\Twig\Extension; |
|
4
|
|
|
|
|
5
|
|
|
use Palmtree\CanonicalUrlBundle\Service\CanonicalUrlGenerator; |
|
6
|
|
|
use Symfony\Component\HttpFoundation\RequestStack; |
|
7
|
|
|
|
|
8
|
|
|
class CanonicalLinkExtension extends \Twig_Extension |
|
|
|
|
|
|
9
|
|
|
{ |
|
10
|
|
|
/** @var CanonicalUrlGenerator */ |
|
11
|
|
|
private $canonicalUrlGenerator; |
|
12
|
|
|
/** @var RequestStack */ |
|
13
|
|
|
private $requestStack; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* CanonicalLinkExtension constructor. |
|
17
|
|
|
* |
|
18
|
|
|
* @param CanonicalUrlGenerator $canonicalUrlGenerator |
|
19
|
|
|
* @param RequestStack $requestStack |
|
20
|
|
|
*/ |
|
21
|
3 |
|
public function __construct(CanonicalUrlGenerator $canonicalUrlGenerator, RequestStack $requestStack) |
|
22
|
|
|
{ |
|
23
|
3 |
|
$this->canonicalUrlGenerator = $canonicalUrlGenerator; |
|
24
|
3 |
|
$this->requestStack = $requestStack; |
|
25
|
3 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @return \Twig_Function[] |
|
29
|
|
|
*/ |
|
30
|
1 |
|
public function getFunctions() |
|
31
|
|
|
{ |
|
32
|
|
|
return [ |
|
|
|
|
|
|
33
|
1 |
|
new \Twig_SimpleFunction('palmtree_canonical_url', [$this, 'generateUrl']), |
|
|
|
|
|
|
34
|
1 |
|
new \Twig_SimpleFunction('palmtree_canonical_link_tag', [$this, 'renderLinkTag'], [ |
|
|
|
|
|
|
35
|
1 |
|
'needs_environment' => true, |
|
36
|
|
|
'is_safe' => ['html'], |
|
37
|
|
|
]), |
|
38
|
|
|
]; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param \Twig_Environment $environment |
|
43
|
|
|
* @param string $href |
|
44
|
|
|
* |
|
45
|
|
|
* @return string |
|
46
|
|
|
*/ |
|
47
|
1 |
|
public function renderLinkTag(\Twig_Environment $environment, $href = null) |
|
48
|
|
|
{ |
|
49
|
1 |
|
$output = $environment->render('@PalmtreeCanonicalUrl/canonical_link_tag.html.twig', [ |
|
50
|
1 |
|
'href' => $href, |
|
51
|
|
|
]); |
|
52
|
|
|
|
|
53
|
1 |
|
return $output; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param string $route |
|
58
|
|
|
* @param string|array $parameters |
|
59
|
|
|
* |
|
60
|
|
|
* @see CanonicalUrlGenerator::generate() For parameter descriptions. |
|
61
|
|
|
* |
|
62
|
|
|
* @return string |
|
63
|
|
|
*/ |
|
64
|
2 |
|
public function generateUrl($route = null, $parameters = []) |
|
65
|
|
|
{ |
|
66
|
2 |
|
if (\func_num_args() === 0) { |
|
67
|
1 |
|
$request = $this->requestStack->getCurrentRequest(); |
|
68
|
|
|
|
|
69
|
1 |
|
$route = $request->attributes->get('_route'); |
|
70
|
1 |
|
$parameters = $request->attributes->get('_route_params'); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
2 |
|
return $this->canonicalUrlGenerator->generate($route, $parameters); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|