Completed
Pull Request — master (#24)
by Thomas
02:16
created

ScriptFinder::getAllScripts()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 7
nop 0
1
<?php declare(strict_types=1);
2
3
4
namespace Shopware\Psh\Listing;
5
6
/**
7
 * Load all scripts from all the supplied paths and create an array of scripts
8
 */
9
class ScriptFinder
10
{
11
    const VALID_EXTENSIONS = [
12
        'sh',
13
        'psh'
14
    ];
15
16
    /**
17
     * @var string[]
18
     */
19
    private $scriptPaths;
20
21
    /**
22
     * @param string[] $scriptPaths
23
     */
24
    public function __construct(array $scriptPaths)
25
    {
26
        $this->scriptPaths = $scriptPaths;
27
    }
28
29
    /**
30
     * @return Script[]
31
     * @throws ScriptPathNotValidException
32
     */
33
    public function getAllScripts(): array
34
    {
35
        $scripts = [];
36
37
        foreach ($this->scriptPaths as $pathNamespace => $path) {
38
            if (!is_dir($path)) {
39
                throw new ScriptPathNotValidException("The given script path: '{$path}' is not a valid directory");
40
            }
41
42
            foreach (scandir($path) as $fileName) {
43
                $scriptNamespace = null;
44
45
                if (strpos($fileName, '.') === 0) {
46
                    continue;
47
                }
48
49
                $extension = pathinfo($fileName, PATHINFO_EXTENSION);
50
51
                if (!in_array($extension, self::VALID_EXTENSIONS)) {
52
                    continue;
53
                }
54
55
                if (!is_numeric($pathNamespace)) {
56
                    $scriptNamespace = $pathNamespace;
57
                }
58
59
                $scripts[] = new Script($path, $fileName, $scriptNamespace);
60
            }
61
        }
62
63
        return $scripts;
64
    }
65
66
    /**
67
     * @param string $scriptName
68
     * @return Script
69
     * @throws ScriptNotFoundException
70
     */
71
    public function findScriptByName(string $scriptName): Script
72
    {
73
        foreach ($this->getAllScripts() as $script) {
74
            if ($script->getName() === $scriptName) {
75
                return $script;
76
            }
77
        }
78
79
        throw new ScriptNotFoundException('Unable to find script named "' . $scriptName . '"');
80
    }
81
}
82