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