Passed
Pull Request — master (#72)
by Wilmer
01:24
created

Theme::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Yiisoft\View;
5
6
use Yiisoft\Files\FileHelper;
7
8
/**
9
 * Theme represents an application theme.
10
 *
11
 * When {@see View} renders a view file, it will check the {@see View::theme|active theme} to see if there is a themed
12
 * version of the view file exists. If so, the themed version will be rendered instead.
13
 *
14
 * A theme is a directory consisting of view files which are meant to replace their non-themed counterparts.
15
 *
16
 * Theme uses {@see pathMap} to achieve the view file replacement:
17
 *
18
 * 1. It first looks for a key in {@see pathMap} that is a substring of the given view file path;
19
 * 2. If such a key exists, the corresponding value will be used to replace the corresponding part
20
 *    in the view file path;
21
 * 3. It will then check if the updated view file exists or not. If so, that file will be used
22
 *    to replace the original view file.
23
 * 4. If Step 2 or 3 fails, the original view file will be used.
24
 *
25
 * For example, if {@see pathMap} is `['@app/views' => '@app/themes/basic']`,
26
 * then the themed version for a view file `@app/views/site/index.php` will be
27
 * `@app/themes/basic/site/index.php`.
28
 *
29
 * It is possible to map a single path to multiple paths. For example,
30
 *
31
 * ```php
32
 * 'pathMap' => [
33
 *     '@app/views' => [
34
 *         '@app/themes/christmas',
35
 *         '@app/themes/basic',
36
 *     ],
37
 * ]
38
 * ```
39
 *
40
 * In this case, the themed version could be either `@app/themes/christmas/site/index.php` or
41
 * `@app/themes/basic/site/index.php`. The former has precedence over the latter if both files exist.
42
 *
43
 * To use a theme, you should configure the {@see View::theme|theme} property of the "view" application
44
 * component like the following:
45
 *
46
 * ```php
47
 * 'view' => [
48
 *     'theme' => [
49
 *         'basePath' => '@app/themes/basic',
50
 *         'baseUrl' => '@web/themes/basic',
51
 *     ],
52
 * ],
53
 * ```
54
 *
55
 * The above configuration specifies a theme located under the "themes/basic" directory of the Web folder that contains
56
 * the entry script of the application. If your theme is designed to handle modules, you may configure the
57
 * {@see pathMap} property like described above.
58
 *
59
 * For more details and usage information on Theme, see the [guide article on theming](guide:output-theming).
60
 */
61
class Theme
62
{
63
    /**
64
     * @var array the mapping between view directories and their corresponding themed versions.
65
     *
66
     * This property is used by {@see applyTo()} when a view is trying to apply the theme.
67
     * [Path aliases](guide:concept-aliases) can be used when specifying directories.
68
     * If this property is empty or not set, a mapping {@see Application::basePath} to {@see basePath} will be used.
69
     */
70
    private array $pathMap = [];
71
72
    private ?string $baseUrl = null;
73
74
    private ?string $basePath = null;
75
76 16
    public function __construct(array $pathMap = [], string $basePath = null, string $baseUrl = null)
77
    {
78 16
        $this->pathMap = $pathMap;
79 16
        $this->basePath = $basePath;
80
81 16
        if ($baseUrl !== null) {
82 1
            $this->baseUrl = rtrim($baseUrl, '/');
83
        }
84
    }
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 11
    public function applyTo(string $path): string
115
    {
116 11
        if ($this->pathMap === []) {
117 7
            return $path;
118
        }
119 4
        $path = FileHelper::normalizePath($path);
120 4
        foreach ($this->pathMap as $from => $tos) {
121 4
            if (!is_string($from)) {
122
                throw new \InvalidArgumentException('Pathmap should contain strings');
123
            }
124
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()) !== null) {
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()) !== null) {
167 1
            return $basePath . '/' . ltrim($path, '/\\');
168
        }
169
170 1
        return $path;
171
    }
172
}
173