Repository navigation
Expand file tree
/
Copy pathStringTemplate.php
More file actions
380 lines (346 loc) · 11 KB
/
Copy pathStringTemplate.php
File metadata and controls
380 lines (346 loc) · 11 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Core\Exception\Exception;
use Cake\Core\InstanceConfigTrait;
use Cake\Utility\Hash;
use RuntimeException;
/**
* Provides an interface for registering and inserting
* content into simple logic-less string templates.
*
* Used by several helpers to provide simple flexible templates
* for generating HTML and other content.
*/
class StringTemplate
{
use InstanceConfigTrait {
getConfig as get;
}
/**
* List of attributes that can be made compact.
*
* @var array
*/
protected $_compactAttributes = [
'allowfullscreen' => true,
'async' => true,
'autofocus' => true,
'autoplay' => true,
'checked' => true,
'compact' => true,
'controls' => true,
'declare' => true,
'default' => true,
'defaultchecked' => true,
'defaultmuted' => true,
'defaultselected' => true,
'defer' => true,
'disabled' => true,
'enabled' => true,
'formnovalidate' => true,
'hidden' => true,
'indeterminate' => true,
'inert' => true,
'ismap' => true,
'itemscope' => true,
'loop' => true,
'multiple' => true,
'muted' => true,
'nohref' => true,
'noresize' => true,
'noshade' => true,
'novalidate' => true,
'nowrap' => true,
'open' => true,
'pauseonexit' => true,
'readonly' => true,
'required' => true,
'reversed' => true,
'scoped' => true,
'seamless' => true,
'selected' => true,
'sortable' => true,
'truespeed' => true,
'typemustmatch' => true,
'visible' => true,
];
/**
* The default templates this instance holds.
*
* @var array
*/
protected $_defaultConfig = [];
/**
* A stack of template sets that have been stashed temporarily.
*
* @var array
*/
protected $_configStack = [];
/**
* Contains the list of compiled templates
*
* @var array
*/
protected $_compiled = [];
/**
* Constructor.
*
* @param array $config A set of templates to add.
*/
public function __construct(array $config = [])
{
$this->add($config);
}
/**
* Push the current templates into the template stack.
*
* @return void
*/
public function push(): void
{
$this->_configStack[] = [
$this->_config,
$this->_compiled,
];
}
/**
* Restore the most recently pushed set of templates.
*
* @return void
*/
public function pop(): void
{
if (empty($this->_configStack)) {
return;
}
[$this->_config, $this->_compiled] = array_pop($this->_configStack);
}
/**
* Registers a list of templates by name
*
* ### Example:
*
* ```
* $templater->add([
* 'link' => '<a href="{{url}}">{{title}}</a>'
* 'button' => '<button>{{text}}</button>'
* ]);
* ```
*
* @param string[] $templates An associative list of named templates.
* @return $this
*/
public function add(array $templates)
{
$this->setConfig($templates);
$this->_compileTemplates(array_keys($templates));
return $this;
}
/**
* Compile templates into a more efficient printf() compatible format.
*
* @param string[] $templates The template names to compile. If empty all templates will be compiled.
* @return void
*/
protected function _compileTemplates(array $templates = []): void
{
if (empty($templates)) {
$templates = array_keys($this->_config);
}
foreach ($templates as $name) {
$template = $this->get($name);
if ($template === null) {
$this->_compiled[$name] = [null, null];
}
$template = str_replace('%', '%%', $template);
preg_match_all('#\{\{([\w\._]+)\}\}#', $template, $matches);
$this->_compiled[$name] = [
str_replace($matches[0], '%s', $template),
$matches[1],
];
}
}
/**
* Load a config file containing templates.
*
* Template files should define a `$config` variable containing
* all the templates to load. Loaded templates will be merged with existing
* templates.
*
* @param string $file The file to load
* @return void
*/
public function load(string $file): void
{
if ($file === '') {
throw new Exception('String template filename cannot be an empty string');
}
$loader = new PhpConfig();
$templates = $loader->read($file);
$this->add($templates);
}
/**
* Remove the named template.
*
* @param string $name The template to remove.
* @return void
*/
public function remove(string $name): void
{
$this->setConfig($name, null);
unset($this->_compiled[$name]);
}
/**
* Format a template string with $data
*
* @param string $name The template name.
* @param array $data The data to insert.
* @return string Formatted string
* @throws \RuntimeException If template not found.
*/
public function format(string $name, array $data): string
{
if (!isset($this->_compiled[$name])) {
throw new RuntimeException("Cannot find template named '$name'.");
}
[$template, $placeholders] = $this->_compiled[$name];
if (isset($data['templateVars'])) {
$data += $data['templateVars'];
unset($data['templateVars']);
}
$replace = [];
foreach ($placeholders as $placeholder) {
$replacement = $data[$placeholder] ?? null;
if (is_array($replacement)) {
$replacement = implode('', $replacement);
}
$replace[] = $replacement;
}
return vsprintf($template, $replace);
}
/**
* Returns a space-delimited string with items of the $options array. If a key
* of $options array happens to be one of those listed
* in `StringTemplate::$_compactAttributes` and its value is one of:
*
* - '1' (string)
* - 1 (integer)
* - true (boolean)
* - 'true' (string)
*
* Then the value will be reset to be identical with key's name.
* If the value is not one of these 4, the parameter is not output.
*
* 'escape' is a special option in that it controls the conversion of
* attributes to their HTML-entity encoded equivalents. Set to false to disable HTML-encoding.
*
* If value for any option key is set to `null` or `false`, that option will be excluded from output.
*
* This method uses the 'attribute' and 'compactAttribute' templates. Each of
* these templates uses the `name` and `value` variables. You can modify these
* templates to change how attributes are formatted.
*
* @param array|null $options Array of options.
* @param array|null $exclude Array of options to be excluded, the options here will not be part of the return.
* @return string Composed attributes.
*/
public function formatAttributes(?array $options, ?array $exclude = null): string
{
$insertBefore = ' ';
$options = (array)$options + ['escape' => true];
if (!is_array($exclude)) {
$exclude = [];
}
$exclude = ['escape' => true, 'idPrefix' => true, 'templateVars' => true, 'fieldName' => true]
+ array_flip($exclude);
$escape = $options['escape'];
$attributes = [];
foreach ($options as $key => $value) {
if (!isset($exclude[$key]) && $value !== false && $value !== null) {
$attributes[] = $this->_formatAttribute((string)$key, $value, $escape);
}
}
$out = trim(implode(' ', $attributes));
return $out ? $insertBefore . $out : '';
}
/**
* Formats an individual attribute, and returns the string value of the composed attribute.
* Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
*
* @param string $key The name of the attribute to create
* @param string|string[] $value The value of the attribute to create.
* @param bool $escape Define if the value must be escaped
* @return string The composed attribute.
*/
protected function _formatAttribute(string $key, $value, $escape = true): string
{
if (is_array($value)) {
$value = implode(' ', $value);
}
if (is_numeric($key)) {
return "$value=\"$value\"";
}
$truthy = [1, '1', true, 'true', $key];
$isMinimized = isset($this->_compactAttributes[$key]);
if (!preg_match('/\A(\w|[.-])+\z/', $key)) {
$key = h($key);
}
if ($isMinimized && in_array($value, $truthy, true)) {
return "$key=\"$key\"";
}
if ($isMinimized) {
return '';
}
return $key . '="' . ($escape ? h($value) : $value) . '"';
}
/**
* Adds a class and returns a unique list either in array or space separated
*
* @param array|string $input The array or string to add the class to
* @param array|string $newClass the new class or classes to add
* @param string $useIndex if you are inputting an array with an element other than default of 'class'.
* @return string|string[]
*/
public function addClass($input, $newClass, string $useIndex = 'class')
{
// NOOP
if (empty($newClass)) {
return $input;
}
if (is_array($input)) {
$class = Hash::get($input, $useIndex, []);
} else {
$class = $input;
$input = [];
}
// Convert and sanitise the inputs
if (!is_array($class)) {
if (is_string($class) && !empty($class)) {
$class = explode(' ', $class);
} else {
$class = [];
}
}
if (is_string($newClass)) {
$newClass = explode(' ', $newClass);
}
$class = array_unique(array_merge($class, $newClass));
$input = Hash::insert($input, $useIndex, $class);
return $input;
}
}