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

AssetResolver::getTagBasedAssetPaths()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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