-
Notifications
You must be signed in to change notification settings - Fork 16
/
Importer.php
97 lines (80 loc) 路 2.86 KB
/
Importer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace Castor\Import;
use Castor\Import\Exception\ImportError;
use Castor\Import\Exception\RemoteNotAllowed;
use Castor\Import\Remote\PackageImporter;
use Psr\Log\LoggerInterface;
use Symfony\Component\Finder\Finder;
use function Castor\castor_require;
use function Castor\fix_exception;
/** @internal */
class Importer
{
public function __construct(
private readonly PackageImporter $packageImporter,
private readonly LoggerInterface $logger,
) {
}
/** @phpstan-param ImportSource $source */
public function import(string $path, ?string $file = null, ?string $version = null, ?string $vcs = null, ?array $source = null): void
{
$scheme = parse_url($path, \PHP_URL_SCHEME);
if ($scheme) {
$package = mb_substr($path, mb_strlen($scheme) + 3);
try {
$this->packageImporter->importPackage(
$scheme,
$package,
$file,
$version,
$vcs,
$source,
);
return;
} catch (ImportError $e) {
throw $this->createImportException($package, $e->getMessage(), $e);
} catch (RemoteNotAllowed $e) {
$this->logger->warning($this->getImportLocatedMessage($path, $e->getMessage(), 1));
return;
}
} elseif (null !== $file || null !== $version || null !== $vcs || null !== $source) {
throw $this->createImportException($path, 'The "file", "version", "vcs" and "source" arguments can only be used with a remote import.');
}
if (!file_exists($path)) {
throw $this->createImportException($path, sprintf('The file "%s" does not exist.', $path));
}
if (is_file($path)) {
castor_require($path);
}
if (is_dir($path)) {
$files = Finder::create()
->files()
->name('*.php')
->in($path)
;
foreach ($files as $file) {
castor_require($file->getPathname());
}
}
}
private function getImportLocatedMessage(string $path, string $reason, int $depth): string
{
/** @var array{file: string, line: int} $caller */
$caller = debug_backtrace()[$depth + 1];
return sprintf(
'Could not import "%s" in "%s" on line %d. Reason: %s',
$path,
$caller['file'],
$caller['line'],
$reason,
);
}
private function createImportException(string $path, string $message, ?\Throwable $e = null): \Throwable
{
$depth = 2;
return fix_exception(
new \InvalidArgumentException($this->getImportLocatedMessage($path, $message, $depth), previous: $e),
$depth
);
}
}