Passed
Pull Request — master (#33)
by Sander
01:54
created

PathHelper::getPathsFromWildcard()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 7
c 3
b 0
f 0
dl 0
loc 14
rs 10
cc 3
nc 3
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
    // TODO this doesn't work with glob, or we only allow /* on the end of the path
33
    public function isWildCard(): bool
34
    {
35
        return substr($this->path, -2) === '/*';
36
    }
37
38
    /**
39
     * @return PathHelper[]
40
     */
41
    public function getPathsFromWildcard(): array
42
    {
43
        $entries = glob($this->path, GLOB_ONLYDIR);
44
        if ($entries === false) {
45
            throw new RuntimeException(sprintf('Cannot read directory "%s"', $this->path));
46
        }
47
48
        // TODO Somehow we should skip directories that don't have a valid composer.json
49
        $helpers = [];
50
        foreach ($entries as $entry) {
51
            $helpers[] = new PathHelper($entry);
52
        }
53
54
        return $helpers;
55
    }
56
57
    public function toAbsolutePath(string $workingDirectory): PathHelper
58
    {
59
        // TODO this doesn't work with glob(), or we just have to allow /* on the end as wildcard
60
        $path = $this->isWildCard() ? substr($this->path, -1) : $this->path;
61
62
        // TODO we can also skip the realpath call and do this in a later stage
63
        $real = realpath($workingDirectory . DIRECTORY_SEPARATOR . $path);
64
        if ($real === false) {
65
            throw new InvalidArgumentException(
66
                sprintf('Cannot resolve absolute path to %s.', $path)
67
            );
68
        }
69
70
        if ($this->isWildCard()) {
71
            $real .= DIRECTORY_SEPARATOR . '*';
72
        }
73
74
        return new PathHelper($real);
75
    }
76
77
    public function getNormalizedPath(): string
78
    {
79
        if (substr($this->path, -1) === DIRECTORY_SEPARATOR) {
80
            return substr($this->path, 0, -1);
81
        }
82
83
        return $this->path;
84
    }
85
}
86