1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Resilient\Twig\Extension; |
4
|
|
|
|
5
|
|
|
use \Psr\Http\Message\UriInterface; |
6
|
|
|
use \Slim\Interfaces\RouterInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Twig Router Extension for Slim Routing |
10
|
|
|
*/ |
11
|
|
|
class Slim extends \Twig_Extension |
12
|
|
|
{ |
13
|
|
|
private $uri; |
14
|
|
|
|
15
|
|
|
public function __construct(RouterInterface $router, UriInterface $uri) |
16
|
|
|
{ |
17
|
|
|
$this->router = $router; |
|
|
|
|
18
|
|
|
$this->uri = $uri; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function getName() |
22
|
|
|
{ |
23
|
|
|
return 'slim kln'; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function getFunctions() |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
|
|
new \Twig_SimpleFunction('path_for', array($this, 'pathFor')), |
30
|
|
|
new \Twig_SimpleFunction('base_url', array($this, 'baseUrl')), |
31
|
|
|
new \Twig_SimpleFunction('is_current_path', array($this, 'isCurrentPath')), |
32
|
|
|
]; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* pathFor function. |
37
|
|
|
* |
38
|
|
|
* @access public |
39
|
|
|
* @param mixed $name |
40
|
|
|
* @param mixed $data (default: []) |
41
|
|
|
* @param mixed $queryParams (default: []) |
42
|
|
|
* @return string |
43
|
|
|
*/ |
44
|
|
|
public function pathFor($name, $data = [], $queryParams = []) |
45
|
|
|
{ |
46
|
|
|
return $this->router->pathFor($name, $data, $queryParams); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* baseUrl function. |
51
|
|
|
* |
52
|
|
|
* @access public |
53
|
|
|
* @return string |
54
|
|
|
*/ |
55
|
|
|
public function baseUrl() |
56
|
|
|
{ |
57
|
|
|
if (is_string($this->uri)) { |
58
|
|
|
return $this->uri; |
59
|
|
|
} |
60
|
|
|
if (method_exists($this->uri, 'getBaseUrl')) { |
61
|
|
|
return $this->uri->getBaseUrl(); |
|
|
|
|
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* isCurrentPath function. |
67
|
|
|
* |
68
|
|
|
* @access public |
69
|
|
|
* @param mixed $name |
70
|
|
|
* @return boolean |
71
|
|
|
*/ |
72
|
|
|
public function isCurrentPath($name) |
73
|
|
|
{ |
74
|
|
|
return $this->router->pathFor($name) === $this->uri->getPath(); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Set the base url |
79
|
|
|
* |
80
|
|
|
* @param string|Slim\Http\Uri $baseUrl |
81
|
|
|
* @return void |
82
|
|
|
*/ |
83
|
|
|
public function setBaseUrl($baseUrl) |
84
|
|
|
{ |
85
|
|
|
$this->uri = $baseUrl; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: