DauxHelper   F
last analyzed

Complexity

Total Complexity 60

Size/Duplication

Total Lines 509
Duplicated Lines 0 %

Test Coverage

Coverage 35.44%

Importance

Changes 0
Metric Value
eloc 274
dl 0
loc 509
ccs 56
cts 158
cp 0.3544
rs 3.6
c 0
b 0
f 0
wmc 60

13 Methods

Rating   Name   Duplication   Size   Complexity  
A is() 0 2 2
B charsArray() 0 130 2
A slug() 0 19 2
A resolveVariant() 0 22 5
A getAbsolutePath() 0 6 2
A rebaseConfiguration() 0 11 3
A getFilenames() 0 8 1
B getTheme() 0 64 11
A getCleanPath() 0 17 4
A isAbsolutePath() 0 28 4
C getFile() 0 60 12
A getRelativePath() 0 32 6
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 13
    public static function getFilenames(Config $config, $part)
156
    {
157 13
        $extensions = implode('|', array_map('preg_quote', $config['valid_content_extensions'])) . '|html';
158
159 13
        $raw = preg_replace('/(.*)?\\.(' . $extensions . ')$/', '$1', $part);
160 13
        $raw = Builder::removeSortingInformations($raw);
161
162 13
        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 14
    public static function getFile($tree, $request)
173
    {
174 14
        $request = explode('/', $request);
175 14
        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 14
            if (!$tree instanceof Directory) {
179
                return false;
180
            }
181
182
            // Some relative paths may start with ./
183 14
            if ($node == '.') {
184 3
                continue;
185
            }
186
187 14
            if ($node == '..') {
188 1
                $tree = $tree->getParent();
189 1
                continue;
190
            }
191
192 14
            $node = 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 14
            if (isset($tree->getEntries()[$node])) {
198 14
                $tree = $tree->getEntries()[$node];
199 14
                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 9
            foreach (static::getFilenames($tree->getConfig(), $node) as $filename) {
206 9
                if (isset($tree->getEntries()[$filename])) {
207 9
                    $tree = $tree->getEntries()[$filename];
208 9
                    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
            if ($node !== 'index' && $node !== 'index.html') {
216
                return false;
217
            }
218
219
            return $tree->getIndexPage();
220
        }
221
222
        // If the entry we found is not a directory, we're done
223 14
        if (!$tree instanceof Directory) {
224 14
            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 6
    public static function slug($title)
243
    {
244 6
        foreach (static::charsArray() as $key => $value) {
245 6
            $title = str_replace($value, $key, $title);
246
        }
247
248 6
        $title = preg_replace('/[^\x20-\x7E]/u', '', $title);
249
250 6
        $separator = '_';
251
        // Convert all dashes into underscores
252 6
        $title = preg_replace('![' . preg_quote('-') . ']+!u', $separator, $title);
253
254
        // Remove all characters that are not the separator, letters, numbers, or whitespace.
255 6
        $title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', $title);
256
257
        // Replace all separator characters and whitespace by a single separator
258 6
        $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
259
260 6
        return trim($title, $separator);
261
    }
262
263
    /**
264
     * Returns the replacements for the slug() method.
265
     *
266
     * Taken from Stringy
267
     *
268
     * @return array An array of replacements.
269
     */
270 6
    public static function charsArray()
271
    {
272 6
        static $charsArray;
273
274 6
        if (isset($charsArray)) {
275 5
            return $charsArray;
276
        }
277
278
        return $charsArray = [
279 1
            'a'    => [
280
                'à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ',
281
                'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ä', 'ā', 'ą',
282
                'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ',
283
                'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ',
284
                'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', ],
285
            'b'    => ['б', 'β', 'Ъ', 'Ь', 'ب'],
286
            'c'    => ['ç', 'ć', 'č', 'ĉ', 'ċ'],
287
            'd'    => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ',
288
                'д', 'δ', 'د', 'ض', ],
289
            'e'    => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ',
290
                'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ',
291
                'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э',
292
                'є', 'ə', ],
293
            'f'    => ['ф', 'φ', 'ف'],
294
            'g'    => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج'],
295
            'h'    => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه'],
296
            'i'    => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į',
297
                'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ',
298
                'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ',
299
                'ῗ', 'і', 'ї', 'и', ],
300
            'j'    => ['ĵ', 'ј', 'Ј'],
301
            'k'    => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك'],
302
            'l'    => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل'],
303
            'm'    => ['м', 'μ', 'م'],
304
            'n'    => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن'],
305
            'o'    => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ',
306
                'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő',
307
                'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό',
308
                'ö', 'о', 'و', 'θ', ],
309
            'p'    => ['п', 'π'],
310
            'r'    => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر'],
311
            's'    => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص'],
312
            't'    => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط'],
313
            'u'    => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ',
314
                'ự', 'ü', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у', ],
315
            'v'    => ['в'],
316
            'w'    => ['ŵ', 'ω', 'ώ'],
317
            'x'    => ['χ'],
318
            'y'    => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ',
319
                'ϋ', 'ύ', 'ΰ', 'ي', ],
320
            'z'    => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز'],
321
            'aa'   => ['ع'],
322
            'ae'   => ['æ'],
323
            'ch'   => ['ч'],
324
            'dj'   => ['ђ', 'đ'],
325
            'dz'   => ['џ'],
326
            'gh'   => ['غ'],
327
            'kh'   => ['х', 'خ'],
328
            'lj'   => ['љ'],
329
            'nj'   => ['њ'],
330
            'oe'   => ['œ'],
331
            'ps'   => ['ψ'],
332
            'sh'   => ['ш'],
333
            'shch' => ['щ'],
334
            'ss'   => ['ß'],
335
            'th'   => ['þ', 'ث', 'ذ', 'ظ'],
336
            'ts'   => ['ц'],
337
            'ya'   => ['я'],
338
            'yu'   => ['ю'],
339
            'zh'   => ['ж'],
340
            '(c)'  => ['©'],
341
            'A'    => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ',
342
                'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Ä', 'Å', 'Ā',
343
                'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ',
344
                'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ',
345
                'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А', ],
346
            'B'    => ['Б', 'Β'],
347
            'C'    => ['Ç', 'Ć', 'Č', 'Ĉ', 'Ċ'],
348
            'D'    => ['Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'],
349
            'E'    => ['É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ',
350
                'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ',
351
                'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э',
352
                'Є', 'Ə', ],
353
            'F'    => ['Ф', 'Φ'],
354
            'G'    => ['Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ'],
355
            'H'    => ['Η', 'Ή'],
356
            'I'    => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į',
357
                'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ',
358
                'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї', ],
359
            'K'    => ['К', 'Κ'],
360
            'L'    => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ'],
361
            'M'    => ['М', 'Μ'],
362
            'N'    => ['Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν'],
363
            'O'    => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ',
364
                'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ö', 'Ø', 'Ō',
365
                'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ',
366
                'Ὸ', 'Ό', 'О', 'Θ', 'Ө', ],
367
            'P'    => ['П', 'Π'],
368
            'R'    => ['Ř', 'Ŕ', 'Р', 'Ρ'],
369
            'S'    => ['Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ'],
370
            'T'    => ['Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ'],
371
            'U'    => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ',
372
                'Ự', 'Û', 'Ü', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У', ],
373
            'V'    => ['В'],
374
            'W'    => ['Ω', 'Ώ'],
375
            'X'    => ['Χ'],
376
            'Y'    => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ',
377
                'Ы', 'Й', 'Υ', 'Ϋ', ],
378
            'Z'    => ['Ź', 'Ž', 'Ż', 'З', 'Ζ'],
379
            'AE'   => ['Æ'],
380
            'CH'   => ['Ч'],
381
            'DJ'   => ['Ђ'],
382
            'DZ'   => ['Џ'],
383
            'KH'   => ['Х'],
384
            'LJ'   => ['Љ'],
385
            'NJ'   => ['Њ'],
386
            'PS'   => ['Ψ'],
387
            'SH'   => ['Ш'],
388
            'SHCH' => ['Щ'],
389
            'SS'   => ['ẞ'],
390
            'TH'   => ['Þ'],
391
            'TS'   => ['Ц'],
392
            'YA'   => ['Я'],
393
            'YU'   => ['Ю'],
394
            'ZH'   => ['Ж'],
395
            ' '    => ["\xC2\xA0", "\xE2\x80\x80", "\xE2\x80\x81",
396
                "\xE2\x80\x82", "\xE2\x80\x83", "\xE2\x80\x84",
397
                "\xE2\x80\x85", "\xE2\x80\x86", "\xE2\x80\x87",
398
                "\xE2\x80\x88", "\xE2\x80\x89", "\xE2\x80\x8A",
399
                "\xE2\x80\xAF", "\xE2\x81\x9F", "\xE3\x80\x80", ],
400
        ];
401
    }
402
403
    /**
404
     * @param string $from
405
     * @param string $to
406
     * @return string
407
     */
408 9
    public static function getRelativePath($from, $to)
409
    {
410
        // some compatibility fixes for Windows paths
411 9
        $from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
412 9
        $to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
413 9
        $from = str_replace('\\', '/', $from);
414 9
        $to = str_replace('\\', '/', $to);
415
416 9
        $from = explode('/', $from);
417 9
        $to = explode('/', $to);
418 9
        $relPath = $to;
419
420 9
        foreach ($from as $depth => $dir) {
421
            // find first non-matching dir
422 9
            if ($dir === $to[$depth]) {
423
                // ignore this directory
424 7
                array_shift($relPath);
425
            } else {
426
                // get number of remaining dirs to $from
427 9
                $remaining = count($from) - $depth;
428 9
                if ($remaining > 1) {
429
                    // add traversals up to first matching dir
430 2
                    $padLength = (count($relPath) + $remaining - 1) * -1;
431 2
                    $relPath = array_pad($relPath, $padLength, '..');
432 2
                    break;
433 7
                } else {
434
                    //$relPath[0] = './' . $relPath[0];
435
                }
436
            }
437
        }
438
439 9
        return implode('/', $relPath);
440
    }
441
442
    public static function isAbsolutePath($path)
443
    {
444
        if (!is_string($path)) {
445
            $mess = sprintf('String expected but was given %s', gettype($path));
446
            throw new \InvalidArgumentException($mess);
447
        }
448
449
        if (!ctype_print($path)) {
450
            $mess = 'Path can NOT have non-printable characters or be empty';
451
            throw new \DomainException($mess);
452
        }
453
454
        // Optional wrapper(s).
455
        $regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
456
457
        // Optional root prefix.
458
        $regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
459
460
        // Actual path.
461
        $regExp .= '(?<path>(?:[[:print:]]*))$%';
462
463
        $parts = [];
464
        if (!preg_match($regExp, $path, $parts)) {
465
            $mess = sprintf('Path is NOT valid, was given %s', $path);
466
            throw new \DomainException($mess);
467
        }
468
469
        return '' !== $parts['root'];
470
    }
471
472
    public static function getAbsolutePath($path) {
473
        if (DauxHelper::isAbsolutePath($path)) {
474
            return $path;
475
        }
476
477
        return getcwd() . '/' . $path;
478
    }
479
480
    /**
481
     * @param string|null $path
482
     * @param string $basedir
483
     * @param string $var The constant name to check
484
     * @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...
485
     * @return false|null|string
486
     */
487
    public static function findLocation($path, $basedir, $var, $type) {
488
        // When running through `daux --serve` we set an environment variable to know where we started from
489
        $env = getenv($var);
490
        if ($env && DauxHelper::is($env, $type)) {
491
            return $env;
492
        }
493
494
        // If Path is explicitly null, it's useless to go further
495
        if ($path == null) {
496
            return null;
497
        }
498
499
        // Check if it's relative to the current directory or an absolute path
500
        if (DauxHelper::is($path, $type)) {
501
            return DauxHelper::getAbsolutePath($path);
502
        }
503
504
        // Check if it exists relative to Daux's root
505
        $newPath = $basedir . DIRECTORY_SEPARATOR . $path;
506
        if (DauxHelper::is($newPath, $type)) {
507
            return $newPath;
508
        }
509
510
        return false;
511
    }
512
513
    public static function is($path, $type) {
514
        return ($type == 'dir') ? is_dir($path) : file_exists($path);
515
    }
516
}
517