Passed
Branch refactor (5cbba0)
by Akihito
01:53
created

XmlConfigLoad::locateConfigFile()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 19
rs 9.2222
cc 6
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Koriym\DataFile;
6
7
use Koriym\DataFile\Exception\DataFileNotFoundException;
8
use SimpleXMLElement;
9
10
use function assert;
11
use function dirname;
12
use function file_exists;
13
use function getcwd;
14
use function is_dir;
15
use function is_file;
16
use function realpath;
17
use function sprintf;
18
19
final class XmlConfigLoad
20
{
21
    /** @var string */
22
    private $configName;
23
24
    /** @var XmlLoad */
25
    private $xmlLoad;
26
27
    public function __construct(string $configName)
28
    {
29
        $this->configName = $configName;
30
        $this->xmlLoad = new XmlLoad();
31
    }
32
33
    public function __invoke(string $xmlPath, string $xsdPath): SimpleXMLElement
34
    {
35
        $xmlFullPath = $this->locateConfigFile($xmlPath);
36
37
        return ($this->xmlLoad)($xmlFullPath, $xsdPath);
38
    }
39
40
    public function locateConfigFile(string $path): string
41
    {
42
        if (is_file($path)) {
43
            return $path;
44
        }
45
46
        $dirPath = realpath($path) ?: getcwd();
47
        assert(is_dir($dirPath));
48
49
        do {
50
            $maybePath = sprintf('%s/%s', $dirPath, $this->configName);
51
            if (file_exists($maybePath) || file_exists($maybePath .= '.dist')) {
52
                return $maybePath;
53
            }
54
55
            $dirPath = dirname($dirPath); // @phpstan-ignore-line
56
        } while (dirname($dirPath) !== $dirPath);
57
58
        throw new DataFileNotFoundException($path);
59
    }
60
}
61