Completed
Push — master ( 8ce59e...d8c71a )
by Todd
04:50
created

Ebi::filePutContents()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0061

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 15
cts 16
cp 0.9375
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 13
nc 12
nop 2
crap 5.0061
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2017 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Ebi;
9
10
11
class Ebi {
12
    /**
13
     * @var string
14
     */
15
    protected $cachePath;
16
    /**
17
     * @var callable[]
18
     */
19
    protected $functions;
20
    /**
21
     * @var TemplateLoaderInterface
22
     */
23
    private $templateLoader;
24
    /**
25
     * @var CompilerInterface
26
     */
27
    private $compiler;
28
    /**
29
     * @var callable[]
30
     */
31
    private $components = [];
32
    /**
33
     * @var array
34
     */
35
    private $meta;
36
37
    /**
38
     * Ebi constructor.
39
     *
40
     * @param TemplateLoaderInterface $templateLoader Used to load template sources from component names.
41
     * @param string $cachePath The path to cache compiled templates.
42
     * @param CompilerInterface $compiler The compiler used to compile templates.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $compiler not be null|CompilerInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
43
     */
44 72
    public function __construct(TemplateLoaderInterface $templateLoader, $cachePath, CompilerInterface $compiler = null) {
45 72
        $this->templateLoader = $templateLoader;
46 72
        $this->cachePath = $cachePath;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
47 72
        $this->compiler = $compiler ?: new Compiler();
0 ignored issues
show
Documentation Bug introduced by
It seems like $compiler ?: new \Ebi\Compiler() can also be of type object<Ebi\Compiler>. However, the property $compiler is declared as type object<Ebi\CompilerInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
48
49 72
        $this->defineFunction('abs');
50 72
        $this->defineFunction('arrayColumn', 'array_column');
51 72
        $this->defineFunction('arrayKeyExists', 'array_key_exists');
52 72
        $this->defineFunction('arrayKeys', 'array_keys');
53 72
        $this->defineFunction('arrayMerge', 'array_merge');
54 72
        $this->defineFunction('arrayMergeRecursive', 'array_merge_recursive');
55 72
        $this->defineFunction('arrayReplace', 'array_replace');
56 72
        $this->defineFunction('arrayReplaceRecursive', 'array_replace_recursive');
57 72
        $this->defineFunction('arrayReverse', 'array_reverse');
58 72
        $this->defineFunction('arrayValues', 'array_values');
59 72
        $this->defineFunction('base64Encode', 'base64_encode');
60 72
        $this->defineFunction('ceil');
61 72
        $this->defineFunction('componentExists', [$this, 'componentExists']);
62 72
        $this->defineFunction('count');
63 72
        $this->defineFunction('empty');
64 72
        $this->defineFunction('floor');
65 72
        $this->defineFunction('formatDate', [$this, 'formatDate']);
66 72
        $this->defineFunction('formatNumber', 'number_format');
67 72
        $this->defineFunction('htmlEncode', 'htmlspecialchars');
68 72
        $this->defineFunction('join');
69 72
        $this->defineFunction('lcase', $this->mb('strtolower'));
70 72
        $this->defineFunction('lcfirst');
71 72
        $this->defineFunction('ltrim');
72 72
        $this->defineFunction('max');
73 72
        $this->defineFunction('min');
74 72
        $this->defineFunction('queryEncode', 'http_build_query');
75 72
        $this->defineFunction('round');
76 72
        $this->defineFunction('rtrim');
77 72
        $this->defineFunction('sprintf');
78 72
        $this->defineFunction('strlen', $this->mb('strlen'));
79 72
        $this->defineFunction('substr', $this->mb('substr'));
80 72
        $this->defineFunction('trim');
81 72
        $this->defineFunction('ucase', $this->mb('strtoupper'));
82 72
        $this->defineFunction('ucfirst');
83 72
        $this->defineFunction('ucwords');
84 72
        $this->defineFunction('urlencode', 'rawurlencode');
85
86 72
        $this->defineFunction('@class', [$this, 'attributeClass']);
87
88
        // Define a simple component not found component to help troubleshoot.
89
        $this->defineComponent('@component-not-found', function ($props) {
90 1
            echo '<!-- Ebi component "'.htmlspecialchars($props['component']).'" not found. -->';
91 72
        });
92
93
        // Define a simple component exception.
94
        $this->defineComponent('@exception', function ($props) {
95 1
            echo "\n<!--\nEbi exception in component \"".htmlspecialchars($props['component'])."\".\n".
96 1
                htmlspecialchars($props['message'])."\n-->\n";
97
98 72
        });
99
100 72
        $this->defineComponent('@compile-exception', [$this, 'writeCompileException']);
101 72
    }
102
103
    /**
104
     * Register a runtime function.
105
     *
106
     * @param string $name The name of the function.
107
     * @param callable $function The function callback.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $function not be callable|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
108
     */
109 72
    public function defineFunction($name, $function = null) {
110 72
        if ($function === null) {
111 72
            $function = $name;
112 72
        }
113
114 72
        $this->functions[strtolower($name)] = $function;
115 72
        $this->compiler->defineFunction($name, $function);
0 ignored issues
show
Bug introduced by
The method defineFunction() does not seem to exist on object<Ebi\CompilerInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
116 72
    }
117
118 72
    private function mb($func) {
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
119 72
        return function_exists("mb_$func") ? "mb_$func" : $func;
120
    }
121
122
    /**
123
     * Write a component to the output buffer.
124
     *
125
     * @param string $component The name of the component.
126
     * @param array ...$args
127
     */
128 22
    public function write($component, ...$args) {
129 22
        $component = strtolower($component);
130
131
        try {
132 22
            $callback = $this->lookup($component);
133
134 22
            if (is_callable($callback)) {
135 22
                call_user_func($callback, ...$args);
136 22
            } else {
137 1
                $this->write('@component-not-found', ['component' => $component]);
138
            }
139 22
        } catch (\Throwable $ex) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
140
            $this->write('@exception', ['message' => $ex->getMessage(), 'code', $ex->getCode(), 'component' => $component]);
141
            return;
142 1
        } catch (\Exception $ex) {
143 1
            $this->write('@exception', ['message' => $ex->getMessage(), 'code', $ex->getCode(), 'component' => $component]);
144 1
            return;
145
        }
146 22
    }
147
148
    /**
149
     * Lookup a component with a given name.
150
     *
151
     * @param string $component The component to lookup.
152
     * @return callable|null Returns the component function or **null** if the component is not found.
153
     */
154 67
    public function lookup($component) {
155 67
        $component = strtolower($component);
156 67
        $key = $this->componentKey($component);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
157
158 67
        if (!array_key_exists($key, $this->components)) {
159 62
            $this->loadComponent($component);
160 62
        }
161
162 67
        if (isset($this->components[$key])) {
163 66
            return $this->components[$key];
164
        } else {
165
            // Mark a tombstone to the component array so it doesn't keep getting loaded.
166 2
            $this->components[$key] = null;
167 2
            return null;
168
        }
169
    }
170
171
    /**
172
     * Check to see if a component exists.
173
     *
174
     * @param string $component The name of the component.
175
     * @param bool $loader Whether or not to use the component loader or just look in the component cache.
176
     * @return bool Returns **true** if the component exists or **false** otherwise.
177
     */
178 2
    public function componentExists($component, $loader = true) {
179 2
        $componentKey = $this->componentKey($component);
180 2
        if (array_key_exists($componentKey, $this->components)) {
181 1
            return $this->components[$componentKey] !== null;
182 2
        } elseif ($loader) {
183 2
            return !empty($this->templateLoader->cacheKey($component));
184
        }
185 1
        return false;
186
    }
187
188
    /**
189
     * Strip the namespace off a component name to get the component key.
190
     *
191
     * @param string $component The full name of the component with a possible namespace.
192
     * @return string Returns the component key.
193
     */
194 69
    protected function componentKey($component) {
195 69
        if (false !== $pos = strpos($component, ':')) {
196 1
            $component = substr($component, $pos + 1);
197 1
        }
198 69
        return strtolower($component);
199
    }
200
201
    /**
202
     * Load a component.
203
     *
204
     * @param string $component The name of the component to load.
205
     * @return callable|null Returns the component or **null** if the component isn't found.
206
     */
207 62
    protected function loadComponent($component) {
208 62
        $cacheKey = $this->templateLoader->cacheKey($component);
209
        // The template loader can tell us a template doesn't exist when giving the cache key.
210 62
        if (empty($cacheKey)) {
211 2
            return null;
212
        }
213
214 60
        $cachePath = "{$this->cachePath}/$cacheKey.php";
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
215 60
        $componentKey = $this->componentKey($component);
216
217 60
        if (!file_exists($cachePath)) {
218 60
            $src = $this->templateLoader->load($component);
219
            try {
220 60
                return $this->compile($componentKey, $src, $cacheKey);
221 8
            } catch (CompileException $ex) {
222 8
                $props = ['message' => $ex->getMessage()] + $ex->getContext();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 34 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
223 8
                return $this->components[$componentKey] = function() use ($props) {
224 8
                    $this->write('@compile-exception', $props);
225 8
                };
226
            }
227
        } else {
228
            return $this->includeComponent($componentKey, $cachePath);
229
        }
230
    }
231
232 8
    protected function writeCompileException($props) {
233 8
        echo "\n<section class=\"ebi-ex\">\n",
234 8
            '<h2>Error compiling '.htmlspecialchars($props['path'])." near line {$props['line']}.</h2>\n";
235
236 8
        echo '<p class="ebi-ex-message">'.htmlspecialchars($props['message'])."</p>\n";
237
238 8
        if (!empty($props['source'])) {
239 6
            $source = $props['source'];
240 6
            if (isset($props['sourcePosition'])) {
241 3
                $pos = $props['sourcePosition'];
242 3
                $len = isset($props['sourceLength']) ? $props['sourceLength'] : 1;
243
244 3
                if ($len === 1) {
245
                    // Small kludge to select a viewable character.
246 3
                    for (; $pos >= 0 && isset($source[$pos]) && in_array($source[$pos], [' ', "\n"], true); $pos--, $len++) {
0 ignored issues
show
Unused Code introduced by
This for loop is empty and can be removed.

This check looks for for loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
247
                        // It's all in the loop.
248 1
                    }
249 3
                }
250
251 3
                $source = htmlspecialchars(substr($source, 0, $pos)).
252 3
                    '<mark class="ebi-ex-highlight">'.htmlspecialchars(substr($source, $pos, $len)).'</mark>'.
253 3
                    htmlspecialchars(substr($source, $pos + $len));
254 3
            } else {
255 3
                $source = htmlspecialchars($source);
256
            }
257
258 6
            echo '<pre class="ebi-ex-source ebi-ex-context"><code>',
259
                $source,
260
                "</code></pre>\n";
261 6
        }
262
263 8
        if (!empty($props['lines'])) {
264 8
            echo '<pre class="ebi-ex-source ebi-ex-lines">';
265
266 8
            foreach ($props['lines'] as $i => $line) {
267 8
                echo '<code class="ebi-ex-line">';
268
269 8
                $str = sprintf("%3d. %s", $i, htmlspecialchars($line));
270 8
                if ($i === $props['line']) {
271 8
                    echo "<mark class=\"ebi-ex-highlight\">$str</mark>";
272 8
                } else {
273 6
                    echo $str;
274
                }
275
276 8
                echo "</code>\n";
277 8
            }
278
279 8
            echo "</pre>\n";
280 8
        }
281
282 8
        echo "</section>\n";
283 8
    }
284
285
    /**
286
     * Check to see if a specific cache key exists in the cache.
287
     *
288
     * @param string $cacheKey The cache key to check.
289
     * @return bool Returns **true** if there is a cache key at the file or **false** otherwise.
290
     */
291 1
    public function cacheKeyExists($cacheKey) {
292 1
        $cachePath = "{$this->cachePath}/$cacheKey.php";
293 1
        return file_exists($cachePath);
294
    }
295
296
    /**
297
     * Compile a component from source, cache it and include it.
298
     *
299
     * @param string $component The name of the component.
300
     * @param string $src The component source.
301
     * @param string $cacheKey The cache key of the component.
302
     * @return callable|null Returns the compiled component closure.
303
     */
304 64
    public function compile($component, $src, $cacheKey) {
305 64
        $cachePath = "{$this->cachePath}/$cacheKey.php";
306 64
        $component = strtolower($component);
307
308 64
        $php = $this->compiler->compile($src, ['basename' => $component, 'path' => $cacheKey]);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
309 56
        $comment = "/*\n".str_replace('*/', '❄/', trim($src))."\n*/";
310
311 56
        $this->filePutContents($cachePath, "<?php\n$comment\n$php");
312
313 56
        return $this->includeComponent($component, $cachePath);
314
    }
315
316
    /**
317
     * Include a cached component.
318
     *
319
     * @param string $component The component key.
320
     * @param string $cachePath The path to the component.
321
     * @return callable|null Returns the component function or **null** if the component wasn't properly defined.
322
     */
323 56
    private function includeComponent($component, $cachePath) {
324 56
        unset($this->components[$component]);
325 56
        $fn = $this->requireFile($cachePath);
326
327 56
        if (isset($this->components[$component])) {
328 56
            return $this->components[$component];
329
        } elseif (is_callable($fn)) {
330
            $this->defineComponent($component, $fn);
331
            return $fn;
332
        } else {
333
            $this->components[$component] = null;
334
            return null;
335
        }
336
    }
337
338
    /**
339
     * A safe version of {@link file_put_contents()} that also clears op caches.
340
     *
341
     * @param string $path The path to save to.
342
     * @param string $contents The contents of the file.
343
     * @return bool Returns **true** on success or **false** on failure.
344
     */
345 56
    private function filePutContents($path, $contents) {
346 56
        if (!file_exists(dirname($path))) {
347 4
            mkdir(dirname($path), 0777, true);
348 4
        }
349 56
        $tmpPath = tempnam(dirname($path), 'ebi-');
350 56
        $r = false;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
351 56
        if (file_put_contents($tmpPath, $contents) !== false) {
352 56
            chmod($tmpPath, 0664);
353 56
            $r = rename($tmpPath, $path);
354 56
        }
355
356 56
        if (function_exists('apc_delete_file')) {
357
            // This fixes a bug with some configurations of apc.
358
            @apc_delete_file($path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
359 56
        } elseif (function_exists('opcache_invalidate')) {
360 56
            @opcache_invalidate($path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
361 56
        }
362
363 56
        return $r;
364
    }
365
366
    /**
367
     * Include a file.
368
     *
369
     * This is method is useful for including a file bound to this object instance.
370
     *
371
     * @param string $path The path to the file to include.
372
     * @return mixed Returns the result of the include.
373
     */
374 56
    public function requireFile($path) {
375 56
        return require $path;
376
    }
377
378
    /**
379
     * Register a component.
380
     *
381
     * @param string $name The name of the component to register.
382
     * @param callable $component The component function.
383
     */
384 72
    public function defineComponent($name, callable $component) {
385 72
        $this->components[$name] = $component;
386 72
    }
387
388
    /**
389
     * Render a component to a string.
390
     *
391
     * @param string $component The name of the component to render.
392
     * @param array ...$args Arguments to pass to the component.
393
     * @return string|null Returns the rendered component or **null** if the component was not found.
394
     */
395 63
    public function render($component, ...$args) {
396 63
        if ($callback = $this->lookup($component)) {
397 63
            ob_start();
398 63
            $errs = error_reporting(error_reporting() & ~E_NOTICE & ~E_WARNING);
399 63
            call_user_func($callback, ...$args);
400 63
            error_reporting($errs);
401 63
            $str = ob_get_clean();
402 63
            return $str;
403
        } else {
404
            trigger_error("Could not find component $component.", E_USER_NOTICE);
405
            return null;
406
        }
407
    }
408
409
    /**
410
     * Set the error reporting appropriate for template rendering.
411
     *
412
     * @return int Returns the previous error level.
413
     */
414
    public function setErrorReporting() {
415
        $errs = error_reporting(error_reporting() & ~E_NOTICE & ~E_WARNING);
416
        return $errs;
417
    }
418
419
    /**
420
     * Call a function registered with **defineFunction()**.
421
     *
422
     * If a static or global function is registered then it's simply rendered in the compiled template.
423
     * This method is for closures or callbacks.
424
     *
425
     * @param string $name The name of the registered function.
426
     * @param array ...$args The function's argument.
427
     * @return mixed Returns the result of the function
428
     * @throws RuntimeException Throws an exception when the function isn't found.
429
     */
430 3
    public function call($name, ...$args) {
431 3
        if (!isset($this->functions[$name])) {
432 1
            throw new RuntimeException("Call to undefined function $name.", 500);
433
        } else {
434 2
            return $this->functions[$name](...$args);
435
        }
436
    }
437
438
    /**
439
     * Render a variable appropriately for CSS.
440
     *
441
     * This is a convenience runtime function.
442
     *
443
     * @param string|array $expr A CSS class, an array of CSS classes, or an associative array where the keys are class
444
     * names and the values are truthy conditions to include the class (or not).
445
     * @return string Returns a space-delimited CSS class string.
446
     */
447 6
    public function attributeClass($expr) {
448 6
        if (is_array($expr)) {
449 3
            $classes = [];
450 3
            foreach ($expr as $i => $val) {
451 3
                if (is_array($val)) {
452 1
                    $classes[] = $this->attributeClass($val);
453 3
                } elseif (is_int($i)) {
454 1
                    $classes[] = $val;
455 3
                } elseif (!empty($val)) {
456 2
                    $classes[] = $i;
457 2
                }
458 3
            }
459 3
            return implode(' ', $classes);
460
        } else {
461 3
            return (string)$expr;
462
        }
463
    }
464
465
    /**
466
     * Format a data.
467
     *
468
     * @param mixed $date The date to format. This can be a string data, a timestamp or an instance of **DateTimeInterface**.
469
     * @param string $format The format of the date.
470
     * @return string Returns the formatted data.
471
     * @see date_format()
472
     */
473 1
    public function formatDate($date, $format = 'c') {
474 1
        if (is_string($date)) {
475
            try {
476 1
                $date = new \DateTimeImmutable($date);
477 1
            } catch (\Exception $ex) {
478
                return '#error#';
479
            }
480 1
        } elseif (empty($date)) {
481
            return '';
482
        } elseif (is_int($date)) {
483
            try {
484
                $date = new \DateTimeImmutable('@'.$date);
485
            } catch (\Exception $ex) {
486
                return '#error#';
487
            }
488
        } elseif (!$date instanceof \DateTimeInterface) {
489
            return '#error#';
490
        }
491
492 1
        return $date->format($format);
493
    }
494
495
    /**
496
     * Get a single item from the meta array.
497
     *
498
     * @param string $name The key to get from.
499
     * @param mixed $default The default value if no item at the key exists.
500
     * @return mixed Returns the meta value.
501
     */
502
    public function getMeta($name, $default = null) {
503
        return isset($this->meta[$name]) ? $this->meta[$name] : $default;
504
    }
505
506
    /**
507
     * Set a single item to the meta array.
508
     *
509
     * @param string $name The key to set.
510
     * @param mixed $value The new value.
511
     * @return $this
512
     */
513 1
    public function setMeta($name, $value) {
514 1
        $this->meta[$name] = $value;
515 1
        return $this;
516
    }
517
518
    /**
519
     * Get the template loader.
520
     *
521
     * The template loader translates component names into template contents.
522
     *
523
     * @return TemplateLoaderInterface Returns the template loader.
524
     */
525 1
    public function getTemplateLoader() {
526 1
        return $this->templateLoader;
527
    }
528
529
    /**
530
     * Set the template loader.
531
     *
532
     * The template loader translates component names into template contents.
533
     *
534
     * @param TemplateLoaderInterface $templateLoader The new template loader.
535
     * @return $this
536
     */
537
    public function setTemplateLoader($templateLoader) {
538
        $this->templateLoader = $templateLoader;
539
        return $this;
540
    }
541
542
    /**
543
     * Get the entire meta array.
544
     *
545
     * @return array Returns the meta.
546
     */
547
    public function getMetaArray() {
548
        return $this->meta;
549
    }
550
551
    /**
552
     * Set the entire meta array.
553
     *
554
     * @param array $meta The new meta array.
555
     * @return $this
556
     */
557
    public function setMetaArray(array $meta) {
558
        $this->meta = $meta;
559
        return $this;
560
    }
561
562
    /**
563
     * Return a dynamic attribute.
564
     *
565
     * The attribute renders differently depending on the value.
566
     *
567
     * - If the value is **true** then it will render as an HTML5 boolean attribute.
568
     * - If the value is **false** or **null** then the attribute will not render.
569
     * - Other values render as attribute values.
570
     * - Attributes that start with **aria-** render **true** and **false** as values.
571
     *
572
     * @param string $name The name of the attribute.
573
     * @param mixed $value The value of the attribute.
574
     * @return string Returns the attribute definition or an empty string.
575
     */
576 15
    public function attribute($name, $value) {
577 15
        if (substr($name, 0, 5) === 'aria-' && is_bool($value)) {
578 2
            $value = $value ? 'true' : 'false';
579 2
        }
580
581 15
        if ($value === true) {
582 1
            return ' '.$name;
583 14
        } elseif (!in_array($value, [null, false], true)) {
584 11
            return " $name=\"".htmlspecialchars($value).'"';
585
        }
586 4
        return '';
587
    }
588
589
    /**
590
     * Escape a value for echoing to HTML with a bit of non-scalar checking.
591
     *
592
     * @param mixed $val The value to escape.
593
     * @return string The escaped value.
594
     */
595 25
    public function escape($val = null) {
596 25
        if (is_array($val)) {
597 1
            return '[array]';
598 25
        } elseif ($val instanceof \DateTimeInterface) {
599 1
            return htmlspecialchars($val->format(\DateTime::RFC3339));
600 25
        } elseif (is_object($val) && !method_exists($val, '__toString')) {
601 1
            return '{object}';
602
        } else {
603 25
            return htmlspecialchars($val);
604
        }
605
    }
606
607
    /**
608
     * Write children blocks.
609
     *
610
     * @param array|callable|null $children The children blocks to write.
611
     */
612 4
    public function writeChildren($children) {
613 4
        if (empty($children)) {
614
            return;
615 4
        } elseif (is_array($children)) {
616 1
            array_map([$this, 'writeChildren'], $children);
617 1
        } else {
618 4
            $children();
619
        }
620 4
    }
621
}
622