Passed
Pull Request — master (#84)
by Alexander
02:30
created

Theme::validatePathMap()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.1406
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use Yiisoft\Files\FileHelper;
8
9
/**
10
 * Theme represents an application theme.
11
 *
12
 * When {@see View} renders a view file, it will check the {@see View::theme} to see if there is a themed
13
 * version of the view file exists. If so, the themed version will be rendered instead.
14
 *
15
 * A theme is a directory consisting of view files which are meant to replace their non-themed counterparts.
16
 *
17
 * Theme uses {@see pathMap} to achieve the view file replacement:
18
 *
19
 * 1. It first looks for a key in {@see pathMap} that is a substring of the given view file path;
20
 * 2. If such a key exists, the corresponding value will be used to replace the corresponding part
21
 *    in the view file path;
22
 * 3. It will then check if the updated view file exists or not. If so, that file will be used
23
 *    to replace the original view file.
24
 * 4. If Step 2 or 3 fails, the original view file will be used.
25
 *
26
 * For example, if {@see pathMap} is `['@app/views' => '@app/themes/basic']`,
27
 * then the themed version for a view file `@app/views/site/index.php` will be
28
 * `@app/themes/basic/site/index.php`.
29
 *
30
 * It is possible to map a single path to multiple paths. For example,
31
 *
32
 * ```php
33
 * 'pathMap' => [
34
 *     '@app/views' => [
35
 *         '@app/themes/christmas',
36
 *         '@app/themes/basic',
37
 *     ],
38
 * ]
39
 * ```
40
 *
41
 * In this case, the themed version could be either `@app/themes/christmas/site/index.php` or
42
 * `@app/themes/basic/site/index.php`. The former has precedence over the latter if both files exist.
43
 *
44
 * To use a theme, you should configure the {@see View::theme} property of the "view" application
45
 * component like the following:
46
 *
47
 * ```php
48
 * 'view' => [
49
 *     'theme' => [
50
 *         'basePath' => '@app/themes/basic',
51
 *         'baseUrl' => '@web/themes/basic',
52
 *     ],
53
 * ],
54
 * ```
55
 *
56
 * The above configuration specifies a theme located under the "themes/basic" directory of the Web folder that contains
57
 * the entry script of the application. If your theme is designed to handle modules, you may configure the
58
 * {@see Theme::pathMap} property like described above.
59
 *
60
 * For more details and usage information on Theme, see the [guide article on theming](guide:output-theming).
61
 */
62
class Theme
63
{
64
    /**
65
     * @var array the mapping between view directories and their corresponding themed versions.
66
     *
67
     * This property is used by {@see applyTo()} when a view is trying to apply the theme.
68
     * [Path aliases](guide:concept-aliases) can be used when specifying directories.
69
     * If this property is empty or not set, a mapping {@see Application::basePath} to {@see basePath} will be used.
70
     */
71
    private array $pathMap = [];
72
    private string $baseUrl = '';
73
    private string $basePath = '';
74
75 18
    public function __construct(array $pathMap = [], string $basePath = '', string $baseUrl = '')
76
    {
77 18
        $this->validatePathMap($pathMap);
78 18
        $this->pathMap = $pathMap;
79 18
        $this->basePath = $basePath;
80
81 18
        if ($baseUrl !== '') {
82 1
            $this->baseUrl = rtrim($baseUrl, '/');
83
        }
84 18
    }
85
86
    /**
87
     * @return string the base URL (without ending slash) for this theme. All resources of this theme are considered
88
     * to be under this base URL.
89
     */
90 2
    public function getBaseUrl(): string
91
    {
92 2
        return $this->baseUrl;
93
    }
94
95
    /**
96
     * @return string the root path of this theme. All resources of this theme are located under this directory.
97
     *
98
     * @see pathMap
99
     */
100 2
    public function getBasePath(): string
101
    {
102 2
        return $this->basePath;
103
    }
104
105
    /**
106
     * Converts a file to a themed file if possible.
107
     *
108
     * If there is no corresponding themed file, the original file will be returned.
109
     *
110
     * @param string $path the file to be themed
111
     *
112
     * @return string the themed file, or the original file if the themed version is not available.
113
     */
114 12
    public function applyTo(string $path): string
115
    {
116 12
        if ($this->pathMap === []) {
117 8
            return $path;
118
        }
119 4
        $path = FileHelper::normalizePath($path);
120 4
        foreach ($this->pathMap as $from => $tos) {
121 4
            $from = FileHelper::normalizePath($from) . '/';
122 4
            if (strpos($path, $from) === 0) {
123 4
                $n = strlen($from);
124 4
                foreach ((array)$tos as $to) {
125 4
                    $to = FileHelper::normalizePath($to) . '/';
126 4
                    $file = $to . substr($path, $n);
127 4
                    if (is_file($file)) {
128 3
                        return $file;
129
                    }
130
                }
131
            }
132
        }
133
134 2
        return $path;
135
    }
136
137
    /**
138
     * Converts a relative URL into an absolute URL using {@see baseUrl}.
139
     *
140
     * @param string $url the relative URL to be converted.
141
     *
142
     * @return string the absolute URL
143
     */
144 2
    public function getUrl(string $url): string
145
    {
146 2
        if (($baseUrl = $this->getBaseUrl()) !== '') {
147 1
            return $baseUrl . '/' . ltrim($url, '/');
148
        }
149
150 1
        return $url;
151
    }
152
153
    /**
154
     * Converts a relative file path into an absolute one using {@see basePath}.
155
     *
156
     * @param string $path the relative file path to be converted.
157
     *
158
     * @return string the absolute file path
159
     */
160 2
    public function getPath(string $path): string
161
    {
162 2
        if (($basePath = $this->getBasePath()) !== '') {
163 1
            return $basePath . '/' . ltrim($path, '/\\');
164
        }
165
166 1
        return $path;
167
    }
168
169 18
    private function validatePathMap(array $pathMap): void
170
    {
171 18
        foreach ($pathMap as $source => $destinations) {
172 4
            if (!is_string($source)) {
173
                throw new \InvalidArgumentException('Theme::$pathMap should contain the mapping between view directories and corresponding theme directories.');
174
            }
175
        }
176 18
    }
177
}
178