Debian Codegraph @

vendor/ipl/html/src/FormattedString.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use InvalidArgumentException;
6 use Throwable;
7
8 use function ipl\Stdlib\get_php_type;
9
10 /**
11 * {@link sprintf()}-like formatted HTML string supporting lazy rendering of {@link ValidHtml} element arguments
12 *
13 * # Example Usage
14 * ```
15 * $info = new FormattedString(
16 * 'Follow the %s for more information on %s',
17 * [
18 * new Link('doc/html', 'HTML documentation'),
19 * Html::tag('strong', 'HTML elements')
20 * ]
21 * );
22 * ```
23 */
24 class FormattedString implements ValidHtml
25 {
26 /** @var ValidHtml[] */
27 protected $args = [];
28
29 /** @var ValidHtml */
30 protected $format;
31
32 /**
33 * Create a new {@link sprintf()}-like formatted HTML string
34 *
35 * @param string $format
36 * @param iterable $args
37 *
38 * @throws InvalidArgumentException If arguments given but not iterable
39 */
40 public function __construct($format, $args = null)
41 {
42 $this->format = Html::wantHtml($format);
43
44 if ($args !== null) {
45 if (! is_iterable($args)) {
46 throw new InvalidArgumentException(sprintf(
47 '%s expects parameter two to be iterable, got %s instead',
48 __METHOD__,
49 get_php_type($args)
50 ));
51 }
52
53 foreach ($args as $key => $val) {
54 if (! is_scalar($val) || (is_string($val) && ! is_numeric($val))) {
55 $val = Html::wantHtml($val);
56 }
57
58 $this->args[$key] = $val;
59 }
60 }
61 }
62
63
64 /**
65 * Create a new {@link sprintf()}-like formatted HTML string
66 *
67 * @param string $format
68 * @param mixed ...$args
69 *
70 * @return static
71 */
72 public static function create($format, ...$args)
73 {
74 return new static($format, $args);
75 }
76
77 /**
78 * Render text to HTML when treated like a string
79 *
80 * Calls {@link render()} internally in order to render the text to HTML.
81 * Exceptions will be automatically caught and returned as HTML string as well using {@link Error::render()}.
82 *
83 * @return string
84 */
85 public function __toString()
86 {
87 try {
88 return $this->render();
89 } catch (Throwable $e) {
90 return Error::render($e);
91 }
92 }
93
94 public function render()
95 {
96 return vsprintf(
97 $this->format->render(),
98 $this->args
99 );
100 }
101 }