Passed
Pull Request — master (#15)
by Takashi
02:58
created

AssetResolver::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 15
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Service;
6
7
class AssetResolver
8
{
9
    public const DEFAULT_CSS_PATH = 'build/default.css';
10
    public const DEFAULT_JS_PATH = 'build/default.js';
11
12
    private array $categoryBasedConfig;
13
    private array $tagBasedConfig;
14
15
    public function __construct(?array $config)
16
    {
17
        $this->categoryBasedConfig = [];
18
        $this->tagBasedConfig = [];
19
20
        foreach ((array) $config as $key => $value) {
21
            if (0 === strpos($key, '#')) {
22
                $this->tagBasedConfig[$key] = $value;
23
            } else {
24
                $this->categoryBasedConfig[$key] = $value;
25
            }
26
        }
27
28
        // deeper category should win.
29
        krsort($this->categoryBasedConfig, SORT_NATURAL);
30
    }
31
32
    public function getAssetPaths(?string $category, array $tags): array
33
    {
34
        $assetPaths = [
35
            'css' => self::DEFAULT_CSS_PATH,
36
            'js' => self::DEFAULT_JS_PATH,
37
        ];
38
39
        $categoryBasedAssetPaths = $this->getCategoryBasedAssetPaths($category);
40
        $tagBasedAssetPaths = $this->getTagBasedAssetPaths($tags);
41
42
        return array_merge($assetPaths, $categoryBasedAssetPaths, $tagBasedAssetPaths);
43
    }
44
45
    private function getCategoryBasedAssetPaths(?string $category): array
46
    {
47
        foreach ($this->categoryBasedConfig as $matcher => $paths) {
48
            if (preg_match(sprintf('#^%s#', $matcher), (string) $category)) {
49
                return $paths; // deeper category should match early.
50
            }
51
        }
52
53
        return [];
54
    }
55
56
    private function getTagBasedAssetPaths(?array $tags): array
57
    {
58
        foreach ($this->tagBasedConfig as $matcher => $paths) {
59
            if (in_array(substr($matcher, 1), (array) $tags)) {
60
                return $paths;
61
            }
62
        }
63
64
        return [];
65
    }
66
}
67