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

PathHelper::getPathsFromWildcard()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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