Passed
Pull Request — master (#33)
by Sander
02:52 queued 01:02
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
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();
60
        $path = $this->isWildCard() ? substr($this->path, -1) : $this->path;
61
62
        $real = realpath($workingDirectory . DIRECTORY_SEPARATOR . $path);
63
        if ($real === false) {
64
            throw new InvalidArgumentException(
65
                sprintf('Cannot resolve absolute path to %s.', $path)
66
            );
67
        }
68
69
        if ($this->isWildCard()) {
70
            $real .= DIRECTORY_SEPARATOR . '*';
71
        }
72
73
        return new PathHelper($real);
74
    }
75
76
    public function getNormalizedPath(): string
77
    {
78
        if (substr($this->path, -1) === DIRECTORY_SEPARATOR) {
79
            return substr($this->path, 0, -1);
80
        }
81
82
        return $this->path;
83
    }
84
}
85