Completed
Pull Request — master (#21)
by Todd
02:37
created

Ebi::filePutContents()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

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