Passed
Pull Request — master (#84)
by Rustam
02:28
created

Theme::getUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
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
        foreach ($pathMap as $from => $tos) {
78 4
            if (!is_string($from)) {
79
                throw new \InvalidArgumentException('Theme::$pathMap should contain strings');
80
            }
81
        }
82 18
        $this->pathMap = $pathMap;
83 18
        $this->basePath = $basePath;
84
85 18
        if ($baseUrl !== '') {
86 1
            $this->baseUrl = rtrim($baseUrl, '/');
87
        }
88 18
    }
89
90
    /**
91
     * @return string the base URL (without ending slash) for this theme. All resources of this theme are considered
92
     * to be under this base URL.
93
     */
94 2
    public function getBaseUrl(): string
95
    {
96 2
        return $this->baseUrl;
97
    }
98
99
    /**
100
     * @return string the root path of this theme. All resources of this theme are located under this directory.
101
     *
102
     * @see pathMap
103
     */
104 2
    public function getBasePath(): string
105
    {
106 2
        return $this->basePath;
107
    }
108
109
    /**
110
     * Converts a file to a themed file if possible.
111
     *
112
     * If there is no corresponding themed file, the original file will be returned.
113
     *
114
     * @param string $path the file to be themed
115
     *
116
     * @return string the themed file, or the original file if the themed version is not available.
117
     */
118 12
    public function applyTo(string $path): string
119
    {
120 12
        if ($this->pathMap === []) {
121 8
            return $path;
122
        }
123 4
        $path = FileHelper::normalizePath($path);
124 4
        foreach ($this->pathMap as $from => $tos) {
125 4
            $from = FileHelper::normalizePath($from) . '/';
126 4
            if (strpos($path, $from) === 0) {
127 4
                $n = strlen($from);
128 4
                foreach ((array)$tos as $to) {
129 4
                    $to = FileHelper::normalizePath($to) . '/';
130 4
                    $file = $to . substr($path, $n);
131 4
                    if (is_file($file)) {
132 3
                        return $file;
133
                    }
134
                }
135
            }
136
        }
137
138 2
        return $path;
139
    }
140
141
    /**
142
     * Converts a relative URL into an absolute URL using {@see baseUrl}.
143
     *
144
     * @param string $url the relative URL to be converted.
145
     *
146
     * @return string the absolute URL
147
     */
148 2
    public function getUrl(string $url): string
149
    {
150 2
        if (($baseUrl = $this->getBaseUrl()) !== '') {
151 1
            return $baseUrl . '/' . ltrim($url, '/');
152
        }
153
154 1
        return $url;
155
    }
156
157
    /**
158
     * Converts a relative file path into an absolute one using {@see basePath}.
159
     *
160
     * @param string $path the relative file path to be converted.
161
     *
162
     * @return string the absolute file path
163
     */
164 2
    public function getPath(string $path): string
165
    {
166 2
        if (($basePath = $this->getBasePath()) !== '') {
167 1
            return $basePath . '/' . ltrim($path, '/\\');
168
        }
169
170 1
        return $path;
171
    }
172
}
173