Completed
Pull Request — master (#32)
by Jan Philipp
02:01
created

ScriptFinder::getAllScripts()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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