Passed
Pull Request — master (#167)
by Evgeniy
02:43
created

Theme::validatePathMap()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.6111
cc 5
nc 5
nop 1
crap 5
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 12
    public function __construct(array $pathMap = [], string $basePath = '', string $baseUrl = '')
84
    {
85 12
        $this->validatePathMap($pathMap);
86 10
        $this->pathMap = $pathMap;
87 10
        $this->basePath = $basePath;
88
89 10
        if ($baseUrl !== '') {
90 1
            $this->baseUrl = rtrim($baseUrl, '/');
91
        }
92 10
    }
93
94
    /**
95
     * Returns the URL path for this theme.
96
     *
97
     * @return string The base URL (without ending slash) for this theme. All resources of this theme are considered
98
     * to be under this base URL.
99
     */
100 2
    public function getBaseUrl(): string
101
    {
102 2
        return $this->baseUrl;
103
    }
104
105
    /**
106
     * Returns the base path to the theme directory.
107
     *
108
     * @return string The root path of this theme. All resources of this theme are located under this directory.
109
     *
110
     * @see pathMap
111
     */
112 2
    public function getBasePath(): string
113
    {
114 2
        return $this->basePath;
115
    }
116
117
    /**
118
     * Converts a file to a themed file if possible.
119
     *
120
     * If there is no corresponding themed file, the original file will be returned.
121
     *
122
     * @param string $path The file to be themed
123
     *
124
     * @return string The themed file, or the original file if the themed version is not available.
125
     */
126 5
    public function applyTo(string $path): string
127
    {
128 5
        if ($this->pathMap === []) {
129 1
            return $path;
130
        }
131
132 4
        $path = FileHelper::normalizePath($path);
133
134 4
        foreach ($this->pathMap as $from => $tos) {
135 4
            $from = FileHelper::normalizePath($from) . '/';
136
137 4
            if (strpos($path, $from) === 0) {
138 4
                $n = strlen($from);
139
140 4
                foreach ((array) $tos as $to) {
141 4
                    $to = FileHelper::normalizePath($to) . '/';
142 4
                    $file = $to . substr($path, $n);
143
144 4
                    if (is_file($file)) {
145 3
                        return $file;
146
                    }
147
                }
148
            }
149
        }
150
151 2
        return $path;
152
    }
153
154
    /**
155
     * Converts and returns a relative URL into an absolute URL using {@see getbaseUrl()}.
156
     *
157
     * @param string $url The relative URL to be converted.
158
     *
159
     * @return string The absolute URL
160
     */
161 2
    public function getUrl(string $url): string
162
    {
163 2
        if (($baseUrl = $this->getBaseUrl()) !== '') {
164 1
            return $baseUrl . '/' . ltrim($url, '/');
165
        }
166
167 1
        return $url;
168
    }
169
170
    /**
171
     * Converts and returns a relative file path into an absolute one using {@see getBasePath()}.
172
     *
173
     * @param string $path The relative file path to be converted.
174
     *
175
     * @return string The absolute file path.
176
     */
177 2
    public function getPath(string $path): string
178
    {
179 2
        if (($basePath = $this->getBasePath()) !== '') {
180 1
            return $basePath . '/' . ltrim($path, '/\\');
181
        }
182
183 1
        return $path;
184
    }
185
186
    /**
187
     * Validates the path map.
188
     *
189
     * @param array $pathMap The path map for validation.
190
     */
191 12
    private function validatePathMap(array $pathMap): void
192
    {
193
        $errorMessage = 'The path map should contain the mapping between'
194 12
            . ' view directories and corresponding theme directories.';
195
196
        /** @var mixed $destinations */
197 12
        foreach ($pathMap as $source => $destinations) {
198 7
            if (!is_string($source)) {
199 1
                throw new InvalidArgumentException($errorMessage);
200
            }
201
202
            /** @var mixed $destination */
203 6
            foreach ((array) $destinations as $destination) {
204 6
                if (!is_string($destination)) {
205 1
                    throw new InvalidArgumentException($errorMessage);
206
                }
207
            }
208
        }
209 10
    }
210
}
211