Passed
Pull Request — master (#33)
by Sander
02:09
created

PathHelper::getPathsFromWildcard()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
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 17
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
    public function __construct(string $path)
26
    {
27
        $this->path = $path;
28
    }
29
30
    public function isWildCard(): bool
31
    {
32
        return substr($this->path, -2) === '/*';
33
    }
34
35
    /**
36
     * @return PathHelper[]
37
     */
38
    public function getPathsFromWildcard(): array
39
    {
40
        $entries = glob($this->path, GLOB_ONLYDIR);
41
        if ($entries === false) {
42
            throw new RuntimeException(sprintf('Cannot read directory "%s"', $this->path));
43
        }
44
45
        $helpers = [];
46
        foreach ($entries as $entry) {
47
            if (!file_exists($entry . DIRECTORY_SEPARATOR . 'composer.json')) {
48
                continue;
49
            }
50
51
            $helpers[] = new PathHelper($entry);
52
        }
53
54
        return $helpers;
55
    }
56
57
    public function toAbsolutePath(string $workingDirectory): PathHelper
58
    {
59
        $path = $this->isWildCard() ? substr($this->path, 0, -1) : $this->path;
60
        $real = realpath($workingDirectory . DIRECTORY_SEPARATOR . $path);
61
62
        if ($real === false) {
63
            throw new InvalidArgumentException(
64
                sprintf('Cannot resolve absolute path to %s.', $path)
65
            );
66
        }
67
68
        if ($this->isWildCard()) {
69
            $real .= DIRECTORY_SEPARATOR . '*';
70
        }
71
72
        return new PathHelper($real);
73
    }
74
75
    public function getNormalizedPath(): string
76
    {
77
        if (substr($this->path, -1) === DIRECTORY_SEPARATOR) {
78
            return substr($this->path, 0, -1);
79
        }
80
81
        return $this->path;
82
    }
83
}
84