| 1 |
<?php declare(strict_types=1); |
| 2 |
|
| 3 |
namespace OpenApi; |
| 4 |
|
| 5 |
use Symfony\Component\Finder\Finder; |
| 6 |
|
| 7 |
/** |
| 8 |
* Custom Symfony `Finder` that understands `swagger-php` CLI options. |
| 9 |
*/ |
| 10 |
class SourceFinder extends Finder |
| 11 |
{ |
| 12 |
public function __construct(string|array $directory, null|array|string $exclude = null, string $pattern = '*.php') |
| 13 |
{ |
| 14 |
parent::__construct(); |
| 15 |
|
| 16 |
$this |
| 17 |
->sortByName() |
| 18 |
->files() |
| 19 |
->followLinks() |
| 20 |
->name($pattern); |
| 21 |
|
| 22 |
$directories = (array) $directory; |
| 23 |
|
| 24 |
foreach ($directories as $path) { |
| 25 |
if (is_file($path)) { |
| 26 |
$this->append([$path]); |
| 27 |
} else { |
| 28 |
$this->in($path); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
foreach ((array) $exclude as $path) { |
| 33 |
$this->notPath($this->getRelativePath($path, $directories)); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Turns the given $fullPath into a relative path based on $basePaths, which can either |
| 39 |
* be a single string path, or a list of possible paths. If a list is given, the first |
| 40 |
* matching basePath in the list will be used to compute the relative path. If no |
| 41 |
* relative path could be computed, the original string will be returned because there |
| 42 |
* is always a chance it was a valid relative path to begin with. |
| 43 |
* |
| 44 |
* It should be noted that these are "relative paths" primarily in Finder's sense of them, |
| 45 |
* and conform specifically to what is expected by functions like <code>exclude()</code> and <code>notPath()</code>. |
| 46 |
* |
| 47 |
* In particular, leading and trailing slashes are removed. |
| 48 |
*/ |
| 49 |
private function getRelativePath(string $fullPath, array $directories): string |
| 50 |
{ |
| 51 |
foreach ($directories as $directory) { |
| 52 |
if (str_starts_with($fullPath, (string) $directory)) { |
| 53 |
$relativePath = substr($fullPath, strlen((string) $directory)); |
| 54 |
|
| 55 |
if ($relativePath !== '' && $relativePath !== '0') { |
| 56 |
return trim($relativePath, '/'); |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
return $fullPath; |
| 62 |
} |
| 63 |
} |