Completed
Push — master ( b380ba...d8b52d )
by Todd
11s
created

Ebi::attribute()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 8
nc 9
nop 2
crap 6
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 57
    public function __construct(TemplateLoaderInterface $templateLoader, $cachePath, CompilerInterface $compiler = null) {
45 57
        $this->templateLoader = $templateLoader;
46 57
        $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 57
        $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 57
        $this->defineFunction('abs');
50 57
        $this->defineFunction('arrayColumn', 'array_column');
51 57
        $this->defineFunction('arrayKeyExists', 'array_key_exists');
52 57
        $this->defineFunction('arrayKeys', 'array_keys');
53 57
        $this->defineFunction('arrayMerge', 'array_merge');
54 57
        $this->defineFunction('arrayMergeRecursive', 'array_merge_recursive');
55 57
        $this->defineFunction('arrayReplace', 'array_replace');
56 57
        $this->defineFunction('arrayReplaceRecursive', 'array_replace_recursive');
57 57
        $this->defineFunction('arrayReverse', 'array_reverse');
58 57
        $this->defineFunction('arrayValues', 'array_values');
59 57
        $this->defineFunction('base64Encode', 'base64_encode');
60 57
        $this->defineFunction('ceil');
61 57
        $this->defineFunction('componentExists', [$this, 'componentExists']);
62 57
        $this->defineFunction('count');
63 57
        $this->defineFunction('empty');
64 57
        $this->defineFunction('floor');
65 57
        $this->defineFunction('formatDate', [$this, 'formatDate']);
66 57
        $this->defineFunction('formatNumber', 'number_format');
67 57
        $this->defineFunction('htmlEncode', 'htmlspecialchars');
68 57
        $this->defineFunction('join');
69 57
        $this->defineFunction('lcase', $this->mb('strtolower'));
70 57
        $this->defineFunction('lcfirst');
71 57
        $this->defineFunction('ltrim');
72 57
        $this->defineFunction('max');
73 57
        $this->defineFunction('min');
74 57
        $this->defineFunction('queryEncode', 'http_build_query');
75 57
        $this->defineFunction('round');
76 57
        $this->defineFunction('rtrim');
77 57
        $this->defineFunction('sprintf');
78 57
        $this->defineFunction('strlen', $this->mb('strlen'));
79 57
        $this->defineFunction('substr', $this->mb('substr'));
80 57
        $this->defineFunction('trim');
81 57
        $this->defineFunction('ucase', $this->mb('strtoupper'));
82 57
        $this->defineFunction('ucfirst');
83 57
        $this->defineFunction('ucwords');
84 57
        $this->defineFunction('urlencode', 'rawurlencode');
85
86 57
        $this->defineFunction('@class', [$this, 'attributeClass']);
87
88
        // Define a simple component not found component to help troubleshoot.
89 57
        $this->defineComponent('@component-not-found', function ($props) {
90 1
            echo '<!-- Component "'.htmlspecialchars($props['component']).'" not found. -->';
91 57
        });
92
93
        // Define a simple component exception.
94 57
        $this->defineComponent('@exception', function ($props) {
95 1
            echo "\n<!--\nException in component \"".htmlspecialchars($props['component'])."\"\n".
96 1
                htmlspecialchars($props['message'])."\n-->\n";
97
98 57
        });
99 57
    }
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 57
    public function defineFunction($name, $function = null) {
108 57
        if ($function === null) {
109 57
            $function = $name;
110
        }
111
112 57
        $this->functions[strtolower($name)] = $function;
113 57
        $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 57
    }
115
116 57
    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 57
        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
            } else {
135 13
                $this->write('@component-not-found', ['component' => $component]);
136
            }
137 1
        } 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 52
    public function lookup($component) {
150 52
        $component = strtolower($component);
151 52
        $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 52
        if (!array_key_exists($key, $this->components)) {
154 47
            $this->loadComponent($component);
155
        }
156
157 52
        if (isset($this->components[$key])) {
158 51
            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 54
    protected function componentKey($component) {
190 54
        if (false !== $pos = strpos($component, ':')) {
191 1
            $component = substr($component, $pos + 1);
192
        }
193 54
        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 47
    protected function loadComponent($component) {
203 47
        $cacheKey = $this->templateLoader->cacheKey($component);
204
        // The template loader can tell us a template doesn't exist when giving the cache key.
205 47
        if (empty($cacheKey)) {
206 2
            return null;
207
        }
208
209 45
        $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 45
        $componentKey = $this->componentKey($component);
211
212 45
        if (!file_exists($cachePath)) {
213 45
            $src = $this->templateLoader->load($component);
214 45
            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 49
    public function compile($component, $src, $cacheKey) {
240 49
        $cachePath = "{$this->cachePath}/$cacheKey.php";
241 49
        $component = strtolower($component);
242
243 49
        $php = $this->compiler->compile($src, ['basename' => $component]);
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 49
        $comment = "/*\n".str_replace('*/', '❄/', trim($src))."\n*/";
245
246 49
        $this->filePutContents($cachePath, "<?php\n$comment\n$php");
247
248 49
        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 49
    private function includeComponent($component, $cachePath) {
259 49
        unset($this->components[$component]);
260 49
        $fn = $this->requireFile($cachePath);
261
262 49
        if (isset($this->components[$component])) {
263 49
            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 49
    private function filePutContents($path, $contents) {
281 49
        if (!file_exists(dirname($path))) {
282 4
            mkdir(dirname($path), 0777, true);
283
        }
284 49
        $tmpPath = tempnam(dirname($path), 'ebi-');
285 49
        $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 49
        if (file_put_contents($tmpPath, $contents) !== false) {
287 49
            chmod($tmpPath, 0664);
288 49
            $r = rename($tmpPath, $path);
289
        }
290
291 49
        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 49
        } elseif (function_exists('opcache_invalidate')) {
295 49
            @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
        }
297
298 49
        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 49
    public function requireFile($path) {
310 49
        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 57
    public function defineComponent($name, callable $component) {
320 57
        $this->components[$name] = $component;
321 57
    }
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 48
    public function render($component, ...$args) {
331 48
        if ($callback = $this->lookup($component)) {
332 48
            ob_start();
333 48
            $errs = error_reporting(error_reporting() & ~E_NOTICE & ~E_WARNING);
334 48
            call_user_func($callback, ...$args);
335 48
            error_reporting($errs);
336 48
            $str = ob_get_clean();
337 48
            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 5
    public function attributeClass($expr) {
383 5
        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 2
                } elseif (!empty($val)) {
391 3
                    $classes[] = $i;
392
                }
393
            }
394 3
            return implode(' ', $classes);
395
        } else {
396 2
            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
            } catch (\Exception $ex) {
413 1
                return '#error#';
414
            }
415
        } 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 14
    protected function attribute($name, $value) {
512 14
        if (substr($name, 0, 5) === 'aria-' && is_bool($value)) {
513 2
            $value = $value ? 'true' : 'false';
514
        }
515
516 14
        if ($value === true) {
517 1
            return ' '.$name;
518 13
        } elseif (!in_array($value, [null, false], true)) {
519 10
            return " $name=\"".htmlspecialchars($value).'"';
520
        }
521 3
        return '';
522
    }
523
}
524