Completed
Push — master ( b0f33b...4b59d8 )
by Takashi
03:26
created

AssetResolver::getAssetPaths()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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