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
|
|
|
protected $canonicalUrlGenerator; |
12
|
|
|
/** @var RequestStack */ |
13
|
|
|
protected $requestStack; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* CanonicalLinkExtension constructor. |
17
|
|
|
* @param CanonicalUrlGenerator $canonicalUrlGenerator |
18
|
|
|
* @param RequestStack $requestStack |
19
|
|
|
*/ |
20
|
2 |
|
public function __construct(CanonicalUrlGenerator $canonicalUrlGenerator, RequestStack $requestStack) |
21
|
|
|
{ |
22
|
2 |
|
$this->canonicalUrlGenerator = $canonicalUrlGenerator; |
23
|
2 |
|
$this->requestStack = $requestStack; |
24
|
2 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @return array |
28
|
|
|
*/ |
29
|
1 |
|
public function getFunctions() |
30
|
|
|
{ |
31
|
|
|
return [ |
32
|
1 |
|
new \Twig_Function('palmtree_canonical_url', [$this, 'generateUrl']), |
33
|
1 |
|
new \Twig_Function('palmtree_canonical_link_tag', [$this, 'renderLinkTag'], [ |
34
|
1 |
|
'needs_environment' => true, |
35
|
|
|
'is_safe' => ['html'], |
36
|
|
|
]), |
37
|
|
|
]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param \Twig_Environment $environment |
42
|
|
|
* @param string $href |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
1 |
|
public function renderLinkTag(\Twig_Environment $environment, $href = null) |
47
|
|
|
{ |
48
|
1 |
|
$output = $environment->render('@PalmtreeCanonicalUrl/canonical_link_tag.html.twig', [ |
49
|
1 |
|
'href' => $href, |
50
|
|
|
]); |
51
|
|
|
|
52
|
1 |
|
return $output; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $route |
57
|
|
|
* @param string|array $parameters |
58
|
|
|
* |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
1 |
|
public function generateUrl($route = null, $parameters = null) |
62
|
|
|
{ |
63
|
1 |
|
if (!$route) { |
|
|
|
|
64
|
|
|
$request = $this->requestStack->getCurrentRequest(); |
65
|
|
|
|
66
|
|
|
$route = $request->attributes->get('_route'); |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
return $this->canonicalUrlGenerator->generateUrl($route, $parameters); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: