Passed
Push — master ( 808cac...64bfdf )
by Evgeniy
02:17
created

Theme::throwInvalidPathMapException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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