forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCell.php
More file actions
213 lines (180 loc) · 5.91 KB
/
Copy pathCell.php
File metadata and controls
213 lines (180 loc) · 5.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\View\Exceptions\ViewException;
use Config\Services;
use ReflectionException;
use ReflectionMethod;
/**
* Class Cell
*
* A simple class that can call any other class that can be loaded,
* and echo out it's result. Intended for displaying small blocks of
* content within views that can be managed by other libraries and
* not require they are loaded within controller.
*
* Used with the helper function, it's use will look like:
*
* viewCell('\Some\Class::method', 'limit=5 sort=asc', 60, 'cache-name');
*
* Parameters are matched up with the callback method's arguments of the same name:
*
* class Class {
* function method($limit, $sort)
* }
*
* Alternatively, the params will be passed into the callback method as a simple array
* if matching params are not found.
*
* class Class {
* function method(array $params=null)
* }
*/
class Cell
{
/**
* Instance of the current Cache Instance
*
* @var CacheInterface
*/
protected $cache;
/**
* Cell constructor.
*/
public function __construct(CacheInterface $cache)
{
$this->cache = $cache;
}
/**
* Render a cell, returning its body as a string.
*
* @param null $params
*
* @throws ReflectionException
*/
public function render(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string
{
[$class, $method] = $this->determineClass($library);
// Is it cached?
$cacheName = ! empty($cacheName)
? $cacheName
: str_replace(['\\', '/'], '', $class) . $method . md5(serialize($params));
if (! empty($this->cache) && $output = $this->cache->get($cacheName)) {
return $output;
}
// Not cached - so grab it...
$instance = new $class();
if (method_exists($instance, 'initController')) {
$instance->initController(Services::request(), Services::response(), Services::logger());
}
if (! method_exists($instance, $method)) {
throw ViewException::forInvalidCellMethod($class, $method);
}
// Try to match up the parameter list we were provided
// with the parameter name in the callback method.
$paramArray = $this->prepareParams($params);
$refMethod = new ReflectionMethod($instance, $method);
$paramCount = $refMethod->getNumberOfParameters();
$refParams = $refMethod->getParameters();
if ($paramCount === 0) {
if (! empty($paramArray)) {
throw ViewException::forMissingCellParameters($class, $method);
}
$output = $instance->{$method}();
} elseif (($paramCount === 1)
&& ((! array_key_exists($refParams[0]->name, $paramArray))
|| (array_key_exists($refParams[0]->name, $paramArray)
&& count($paramArray) !== 1))
) {
$output = $instance->{$method}($paramArray);
} else {
$fireArgs = [];
$methodParams = [];
foreach ($refParams as $arg) {
$methodParams[$arg->name] = true;
if (array_key_exists($arg->name, $paramArray)) {
$fireArgs[$arg->name] = $paramArray[$arg->name];
}
}
foreach (array_keys($paramArray) as $key) {
if (! isset($methodParams[$key])) {
throw ViewException::forInvalidCellParameter($key);
}
}
$output = $instance->{$method}(...array_values($fireArgs));
}
// Can we cache it?
if (! empty($this->cache) && $ttl !== 0) {
$this->cache->save($cacheName, $output, $ttl);
}
return $output;
}
/**
* Parses the params attribute. If an array, returns untouched.
* If a string, it should be in the format "key1=value key2=value".
* It will be split and returned as an array.
*
* @param mixed $params
*
* @return array|null
*/
public function prepareParams($params)
{
if (empty($params) || (! is_string($params) && ! is_array($params))) {
return [];
}
if (is_string($params)) {
$newParams = [];
$separator = ' ';
if (strpos($params, ',') !== false) {
$separator = ',';
}
$params = explode($separator, $params);
unset($separator);
foreach ($params as $p) {
if (! empty($p)) {
[$key, $val] = explode('=', $p);
$newParams[trim($key)] = trim($val, ', ');
}
}
$params = $newParams;
unset($newParams);
}
if ($params === []) {
return [];
}
return $params;
}
/**
* Given the library string, attempts to determine the class and method
* to call.
*/
protected function determineClass(string $library): array
{
// We don't want to actually call static methods
// by default, so convert any double colons.
$library = str_replace('::', ':', $library);
[$class, $method] = explode(':', $library);
if (empty($class)) {
throw ViewException::forNoCellClass();
}
if (! class_exists($class, true)) {
throw ViewException::forInvalidCellClass($class);
}
if (empty($method)) {
$method = 'index';
}
return [
$class,
$method,
];
}
}