InstructionsetAutoloader   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A load() 0 26 3
A createDirIterator() 0 8 1
1
<?php
2
/**
3
 * Webino (http://webino.sk)
4
 *
5
 * @link        https://github.com/webino/WebinoDraw for the canonical source repository
6
 * @copyright   Copyright (c) 2012-2017 Webino, s. r. o. (http://webino.sk)
7
 * @author      Peter Bačinský <[email protected]>
8
 * @license     BSD-3-Clause
9
 */
10
11
namespace WebinoDraw\Config;
12
13
use RecursiveDirectoryIterator;
14
use RecursiveIteratorIterator;
15
use RegexIterator;
16
17
/**
18
 * Used in configs to automatically load the drawsets
19
 */
20
class InstructionsetAutoloader
21
{
22
    const DRAWSET_CFG_SUFFIX = '.drawset.php';
23
24
    /**
25
     * @var string
26
     */
27
    protected $dir;
28
29
    /**
30
     * @param string $dir
31
     */
32
    public function __construct($dir)
33
    {
34
        $this->dir = $dir;
35
    }
36
37
    /**
38
     * @return array
39
     */
40
    public function load()
41
    {
42
        $config       = [];
43
        $dirLength    = strlen($this->dir) + 1;
44
        $suffixLength = strlen(self::DRAWSET_CFG_SUFFIX);
45
46
        foreach ($this->createDirIterator($this->dir) as $path) {
47
48
            $relPath   = substr($path[0], $dirLength);
49
            $namespace = explode('/', $relPath)[0];
50
51
            $index = join(
52
                '/',
53
                array_filter([
54
                    $namespace,
55
                    trim(substr($relPath, strlen($namespace), - $suffixLength), '/'),
56
                ])
57
            );
58
59
            /** @noinspection PhpIncludeInspection */
60
            $drawSpec = require $path[0];
61
            $config[$index] = is_array($drawSpec) ? $drawSpec : $drawSpec->toArray();
62
        }
63
64
        return $config;
65
    }
66
67
    /**
68
     * @param string $dir
69
     * @return RegexIterator
70
     */
71
    private function createDirIterator($dir)
72
    {
73
        return new RegexIterator(
74
            new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)),
75
            '/^.+' . preg_quote(self::DRAWSET_CFG_SUFFIX) . '$/i',
76
            RegexIterator::GET_MATCH
77
        );
78
    }
79
}
80