XmlConfigLoad::locateConfigFile()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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