Passed
Pull Request — master (#33)
by Sander
07:14
created

PathHelper::getNormalizedPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the composer-link plugin.
7
 *
8
 * Copyright (c) 2021-2022 Sander Visser <[email protected]>.
9
 *
10
 * For the full copyright and license information, please view the LICENSE.md
11
 * file that was distributed with this source code.
12
 *
13
 * @link https://github.com/SanderSander/composer-link
14
 */
15
16
namespace ComposerLink;
17
18
use InvalidArgumentException;
19
use RuntimeException;
20
21
class PathHelper
22
{
23
    protected string $path;
24
25
    protected string $absolutePath;
26
27
    public function __construct(string $path)
28
    {
29
        $this->path = $path;
30
    }
31
32
    public function isWildCard(): bool
33
    {
34
        return substr($this->path, -1) === '*';
35
    }
36
37
    /**
38
     * @return PathHelper[]
39
     */
40
    public function getPathsFromWildcard(): array
41
    {
42
        $path = substr($this->path, -1);
43
        $paths = [];
44
45
        $entries = scandir($path);
46
47
        if ($entries === false) {
48
            throw new RuntimeException(sprintf('Cannot read directory "%s"', $this->path));
49
        }
50
51
        foreach ($entries as $entry) {
52
            if (is_dir($entry)) {
53
                $paths[] = new PathHelper($entry);
54
            }
55
        }
56
57
        return $paths;
58
    }
59
60
    public function toAbsolutePath(string $workingDirectory): PathHelper
61
    {
62
        $path = $this->isWildCard() ? substr($this->path, -1) : $this->path;
63
64
        $real = realpath($workingDirectory . DIRECTORY_SEPARATOR . $path);
65
        if ($real === false) {
66
            throw new InvalidArgumentException(
67
                sprintf('Cannot resolve absolute path to %s.', $path)
68
            );
69
        }
70
71
        if ($this->isWildCard()) {
72
            $real .= DIRECTORY_SEPARATOR . '*';
73
        }
74
75
        return new PathHelper($real);
76
    }
77
78
    public function getNormalizedPath(): string
79
    {
80
        if (substr($this->path, -1) === DIRECTORY_SEPARATOR) {
81
            return substr($this->path, 0, -1);
82
        }
83
84
        return $this->path;
85
    }
86
}
87