Completed
Pull Request — master (#20)
by Todd
03:42
created

Ebi   C

Complexity

Total Complexity 63

Size/Duplication

Total Lines 513
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 85.71%

Importance

Changes 0
Metric Value
wmc 63
lcom 2
cbo 4
dl 0
loc 513
ccs 180
cts 210
cp 0.8571
rs 5.8893
c 0
b 0
f 0

26 Methods

Rating   Name   Duplication   Size   Complexity  
A mb() 0 3 2
A componentExists() 0 9 3
A loadComponent() 0 17 3
A cacheKeyExists() 0 4 1
A compile() 0 11 1
A includeComponent() 0 14 3
A requireFile() 0 3 1
A defineComponent() 0 3 1
A render() 0 13 2
A setErrorReporting() 0 4 1
A call() 0 7 2
A getMeta() 0 3 2
A setMeta() 0 4 1
A getTemplateLoader() 0 3 1
A setTemplateLoader() 0 4 1
A getMetaArray() 0 3 1
A setMetaArray() 0 4 1
A __construct() 0 56 2
A defineFunction() 0 8 2
A write() 0 16 3
A lookup() 0 16 3
A componentKey() 0 6 2
B filePutContents() 0 20 5
B attributeClass() 0 17 6
B formatDate() 0 21 7
B attribute() 0 12 6

How to fix   Complexity   

Complex Class

Complex classes like Ebi often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Ebi, and based on these observations, apply Extract Interface, too.

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 59
    public function __construct(TemplateLoaderInterface $templateLoader, $cachePath, CompilerInterface $compiler = null) {
45 59
        $this->templateLoader = $templateLoader;
46 59
        $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 59
        $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 59
        $this->defineFunction('abs');
50 59
        $this->defineFunction('arrayColumn', 'array_column');
51 59
        $this->defineFunction('arrayKeyExists', 'array_key_exists');
52 59
        $this->defineFunction('arrayKeys', 'array_keys');
53 59
        $this->defineFunction('arrayMerge', 'array_merge');
54 59
        $this->defineFunction('arrayMergeRecursive', 'array_merge_recursive');
55 59
        $this->defineFunction('arrayReplace', 'array_replace');
56 59
        $this->defineFunction('arrayReplaceRecursive', 'array_replace_recursive');
57 59
        $this->defineFunction('arrayReverse', 'array_reverse');
58 59
        $this->defineFunction('arrayValues', 'array_values');
59 59
        $this->defineFunction('base64Encode', 'base64_encode');
60 59
        $this->defineFunction('ceil');
61 59
        $this->defineFunction('componentExists', [$this, 'componentExists']);
62 59
        $this->defineFunction('count');
63 59
        $this->defineFunction('empty');
64 59
        $this->defineFunction('floor');
65 59
        $this->defineFunction('formatDate', [$this, 'formatDate']);
66 59
        $this->defineFunction('formatNumber', 'number_format');
67 59
        $this->defineFunction('htmlEncode', 'htmlspecialchars');
68 59
        $this->defineFunction('join');
69 59
        $this->defineFunction('lcase', $this->mb('strtolower'));
70 59
        $this->defineFunction('lcfirst');
71 59
        $this->defineFunction('ltrim');
72 59
        $this->defineFunction('max');
73 59
        $this->defineFunction('min');
74 59
        $this->defineFunction('queryEncode', 'http_build_query');
75 59
        $this->defineFunction('round');
76 59
        $this->defineFunction('rtrim');
77 59
        $this->defineFunction('sprintf');
78 59
        $this->defineFunction('strlen', $this->mb('strlen'));
79 59
        $this->defineFunction('substr', $this->mb('substr'));
80 59
        $this->defineFunction('trim');
81 59
        $this->defineFunction('ucase', $this->mb('strtoupper'));
82 59
        $this->defineFunction('ucfirst');
83 59
        $this->defineFunction('ucwords');
84 59
        $this->defineFunction('urlencode', 'rawurlencode');
85
86 59
        $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 59
        });
92
93
        // Define a simple component exception.
94 59
        $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 59
        });
99 59
    }
100
101
    /**
102
     * Register a runtime function.
103
     *
104
     * @param string $name The name of the function.
105
     * @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...
106
     */
107 59
    public function defineFunction($name, $function = null) {
108 59
        if ($function === null) {
109 59
            $function = $name;
110 59
        }
111
112 59
        $this->functions[strtolower($name)] = $function;
113 59
        $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...
114 59
    }
115
116 59
    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...
117 59
        return function_exists("mb_$func") ? "mb_$func" : $func;
118
    }
119
120
    /**
121
     * Write a component to the output buffer.
122
     *
123
     * @param string $component The name of the component.
124
     * @param array ...$args
125
     */
126 13
    public function write($component, ...$args) {
127 13
        $component = strtolower($component);
128
129
        try {
130 13
            $callback = $this->lookup($component);
131
132 13
            if (is_callable($callback)) {
133 13
                call_user_func($callback, ...$args);
134 13
            } else {
135 1
                $this->write('@component-not-found', ['component' => $component]);
136
            }
137 13
        } catch (\Exception $ex) {
138 1
            $this->write('@exception', ['message' => $ex->getMessage(), 'code', $ex->getCode(), 'component' => $component]);
139 1
            return;
140
        }
141 13
    }
142
143
    /**
144
     * Lookup a component with a given name.
145
     *
146
     * @param string $component The component to lookup.
147
     * @return callable|null Returns the component function or **null** if the component is not found.
148
     */
149 54
    public function lookup($component) {
150 54
        $component = strtolower($component);
151 54
        $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...
152
153 54
        if (!array_key_exists($key, $this->components)) {
154 49
            $this->loadComponent($component);
155 49
        }
156
157 54
        if (isset($this->components[$key])) {
158 53
            return $this->components[$key];
159
        } else {
160
            // Mark a tombstone to the component array so it doesn't keep getting loaded.
161 2
            $this->components[$key] = null;
162 2
            return null;
163
        }
164
    }
165
166
    /**
167
     * Check to see if a component exists.
168
     *
169
     * @param string $component The name of the component.
170
     * @param bool $loader Whether or not to use the component loader or just look in the component cache.
171
     * @return bool Returns **true** if the component exists or **false** otherwise.
172
     */
173 2
    public function componentExists($component, $loader = true) {
174 2
        $componentKey = $this->componentKey($component);
175 2
        if (array_key_exists($componentKey, $this->components)) {
176 1
            return $this->components[$componentKey] !== null;
177 2
        } elseif ($loader) {
178 2
            return !empty($this->templateLoader->cacheKey($component));
179
        }
180 1
        return false;
181
    }
182
183
    /**
184
     * Strip the namespace off a component name to get the component key.
185
     *
186
     * @param string $component The full name of the component with a possible namespace.
187
     * @return string Returns the component key.
188
     */
189 56
    protected function componentKey($component) {
190 56
        if (false !== $pos = strpos($component, ':')) {
191 1
            $component = substr($component, $pos + 1);
192 1
        }
193 56
        return strtolower($component);
194
    }
195
196
    /**
197
     * Load a component.
198
     *
199
     * @param string $component The name of the component to load.
200
     * @return callable|null Returns the component or **null** if the component isn't found.
201
     */
202 49
    protected function loadComponent($component) {
203 49
        $cacheKey = $this->templateLoader->cacheKey($component);
204
        // The template loader can tell us a template doesn't exist when giving the cache key.
205 49
        if (empty($cacheKey)) {
206 2
            return null;
207
        }
208
209 47
        $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...
210 47
        $componentKey = $this->componentKey($component);
211
212 47
        if (!file_exists($cachePath)) {
213 47
            $src = $this->templateLoader->load($component);
214 47
            return $this->compile($componentKey, $src, $cacheKey);
215
        } else {
216
            return $this->includeComponent($componentKey, $cachePath);
217
        }
218
    }
219
220
    /**
221
     * Check to see if a specific cache key exists in the cache.
222
     *
223
     * @param string $cacheKey The cache key to check.
224
     * @return bool Returns **true** if there is a cache key at the file or **false** otherwise.
225
     */
226 1
    public function cacheKeyExists($cacheKey) {
227 1
        $cachePath = "{$this->cachePath}/$cacheKey.php";
228 1
        return file_exists($cachePath);
229
    }
230
231
    /**
232
     * Compile a component from source, cache it and include it.
233
     *
234
     * @param string $component The name of the component.
235
     * @param string $src The component source.
236
     * @param string $cacheKey The cache key of the component.
237
     * @return callable|null Returns the compiled component closure.
238
     */
239 51
    public function compile($component, $src, $cacheKey) {
240 51
        $cachePath = "{$this->cachePath}/$cacheKey.php";
241 51
        $component = strtolower($component);
242
243 51
        $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...
244 51
        $comment = "/*\n".str_replace('*/', '❄/', trim($src))."\n*/";
245
246 51
        $this->filePutContents($cachePath, "<?php\n$comment\n$php");
247
248 51
        return $this->includeComponent($component, $cachePath);
249
    }
250
251
    /**
252
     * Include a cached component.
253
     *
254
     * @param string $component The component key.
255
     * @param string $cachePath The path to the component.
256
     * @return callable|null Returns the component function or **null** if the component wasn't properly defined.
257
     */
258 51
    private function includeComponent($component, $cachePath) {
259 51
        unset($this->components[$component]);
260 51
        $fn = $this->requireFile($cachePath);
261
262 51
        if (isset($this->components[$component])) {
263 51
            return $this->components[$component];
264
        } elseif (is_callable($fn)) {
265
            $this->defineComponent($component, $fn);
266
            return $fn;
267
        } else {
268
            $this->components[$component] = null;
269
            return null;
270
        }
271
    }
272
273
    /**
274
     * A safe version of {@link file_put_contents()} that also clears op caches.
275
     *
276
     * @param string $path The path to save to.
277
     * @param string $contents The contents of the file.
278
     * @return bool Returns **true** on success or **false** on failure.
279
     */
280 51
    private function filePutContents($path, $contents) {
281 51
        if (!file_exists(dirname($path))) {
282 4
            mkdir(dirname($path), 0777, true);
283 4
        }
284 51
        $tmpPath = tempnam(dirname($path), 'ebi-');
285 51
        $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...
286 51
        if (file_put_contents($tmpPath, $contents) !== false) {
287 51
            chmod($tmpPath, 0664);
288 51
            $r = rename($tmpPath, $path);
289 51
        }
290
291 51
        if (function_exists('apc_delete_file')) {
292
            // This fixes a bug with some configurations of apc.
293
            @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...
294 51
        } elseif (function_exists('opcache_invalidate')) {
295 51
            @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...
296 51
        }
297
298 51
        return $r;
299
    }
300
301
    /**
302
     * Include a file.
303
     *
304
     * This is method is useful for including a file bound to this object instance.
305
     *
306
     * @param string $path The path to the file to include.
307
     * @return mixed Returns the result of the include.
308
     */
309 51
    public function requireFile($path) {
310 51
        return require $path;
311
    }
312
313
    /**
314
     * Register a component.
315
     *
316
     * @param string $name The name of the component to register.
317
     * @param callable $component The component function.
318
     */
319 59
    public function defineComponent($name, callable $component) {
320 59
        $this->components[$name] = $component;
321 59
    }
322
323
    /**
324
     * Render a component to a string.
325
     *
326
     * @param string $component The name of the component to render.
327
     * @param array ...$args Arguments to pass to the component.
328
     * @return string|null Returns the rendered component or **null** if the component was not found.
329
     */
330 50
    public function render($component, ...$args) {
331 50
        if ($callback = $this->lookup($component)) {
332 50
            ob_start();
333 50
            $errs = error_reporting(error_reporting() & ~E_NOTICE & ~E_WARNING);
334 50
            call_user_func($callback, ...$args);
335 50
            error_reporting($errs);
336 50
            $str = ob_get_clean();
337 50
            return $str;
338
        } else {
339
            trigger_error("Could not find component $component.", E_USER_NOTICE);
340
            return null;
341
        }
342
    }
343
344
    /**
345
     * Set the error reporting appropriate for template rendering.
346
     *
347
     * @return int Returns the previous error level.
348
     */
349
    public function setErrorReporting() {
350
        $errs = error_reporting(error_reporting() & ~E_NOTICE & ~E_WARNING);
351
        return $errs;
352
    }
353
354
    /**
355
     * Call a function registered with **defineFunction()**.
356
     *
357
     * If a static or global function is registered then it's simply rendered in the compiled template.
358
     * This method is for closures or callbacks.
359
     *
360
     * @param string $name The name of the registered function.
361
     * @param array ...$args The function's argument.
362
     * @return mixed Returns the result of the function
363
     * @throws RuntimeException Throws an exception when the function isn't found.
364
     */
365 3
    public function call($name, ...$args) {
366 3
        if (!isset($this->functions[$name])) {
367 1
            throw new RuntimeException("Call to undefined function $name.", 500);
368
        } else {
369 2
            return $this->functions[$name](...$args);
370
        }
371
    }
372
373
    /**
374
     * Render a variable appropriately for CSS.
375
     *
376
     * This is a convenience runtime function.
377
     *
378
     * @param string|array $expr A CSS class, an array of CSS classes, or an associative array where the keys are class
379
     * names and the values are truthy conditions to include the class (or not).
380
     * @return string Returns a space-delimited CSS class string.
381
     */
382 6
    public function attributeClass($expr) {
383 6
        if (is_array($expr)) {
384 3
            $classes = [];
385 3
            foreach ($expr as $i => $val) {
386 3
                if (is_array($val)) {
387 1
                    $classes[] = $this->attributeClass($val);
388 3
                } elseif (is_int($i)) {
389 1
                    $classes[] = $val;
390 3
                } elseif (!empty($val)) {
391 2
                    $classes[] = $i;
392 2
                }
393 3
            }
394 3
            return implode(' ', $classes);
395
        } else {
396 3
            return (string)$expr;
397
        }
398
    }
399
400
    /**
401
     * Format a data.
402
     *
403
     * @param mixed $date The date to format. This can be a string data, a timestamp or an instance of **DateTimeInterface**.
404
     * @param string $format The format of the date.
405
     * @return string Returns the formatted data.
406
     * @see date_format()
407
     */
408 1
    public function formatDate($date, $format = 'c') {
409 1
        if (is_string($date)) {
410
            try {
411 1
                $date = new \DateTimeImmutable($date);
412 1
            } catch (\Exception $ex) {
413
                return '#error#';
414
            }
415 1
        } elseif (empty($date)) {
416
            return '';
417
        } elseif (is_int($date)) {
418
            try {
419
                $date = new \DateTimeImmutable('@'.$date);
420
            } catch (\Exception $ex) {
421
                return '#error#';
422
            }
423
        } elseif (!$date instanceof \DateTimeInterface) {
424
            return '#error#';
425
        }
426
427 1
        return $date->format($format);
428
    }
429
430
    /**
431
     * Get a single item from the meta array.
432
     *
433
     * @param string $name The key to get from.
434
     * @param mixed $default The default value if no item at the key exists.
435
     * @return mixed Returns the meta value.
436
     */
437
    public function getMeta($name, $default = null) {
438
        return isset($this->meta[$name]) ? $this->meta[$name] : $default;
439
    }
440
441
    /**
442
     * Set a single item to the meta array.
443
     *
444
     * @param string $name The key to set.
445
     * @param mixed $value The new value.
446
     * @return $this
447
     */
448 1
    public function setMeta($name, $value) {
449 1
        $this->meta[$name] = $value;
450 1
        return $this;
451
    }
452
453
    /**
454
     * Get the template loader.
455
     *
456
     * The template loader translates component names into template contents.
457
     *
458
     * @return TemplateLoaderInterface Returns the template loader.
459
     */
460 1
    public function getTemplateLoader() {
461 1
        return $this->templateLoader;
462
    }
463
464
    /**
465
     * Set the template loader.
466
     *
467
     * The template loader translates component names into template contents.
468
     *
469
     * @param TemplateLoaderInterface $templateLoader The new template loader.
470
     * @return $this
471
     */
472
    public function setTemplateLoader($templateLoader) {
473
        $this->templateLoader = $templateLoader;
474
        return $this;
475
    }
476
477
    /**
478
     * Get the entire meta array.
479
     *
480
     * @return array Returns the meta.
481
     */
482
    public function getMetaArray() {
483
        return $this->meta;
484
    }
485
486
    /**
487
     * Set the entire meta array.
488
     *
489
     * @param array $meta The new meta array.
490
     * @return $this
491
     */
492
    public function setMetaArray(array $meta) {
493
        $this->meta = $meta;
494
        return $this;
495
    }
496
497
    /**
498
     * Return a dynamic attribute.
499
     *
500
     * The attribute renders differently depending on the value.
501
     *
502
     * - If the value is **true** then it will render as an HTML5 boolean attribute.
503
     * - If the value is **false** or **null** then the attribute will not render.
504
     * - Other values render as attribute values.
505
     * - Attributes that start with **aria-** render **true** and **false** as values.
506
     *
507
     * @param string $name The name of the attribute.
508
     * @param mixed $value The value of the attribute.
509
     * @return string Returns the attribute definition or an empty string.
510
     */
511 15
    protected function attribute($name, $value) {
512 15
        if (substr($name, 0, 5) === 'aria-' && is_bool($value)) {
513 2
            $value = $value ? 'true' : 'false';
514 2
        }
515
516 15
        if ($value === true) {
517 1
            return ' '.$name;
518 14
        } elseif (!in_array($value, [null, false], true)) {
519 11
            return " $name=\"".htmlspecialchars($value).'"';
520
        }
521 4
        return '';
522
    }
523
}
524