Debian Codegraph @

vendor/ipl/html/src/Error.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use Exception;
6 use Throwable;
7
8 use function ipl\Stdlib\get_php_type;
9
10 /**
11 * Class Error
12 *
13 * TODO: Eventually allow to (statically) inject a custom error renderer.
14 *
15 * @package ipl\Html
16 */
17 abstract class Error
18 {
19 /** @var bool */
20 protected static $showTraces = true;
21
22 /**
23 *
24 * @param Exception|Throwable|string $error
25 * @return HtmlDocument
26 */
27 public static function show($error)
28 {
29 if ($error instanceof Throwable) {
30 // PHP 7+
31 $msg = static::createMessageForException($error);
32 } elseif (is_string($error)) {
33 $msg = $error;
34 } else {
35 // TODO: translate?
36 $msg = 'Got an invalid error';
37 }
38
39 $result = static::renderErrorMessage($msg);
40 if (static::showTraces() && $error instanceof Throwable) {
41 $result->addHtml(Html::tag('pre', $error->getTraceAsString()));
42 }
43
44 return $result;
45 }
46
47 /**
48 *
49 * @param Exception|Throwable|string $error
50 * @return string
51 */
52 public static function render($error)
53 {
54 return static::show($error)->render();
55 }
56
57 /**
58 * @param bool|null $show
59 * @return bool
60 */
61 public static function showTraces($show = null)
62 {
63 if ($show !== null) {
64 self::$showTraces = (bool) $show;
65 }
66
67 return self::$showTraces;
68 }
69
70 /**
71 * @deprecated Use {@link get_php_type()} instead
72 */
73 public static function getPhpTypeName($any)
74 {
75 return get_php_type($any);
76 }
77
78 /**
79 * @param Exception|Throwable $exception
80 * @return string
81 */
82 protected static function createMessageForException($exception)
83 {
84 $file = preg_split('/[\/\\\]/', $exception->getFile(), -1, PREG_SPLIT_NO_EMPTY) ?: [];
85 $file = array_pop($file);
86 return sprintf(
87 '%s (%s:%d)',
88 $exception->getMessage(),
89 $file,
90 $exception->getLine()
91 );
92 }
93
94 /**
95 * @param string
96 * @return HtmlDocument
97 */
98 protected static function renderErrorMessage($message)
99 {
100 $output = new HtmlDocument();
101 $output->addHtml(
102 Html::tag('div', ['class' => 'exception'], [
103 Html::tag('h1', [
104 Html::tag('i', ['class' => 'icon-bug']),
105 // TODO: Translate? More hints?
106 'Oops, an error occurred!'
107 ]),
108 Html::tag('pre', $message)
109 ])
110 );
111
112 return $output;
113 }
114 }