DauxHelper   F
last analyzed

Complexity

Total Complexity 60

Size/Duplication

Total Lines 512
Duplicated Lines 0 %

Test Coverage

Coverage 37.34%

Importance

Changes 10
Bugs 2 Features 0
Metric Value
eloc 274
c 10
b 2
f 0
dl 0
loc 512
ccs 59
cts 158
cp 0.3734
rs 3.6
wmc 60

13 Methods

Rating   Name   Duplication   Size   Complexity  
A rebaseConfiguration() 0 11 3
A getFilenames() 0 8 1
A getCleanPath() 0 17 4
A is() 0 2 2
A getRelativePath() 0 32 6
B charsArray() 0 130 2
A slug() 0 22 2
A resolveVariant() 0 22 5
A getAbsolutePath() 0 6 2
B getTheme() 0 64 11
A isAbsolutePath() 0 28 4
C getFile() 0 60 12
A findLocation() 0 24 6

How to fix   Complexity   

Complex Class

Complex classes like DauxHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DauxHelper, and based on these observations, apply Extract Interface, too.

1
<?php namespace Todaymade\Daux;
2
3
use Todaymade\Daux\Tree\Builder;
4
use Todaymade\Daux\Tree\Directory;
5
6
class DauxHelper
7
{
8
    /**
9
     * Set a new base_url for the configuration
10
     *
11
     * @param Config $config
12
     * @param string $base_url
13
     */
14
    public static function rebaseConfiguration(Config $config, $base_url)
15
    {
16
        // Avoid changing the url if it is already correct
17
        if ($config['base_url'] == $base_url && !empty($config['theme'])) {
18
            return;
19
        }
20
21
        // Change base url for all links on the pages
22
        $config['base_url'] = $config['base_page'] = $base_url;
23
        $config['theme'] = static::getTheme($config, $base_url);
24
        $config['image'] = str_replace('<base_url>', $base_url, $config['image']);
25
    }
26
27
    protected static function resolveVariant(Config $params)
28
    {
29
        if (array_key_exists('theme-variant', $params['html'])) {
30
            return;
31
        }
32
33
        if (is_dir(realpath(($params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme'])))) {
34
            return;
35
        }
36
37
        $theme = explode('-', $params['html']['theme']);
38
39
        // do we have a variant or only a theme ?
40
        if (isset($theme[1])) {
41
            $params['html']['theme-variant'] = array_pop($theme);
42
            $params['html']['theme'] = implode('-', $theme);
43
        } else {
44
            $params['html']['theme'] = array_pop($theme);
45
        }
46
47
        if (!is_dir(realpath($params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme']))) {
48
            throw new \RuntimeException("Theme '{$params['html']['theme']}' not found");
49
        }
50
    }
51
52
    /**
53
     * @param Config $params
54
     * @param string $current_url
55
     * @return array
56
     */
57
    protected static function getTheme(Config $params, $current_url)
58
    {
59
        self::resolveVariant($params);
60
61
        $theme_folder = $params->getThemesPath() . DIRECTORY_SEPARATOR . $params['html']['theme'];
62
        $theme_url = $params['base_url'] . 'themes/' . $params['html']['theme'] . '/';
63
64
        $theme = [];
65
        if (is_file($theme_folder . DIRECTORY_SEPARATOR . 'config.json')) {
66
            $theme = json_decode(file_get_contents($theme_folder . DIRECTORY_SEPARATOR . 'config.json'), true);
67
            if (!$theme) {
68
                $theme = [];
69
            }
70
        }
71
72
        //Default parameters for theme
73
        $theme += [
74
            'name' => $params['html']['theme'],
75
            'css' => [],
76
            'js' => [],
77
            'fonts' => [],
78
            'favicon' => '<base_url>themes/daux/img/favicon.png',
79
            'templates' => $theme_folder . DIRECTORY_SEPARATOR . 'templates',
80
            'variants' => [],
81
        ];
82
83
        if (array_key_exists('theme-variant', $params['html'])) {
84
            $variant = $params['html']['theme-variant'];
85
            if (!array_key_exists($variant, $theme['variants'])) {
86
                throw new Exception("Variant '$variant' not found for theme '$theme[name]'");
87
            }
88
89
            // These will be replaced
90
            foreach (['templates', 'favicon'] as $element) {
91
                if (array_key_exists($element, $theme['variants'][$variant])) {
92
                    $theme[$element] = $theme['variants'][$variant][$element];
93
                }
94
            }
95
96
            // These will be merged
97
            foreach (['css', 'js', 'fonts'] as $element) {
98
                if (array_key_exists($element, $theme['variants'][$variant])) {
99
                    $theme[$element] = array_merge($theme[$element], $theme['variants'][$variant][$element]);
100
                }
101
            }
102
        }
103
104
        $substitutions = [
105
            '<local_base>' => $params['local_base'],
106
            '<base_url>' => $current_url,
107
            '<theme_url>' => $theme_url,
108
        ];
109
110
        // Substitute some placeholders
111
        $theme['templates'] = strtr($theme['templates'], $substitutions);
112
        $theme['favicon'] = utf8_encode(strtr($theme['favicon'], $substitutions));
113
114
        foreach (['css', 'js', 'fonts'] as $element) {
115
            foreach ($theme[$element] as $key => $value) {
116
                $theme[$element][$key] = utf8_encode(strtr($value, $substitutions));
117
            }
118
        }
119
120
        return $theme;
121
    }
122
123
    /**
124
     * Remove all '/./' and '/../' in a path, without actually checking the path
125
     *
126
     * @param string $path
127
     * @return string
128
     */
129
    public static function getCleanPath($path)
130
    {
131
        $path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
132
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
133
        $absolutes = [];
134
        foreach ($parts as $part) {
135
            if ('.' == $part) {
136
                continue;
137
            }
138
            if ('..' == $part) {
139
                array_pop($absolutes);
140
            } else {
141
                $absolutes[] = $part;
142
            }
143
        }
144
145
        return implode(DIRECTORY_SEPARATOR, $absolutes);
146
    }
147
148
    /**
149
     * Get the possible output file names for a source file.
150
     *
151
     * @param Config $config
152
     * @param string $part
153
     * @return string[]
154
     */
155 16
    public static function getFilenames(Config $config, $part)
156
    {
157 16
        $extensions = implode('|', array_map('preg_quote', $config['valid_content_extensions'])) . '|html';
158
159 16
        $raw = preg_replace('/(.*)?\\.(' . $extensions . ')$/', '$1', $part);
160 16
        $raw = Builder::removeSortingInformations($raw);
161
162 16
        return ["$raw.html", $raw];
163
    }
164
165
    /**
166
     * Locate a file in the tree. Returns the file if found or false
167
     *
168
     * @param Directory $tree
169
     * @param string $request
170
     * @return Tree\Content|Tree\Raw|false
171
     */
172 17
    public static function getFile($tree, $request)
173
    {
174 17
        $request = explode('/', $request);
175 17
        foreach ($request as $node) {
176
            // If the element we're in currently is not a
177
            // directory, we failed to find the requested file
178 17
            if (!$tree instanceof Directory) {
179 1
                return false;
180
            }
181
182
            // Some relative paths may start with ./
183 17
            if ($node == '.') {
184 3
                continue;
185
            }
186
187 17
            if ($node == '..') {
188 2
                $tree = $tree->getParent();
189 2
                continue;
190
            }
191
192 17
            $node = DauxHelper::slug(urldecode($node));
193
194
            // if the node exists in the current request tree,
195
            // change the $tree variable to reference the new
196
            // node and proceed to the next url part
197 17
            if (isset($tree->getEntries()[$node])) {
198 17
                $tree = $tree->getEntries()[$node];
199 17
                continue;
200
            }
201
202
            // if the node doesn't exist, we can try
203
            // two variants of the requested file:
204
            // with and w/o the .html extension
205 12
            foreach (static::getFilenames($tree->getConfig(), $node) as $filename) {
206 12
                if (isset($tree->getEntries()[$filename])) {
207 12
                    $tree = $tree->getEntries()[$filename];
208 12
                    continue 2;
209
                }
210
            }
211
212
            // At this stage, we're in a directory, but no
213
            // sub-item matches, so the current node must
214
            // be an index page or we failed
215 3
            if ($node !== 'index' && $node !== 'index.html') {
216 3
                return false;
217
            }
218
219
            return $tree->getIndexPage();
220
        }
221
222
        // If the entry we found is not a directory, we're done
223 17
        if (!$tree instanceof Directory) {
224 17
            return $tree;
225
        }
226
227
        if ($index = $tree->getIndexPage()) {
228
            return $index;
229
        }
230
231
        return false;
232
    }
233
234
    /**
235
     * Generate a URL friendly "slug" from a given string.
236
     *
237
     * Taken from Stringy
238
     *
239
     * @param  string $title
240
     * @return string
241
     */
242 27
    public static function slug($title)
243
    {
244
        // Convert to ASCII
245 27
        foreach (static::charsArray() as $key => $value) {
246 27
            $title = str_replace($value, $key, $title);
247
        }
248
249
        // Remove unsupported characters
250 27
        $title = preg_replace('/[^\x20-\x7E]/u', '', $title);
251
252 27
        $separator = '_';
253
        // Convert all dashes into underscores
254 27
        $title = preg_replace('![' . preg_quote('-') . ']+!u', $separator, $title);
255
256
        // Remove all characters that are not valid in a URL: 
257
        // $-_.+!*'(), separator, letters, numbers, or whitespace.
258 27
        $title = preg_replace('![^-' . preg_quote($separator) . '\!\'\(\),\.\+\*\$\pL\pN\s]+!u', '', $title);
259
260
        // Replace all separator characters and whitespace by a single separator
261 27
        $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
262
263 27
        return trim($title, $separator);
264
    }
265
266
    /**
267
     * Returns the replacements for the slug() method.
268
     *
269
     * Taken from Stringy
270
     *
271
     * @return array An array of replacements.
272
     */
273 27
    public static function charsArray()
274
    {
275 27
        static $charsArray;
276
277 27
        if (isset($charsArray)) {
278 27
            return $charsArray;
279
        }
280
281
        return $charsArray = [
282 1
            'a'    => [
283
                'à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ',
284
                'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ä', 'ā', 'ą',
285
                'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ',
286
                'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ',
287
                'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', ],
288
            'b'    => ['б', 'β', 'Ъ', 'Ь', 'ب'],
289
            'c'    => ['ç', 'ć', 'č', 'ĉ', 'ċ'],
290
            'd'    => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ',
291
                'д', 'δ', 'د', 'ض', ],
292
            'e'    => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ',
293
                'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ',
294
                'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э',
295
                'є', 'ə', ],
296
            'f'    => ['ф', 'φ', 'ف'],
297
            'g'    => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج'],
298
            'h'    => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه'],
299
            'i'    => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į',
300
                'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ',
301
                'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ',
302
                'ῗ', 'і', 'ї', 'и', ],
303
            'j'    => ['ĵ', 'ј', 'Ј'],
304
            'k'    => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك'],
305
            'l'    => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل'],
306
            'm'    => ['м', 'μ', 'م'],
307
            'n'    => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن'],
308
            'o'    => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ',
309
                'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő',
310
                'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό',
311
                'ö', 'о', 'و', 'θ', ],
312
            'p'    => ['п', 'π'],
313
            'r'    => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر'],
314
            's'    => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص'],
315
            't'    => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط'],
316
            'u'    => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ',
317
                'ự', 'ü', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у', ],
318
            'v'    => ['в'],
319
            'w'    => ['ŵ', 'ω', 'ώ'],
320
            'x'    => ['χ'],
321
            'y'    => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ',
322
                'ϋ', 'ύ', 'ΰ', 'ي', ],
323
            'z'    => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز'],
324
            'aa'   => ['ع'],
325
            'ae'   => ['æ'],
326
            'ch'   => ['ч'],
327
            'dj'   => ['ђ', 'đ'],
328
            'dz'   => ['џ'],
329
            'gh'   => ['غ'],
330
            'kh'   => ['х', 'خ'],
331
            'lj'   => ['љ'],
332
            'nj'   => ['њ'],
333
            'oe'   => ['œ'],
334
            'ps'   => ['ψ'],
335
            'sh'   => ['ш'],
336
            'shch' => ['щ'],
337
            'ss'   => ['ß'],
338
            'th'   => ['þ', 'ث', 'ذ', 'ظ'],
339
            'ts'   => ['ц'],
340
            'ya'   => ['я'],
341
            'yu'   => ['ю'],
342
            'zh'   => ['ж'],
343
            '(c)'  => ['©'],
344
            'A'    => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ',
345
                'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Ä', 'Å', 'Ā',
346
                'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ',
347
                'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ',
348
                'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А', ],
349
            'B'    => ['Б', 'Β'],
350
            'C'    => ['Ç', 'Ć', 'Č', 'Ĉ', 'Ċ'],
351
            'D'    => ['Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'],
352
            'E'    => ['É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ',
353
                'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ',
354
                'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э',
355
                'Є', 'Ə', ],
356
            'F'    => ['Ф', 'Φ'],
357
            'G'    => ['Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ'],
358
            'H'    => ['Η', 'Ή'],
359
            'I'    => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į',
360
                'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ',
361
                'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї', ],
362
            'K'    => ['К', 'Κ'],
363
            'L'    => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ'],
364
            'M'    => ['М', 'Μ'],
365
            'N'    => ['Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν'],
366
            'O'    => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ',
367
                'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ö', 'Ø', 'Ō',
368
                'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ',
369
                'Ὸ', 'Ό', 'О', 'Θ', 'Ө', ],
370
            'P'    => ['П', 'Π'],
371
            'R'    => ['Ř', 'Ŕ', 'Р', 'Ρ'],
372
            'S'    => ['Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ'],
373
            'T'    => ['Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ'],
374
            'U'    => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ',
375
                'Ự', 'Û', 'Ü', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У', ],
376
            'V'    => ['В'],
377
            'W'    => ['Ω', 'Ώ'],
378
            'X'    => ['Χ'],
379
            'Y'    => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ',
380
                'Ы', 'Й', 'Υ', 'Ϋ', ],
381
            'Z'    => ['Ź', 'Ž', 'Ż', 'З', 'Ζ'],
382
            'AE'   => ['Æ'],
383
            'CH'   => ['Ч'],
384
            'DJ'   => ['Ђ'],
385
            'DZ'   => ['Џ'],
386
            'KH'   => ['Х'],
387
            'LJ'   => ['Љ'],
388
            'NJ'   => ['Њ'],
389
            'PS'   => ['Ψ'],
390
            'SH'   => ['Ш'],
391
            'SHCH' => ['Щ'],
392
            'SS'   => ['ẞ'],
393
            'TH'   => ['Þ'],
394
            'TS'   => ['Ц'],
395
            'YA'   => ['Я'],
396
            'YU'   => ['Ю'],
397
            'ZH'   => ['Ж'],
398
            ' '    => ["\xC2\xA0", "\xE2\x80\x80", "\xE2\x80\x81",
399
                "\xE2\x80\x82", "\xE2\x80\x83", "\xE2\x80\x84",
400
                "\xE2\x80\x85", "\xE2\x80\x86", "\xE2\x80\x87",
401
                "\xE2\x80\x88", "\xE2\x80\x89", "\xE2\x80\x8A",
402
                "\xE2\x80\xAF", "\xE2\x81\x9F", "\xE3\x80\x80", ],
403
        ];
404
    }
405
406
    /**
407
     * @param string $from
408
     * @param string $to
409
     * @return string
410
     */
411 12
    public static function getRelativePath($from, $to)
412
    {
413
        // some compatibility fixes for Windows paths
414 12
        $from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
415 12
        $to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
416 12
        $from = str_replace('\\', '/', $from);
417 12
        $to = str_replace('\\', '/', $to);
418
419 12
        $from = explode('/', $from);
420 12
        $to = explode('/', $to);
421 12
        $relPath = $to;
422
423 12
        foreach ($from as $depth => $dir) {
424
            // find first non-matching dir
425 12
            if ($dir === $to[$depth]) {
426
                // ignore this directory
427 8
                array_shift($relPath);
428
            } else {
429
                // get number of remaining dirs to $from
430 12
                $remaining = count($from) - $depth;
431 12
                if ($remaining > 1) {
432
                    // add traversals up to first matching dir
433 4
                    $padLength = (count($relPath) + $remaining - 1) * -1;
434 4
                    $relPath = array_pad($relPath, $padLength, '..');
435 4
                    break;
436 8
                } else {
437
                    //$relPath[0] = './' . $relPath[0];
438
                }
439
            }
440
        }
441
442 12
        return implode('/', $relPath);
443
    }
444
445
    public static function isAbsolutePath($path)
446
    {
447
        if (!is_string($path)) {
448
            $mess = sprintf('String expected but was given %s', gettype($path));
449
            throw new \InvalidArgumentException($mess);
450
        }
451
452
        if (!ctype_print($path)) {
453
            $mess = 'Path can NOT have non-printable characters or be empty';
454
            throw new \DomainException($mess);
455
        }
456
457
        // Optional wrapper(s).
458
        $regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
459
460
        // Optional root prefix.
461
        $regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
462
463
        // Actual path.
464
        $regExp .= '(?<path>(?:[[:print:]]*))$%';
465
466
        $parts = [];
467
        if (!preg_match($regExp, $path, $parts)) {
468
            $mess = sprintf('Path is NOT valid, was given %s', $path);
469
            throw new \DomainException($mess);
470
        }
471
472
        return '' !== $parts['root'];
473
    }
474
475
    public static function getAbsolutePath($path) {
476
        if (DauxHelper::isAbsolutePath($path)) {
477
            return $path;
478
        }
479
480
        return getcwd() . '/' . $path;
481
    }
482
483
    /**
484
     * @param string|null $path
485
     * @param string $basedir
486
     * @param string $var The constant name to check
487
     * @param "dir"|"file" $type
0 ignored issues
show
Documentation Bug introduced by Stéphane Goetz
The doc comment "dir"|"file" at position 0 could not be parsed: Unknown type name '"dir"' at position 0 in "dir"|"file".
Loading history...
488
     * @return false|null|string
489
     */
490
    public static function findLocation($path, $basedir, $var, $type) {
491
        // When running through `daux --serve` we set an environment variable to know where we started from
492
        $env = getenv($var);
493
        if ($env && DauxHelper::is($env, $type)) {
494
            return $env;
495
        }
496
497
        // If Path is explicitly null, it's useless to go further
498
        if ($path == null) {
499
            return null;
500
        }
501
502
        // Check if it's relative to the current directory or an absolute path
503
        if (DauxHelper::is($path, $type)) {
504
            return DauxHelper::getAbsolutePath($path);
505
        }
506
507
        // Check if it exists relative to Daux's root
508
        $newPath = $basedir . DIRECTORY_SEPARATOR . $path;
509
        if (DauxHelper::is($newPath, $type)) {
510
            return $newPath;
511
        }
512
513
        return false;
514
    }
515
516
    public static function is($path, $type) {
517
        return ($type == 'dir') ? is_dir($path) : file_exists($path);
518
    }
519
}
520