Folder::getScript()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 1
dl 0
loc 17
ccs 8
cts 8
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Conia\Quma;
6
7
use RuntimeException;
8
9
/** @psalm-api */
10
class Folder
11
{
12
    protected Database $db;
13
    protected string $folder;
14
15 26
    public function __construct(Database $db, string $folder)
16
    {
17 26
        $this->db = $db;
18 26
        $this->folder = $folder;
19
    }
20
21 2
    public function __get(string $key): Script
22
    {
23 2
        return $this->getScript($key);
24
    }
25
26 24
    public function __call(string $key, array $args): Query
27
    {
28 24
        $script = $this->getScript($key);
29
30 24
        return $script->invoke(...$args);
31
    }
32
33 26
    protected function scriptPath(string $key, bool $isTemplate): bool|string
34
    {
35 26
        $ext = $isTemplate ? '.tpql' : '.sql';
36
37 26
        foreach ($this->db->getSqlDirs() as $path) {
38
            assert(is_string($path));
39 26
            $result = $path . DIRECTORY_SEPARATOR .
40 26
                $this->folder . DIRECTORY_SEPARATOR .
41 26
                $key . $ext;
42
43 26
            if (is_file($result)) {
44 25
                return $result;
45
            }
46
        }
47
48 6
        return false;
49
    }
50
51 26
    protected function readScript(string $key): string|false
52
    {
53 26
        $script = $this->scriptPath($key, false);
54
55 26
        if ($script && is_string($script)) {
56 20
            return file_get_contents($script);
57
        }
58
59 6
        return false;
60
    }
61
62 26
    protected function getScript(string $key): Script
63
    {
64 26
        $stmt = $this->readScript($key);
65
66 26
        if ($stmt) {
67 20
            return new Script($this->db, $stmt, false);
68
        }
69
70
        // If $stmt is not truthy until now,
71
        // assume the script is a dnyamic sql template
72 6
        $dynStmt = $this->scriptPath($key, true);
73
74 6
        if ($dynStmt && is_string($dynStmt)) {
75 5
            return new Script($this->db, $dynStmt, true);
76
        }
77
78 1
        throw new RuntimeException('SQL script does not exist');
79
    }
80
}
81