xref: /webtrees/app/Html.php (revision 76d39c55735cfa9ad0972b0dd530e96b051f9ebe)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use function e;
23use function http_build_query;
24use function implode;
25use function is_int;
26use function is_string;
27use function strtr;
28
29use const PHP_QUERY_RFC3986;
30
31/**
32 * Class Html - Add HTML markup to elements consistently.
33 */
34class Html
35{
36    /**
37     * Convert an array of HTML attributes to an HTML string.
38     *
39     * @param array<string,string|int|bool> $attributes
40     *
41     * @return string
42     */
43    public static function attributes(array $attributes): string
44    {
45        $html = [];
46        foreach ($attributes as $key => $value) {
47            if (is_string($value)) {
48                $html[] = e($key) . '="' . e($value) . '"';
49            } elseif (is_int($value)) {
50                $html[] = e($key) . '="' . $value . '"';
51            } elseif ($value === true) {
52                $html[] = e($key) . '="' . e($key) . '"';
53            }
54        }
55
56        return implode(' ', $html);
57    }
58
59    /**
60     * Encode a URL.
61     *
62     * @param string                                    $path
63     * @param array<bool|int|string|array<string>|null> $data
64     *
65     * @return string
66     */
67    public static function url(string $path, array $data): string
68    {
69        $path = strtr($path, [' ' => '%20']);
70
71        if ($data !== []) {
72            $path .= '?' . http_build_query($data, '', '&', PHP_QUERY_RFC3986);
73        }
74
75        return $path;
76    }
77
78    /**
79     * Filenames are (almost?) always LTR, even on RTL systems.
80     *
81     * @param string $filename
82     *
83     * @return string
84     */
85    public static function filename(string $filename): string
86    {
87        return '<samp class="filename" dir="ltr">' . e($filename) . '</samp>';
88    }
89}
90