Theme::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 4
nop 3
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use InvalidArgumentException;
8
use Yiisoft\Files\FileHelper;
9
10
use function is_file;
11
use function is_string;
12
use function ltrim;
13
use function rtrim;
14
use function strlen;
15
use function substr;
16
17
/**
18
 * `Theme` represents an application theme.
19
 *
20
 * When {@see View} renders a view file, it will check the {@see View::$theme} to see if there is a themed
21
 * version of the view file exists. If so, the themed version will be rendered instead.
22
 *
23
 * A theme is a directory consisting of view files which are meant to replace their non-themed counterparts.
24
 *
25
 * Theme uses {@see Theme::$pathMap} to achieve the view file replacement:
26
 *
27
 * 1. It first looks for a key in {@see Theme::$pathMap} that is a substring of the given view file path;
28
 * 2. If such a key exists, the corresponding value will be used to replace the corresponding part
29
 *    in the view file path;
30
 * 3. It will then check if the updated view file exists or not. If so, that file will be used
31
 *    to replace the original view file.
32
 * 4. If Step 2 or 3 fails, the original view file will be used.
33
 *
34
 * For example, if {@see Theme::$pathMap} is `['/app/views' => '/app/themes/basic']`, then the themed version for
35
 * a view file `/app/views/site/index.php` will be `/app/themes/basic/site/index.php`.
36
 *
37
 * It is possible to map a single path to multiple paths. For example:
38
 *
39
 * ```php
40
 * 'yiisoft/view' => [
41
 *     'theme' => [
42
 *         'pathMap' => [
43
 *             '/app/views' => [
44
 *                 '/app/themes/christmas',
45
 *                 '/app/themes/basic',
46
 *             ],
47
 *         ],
48
 *         'basePath' => '',
49
 *         'baseUrl' => '',
50
 *     ],
51
 * ],
52
 * ```
53
 *
54
 * In this case, the themed version could be either `/app/themes/christmas/site/index.php` or
55
 * `/app/themes/basic/site/index.php`. The former has precedence over the latter if both files exist.
56
 *
57
 * To use the theme directly without configurations, you should set it using the {@see View::setTheme()} as follows:
58
 *
59
 * ```php
60
 * $pathMap = [...];
61
 * $basePath = '/path/to/private/themes/basic';
62
 * $baseUrl = '/path/to/public/themes/basic';
63
 *
64
 * $view->setTheme(new Theme([...], $basePath, $baseUrl));
65
 * ```
66
 */
67
final class Theme
68
{
69
    /**
70
     * @var array<string, string|string[]>
71
     */
72
    private array $pathMap;
73
    private string $basePath = '';
74
    private string $baseUrl = '';
75
76
    /**
77
     * @param array $pathMap The mapping between view directories and their corresponding
78
     * themed versions. The path map is used by {@see applyTo()} when a view is trying to apply the theme.
79
     * @param string $basePath The base path to the theme directory.
80
     * @param string $baseUrl The base URL for this theme.
81
     *
82
     * @psalm-param array<string, string|string[]> $pathMap
83
     */
84 18
    public function __construct(array $pathMap = [], string $basePath = '', string $baseUrl = '')
85
    {
86 18
        $this->validatePathMap($pathMap);
87 16
        $this->pathMap = $pathMap;
88
89 16
        if ($basePath !== '') {
90 4
            $this->basePath = rtrim($basePath, '/');
91
        }
92
93 16
        if ($baseUrl !== '') {
94 3
            $this->baseUrl = rtrim($baseUrl, '/');
95
        }
96
    }
97
98
    /**
99
     * Returns the URL path for this theme.
100
     *
101
     * @return string The base URL (without ending slash) for this theme. All resources of this theme are considered
102
     * to be under this base URL.
103
     */
104 4
    public function getBaseUrl(): string
105
    {
106 4
        return $this->baseUrl;
107
    }
108
109
    /**
110
     * Returns the base path to the theme directory.
111
     *
112
     * @return string The root path of this theme. All resources of this theme are located under this directory.
113
     *
114
     * @see pathMap
115
     */
116 5
    public function getBasePath(): string
117
    {
118 5
        return $this->basePath;
119
    }
120
121
    /**
122
     * Converts a file to a themed file if possible.
123
     *
124
     * If there is no corresponding themed file, the original file will be returned.
125
     *
126
     * @param string $path The file to be themed
127
     *
128
     * @return string The themed file, or the original file if the themed version is not available.
129
     */
130 5
    public function applyTo(string $path): string
131
    {
132 5
        if ($this->pathMap === []) {
133 1
            return $path;
134
        }
135
136 4
        $path = FileHelper::normalizePath($path);
137
138 4
        foreach ($this->pathMap as $from => $tos) {
139 4
            $from = FileHelper::normalizePath($from) . '/';
140
141 4
            if (str_starts_with($path, $from)) {
142 4
                $n = strlen($from);
143
144 4
                foreach ((array) $tos as $to) {
145 4
                    $to = FileHelper::normalizePath($to) . '/';
146 4
                    $file = $to . substr($path, $n);
147
148 4
                    if (is_file($file)) {
149 3
                        return $file;
150
                    }
151
                }
152
            }
153
        }
154
155 2
        return $path;
156
    }
157
158
    /**
159
     * Converts and returns a relative URL into an absolute URL using {@see getbaseUrl()}.
160
     *
161
     * @param string $url The relative URL to be converted.
162
     *
163
     * @return string The absolute URL
164
     */
165 2
    public function getUrl(string $url): string
166
    {
167 2
        if (($baseUrl = $this->getBaseUrl()) !== '') {
168 1
            return $baseUrl . '/' . ltrim($url, '/');
169
        }
170
171 1
        return $url;
172
    }
173
174
    /**
175
     * Converts and returns a relative file path into an absolute one using {@see getBasePath()}.
176
     *
177
     * @param string $path The relative file path to be converted.
178
     *
179
     * @return string The absolute file path.
180
     */
181 3
    public function getPath(string $path): string
182
    {
183 3
        if (($basePath = $this->getBasePath()) !== '') {
184 2
            return $basePath . '/' . ltrim($path, '/\\');
185
        }
186
187 1
        return $path;
188
    }
189
190
    /**
191
     * Validates the path map.
192
     *
193
     * @param array $pathMap The path map for validation.
194
     */
195 18
    private function validatePathMap(array $pathMap): void
196
    {
197
        /** @var mixed $destinations */
198 18
        foreach ($pathMap as $source => $destinations) {
199 6
            if (!is_string($source)) {
200 1
                $this->throwInvalidPathMapException();
201
            }
202
203
            /** @var mixed $destination */
204 5
            foreach ((array)$destinations as $destination) {
205 5
                if (!is_string($destination)) {
206 1
                    $this->throwInvalidPathMapException();
207
                }
208
            }
209
        }
210
    }
211
212 2
    private function throwInvalidPathMapException(): void
213
    {
214 2
        throw new InvalidArgumentException(
215 2
            'The path map should contain the mapping between view directories and corresponding theme directories.'
216 2
        );
217
    }
218
}
219