summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/html/src/Html.php
blob: afcba39b2b99f1bec6d54343654ed50561d46d58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<?php

namespace ipl\Html;

use InvalidArgumentException;

use function ipl\Stdlib\get_php_type;
use function ipl\Stdlib\iterable_key_first;

/**
 * Main utility class when working with ipl\Html
 */
abstract class Html
{
    /**
     * Create a HTML element from the given tag, attributes and content
     *
     * This method does not render the HTML element but creates a {@link HtmlElement}
     * instance from the given tag, attributes and content
     *
     * @param string $name       The desired HTML tag name
     * @param mixed  $attributes HTML attributes or content for the element
     * @param mixed  $content    The content of the element if no attributes have been given
     *
     * @return HtmlElement The created element
     */
    public static function tag($name, $attributes = null, $content = null)
    {
        if ($content !== null) {
            // If not null, it's html content, no question
            $content = static::wantHtmlList($content);
        } elseif ($attributes instanceof ValidHtml || is_scalar($attributes)) {
            // Otherwise $attributes may be $content, but only if definitely **NOT** attributes
            $content = static::wantHtmlList($attributes);
            $attributes = null;
        }

        if ($attributes !== null) {
            if (! is_iterable($attributes) || ! is_int(iterable_key_first($attributes))) {
                // Not an array (e.g. instance of Attributes) or an associative array
                $attributes = Attributes::wantAttributes($attributes);
            } elseif (is_iterable($attributes)) {
                // $attributes may still be $content, in case of a sequenced array
                if ($content !== null) {
                    // But not if there's already $content
                    throw new InvalidArgumentException('Value of argument $attributes are no attributes');
                }

                $content = static::wantHtmlList($attributes);
                $attributes = null;
            }
        }

        return new HtmlElement($name, $attributes, ...($content ?: []));
    }

    /**
     * Convert special characters to HTML5 entities using the UTF-8 character
     * set for encoding
     *
     * This method internally uses {@link htmlspecialchars} with the following
     * flags:
     *
     * * Single quotes are not escaped (ENT_COMPAT)
     * * Uses HTML5 entities, disallowing &#013; (ENT_HTML5)
     * * Invalid characters are replaced with � (ENT_SUBSTITUTE)
     *
     * Already existing HTML entities will be encoded as well.
     *
     * @param string $content The content to encode
     *
     * @return string The encoded content
     */
    public static function escape($content)
    {
        return htmlspecialchars($content, ENT_COMPAT | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8');
    }

    /**
     * Factory for {@link sprintf()}-like formatted HTML strings
     *
     * This allows to use {@link sprintf()}-like format strings with {@link ValidHtml} element arguments, but with the
     * advantage that they'll not be rendered immediately.
     *
     * # Example Usage
     * ```
     * echo Html::sprintf('Hello %s!', Html::tag('strong', $name));
     * ```
     *
     * @param string $format
     * @param mixed  ...$args
     *
     * @return FormattedString
     */
    public static function sprintf($format, ...$args)
    {
        return new FormattedString($format, $args);
    }

    /**
     * Wrap each item of then given list
     *
     * $wrapper is a simple HTML tag per entry if a string is given,
     * otherwise the given callable is called with key and value of each list item as parameters.
     *
     * @param iterable        $list
     * @param string|callable $wrapper
     *
     * @return HtmlDocument
     */
    public static function wrapEach($list, $wrapper)
    {
        if (! is_iterable($list)) {
            throw new InvalidArgumentException(sprintf(
                'Html::wrapEach() requires a traversable list, got "%s"',
                get_php_type($list)
            ));
        }
        $result = new HtmlDocument();
        foreach ($list as $name => $value) {
            if (is_string($wrapper)) {
                $result->addHtml(Html::tag($wrapper, $value));
            } elseif (is_callable($wrapper)) {
                $result->add($wrapper($name, $value));
            } else {
                throw new InvalidArgumentException(sprintf(
                    'Wrapper must be callable or a string in Html::wrapEach(), got "%s"',
                    get_php_type($wrapper)
                ));
            }
        }

        return $result;
    }

    /**
     * Ensure that the given content of mixed type is converted to an instance of {@link ValidHtml}
     *
     * Returns the very same element in case it's already an instance of {@link ValidHtml}.
     *
     * @param mixed $any
     *
     * @return ValidHtml
     *
     * @throws InvalidArgumentException In case the given content is of an unsupported type
     */
    public static function wantHtml($any)
    {
        if ($any instanceof ValidHtml) {
            return $any;
        } elseif (static::canBeRenderedAsString($any)) {
            return new Text($any);
        } elseif (is_iterable($any)) {
            $html = new HtmlDocument();
            foreach ($any as $el) {
                if ($el !== null) {
                    $html->addHtml(static::wantHtml($el));
                }
            }

            return $html;
        } else {
            throw new InvalidArgumentException(sprintf(
                'String, Html Element or Array of such expected, got "%s"',
                get_php_type($any)
            ));
        }
    }

    /**
     * Accept any input and return it as list of ValidHtml
     *
     * @param mixed $content
     *
     * @return ValidHtml[]
     */
    public static function wantHtmlList($content)
    {
        $list = [];

        if ($content === null) {
            return $list;
        } elseif (! is_iterable($content)) {
            $list[] = static::wantHtml($content);
        } elseif ($content instanceof ValidHtml) {
            $list[] = $content;
        } else {
            foreach ($content as $part) {
                $list = array_merge($list, static::wantHtmlList($part));
            }
        }

        return $list;
    }

    /**
     * Get whether the given variable be rendered as a string
     *
     * @param mixed $any
     *
     * @return bool
     */
    public static function canBeRenderedAsString($any)
    {
        return is_scalar($any) || is_null($any) || (
            is_object($any) && method_exists($any, '__toString')
        );
    }

    /**
     * Forward inaccessible static method calls to {@link Html::tag()} with the method's name as tag
     *
     * @param string $name
     * @param array  $arguments
     *
     * @return HtmlElement
     */
    public static function __callStatic($name, $arguments)
    {
        $attributes = array_shift($arguments);
        $content = array_shift($arguments);

        return static::tag($name, $attributes, $content);
    }

    /**
     * @deprecated Use {@link Html::encode()} instead
     */
    public static function escapeForHtml($content)
    {
        return static::escape($content);
    }

    /**
     * @deprecated Use {@link Error::render()} instead
     */
    public static function renderError($error)
    {
        return Error::render($error);
    }
}