-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
SourceCollector.php
87 lines (71 loc) · 2.2 KB
/
SourceCollector.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
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Frontend\Compiler\Source;
use Closure;
/**
* @internal
*/
class SourceCollector
{
public function __construct(
protected array $allowedSourceTypes = []
) {
}
/**
* @var SourceInterface[]
*/
protected array $sources = [];
public function addFile(string $file, string $extensionId = null): static
{
$this->sources[] = $this->validateSourceType(
new FileSource($file, $extensionId)
);
return $this;
}
public function addString(Closure $callback): static
{
$this->sources[] = $this->validateSourceType(
new StringSource($callback)
);
return $this;
}
public function addDirectory(string $directory, string $extensionId = null): static
{
$this->sources[] = $this->validateSourceType(
new DirectorySource($directory, $extensionId)
);
return $this;
}
/**
* @return SourceInterface[]
*/
public function getSources(): array
{
return $this->sources;
}
protected function validateSourceType(SourceInterface $source): SourceInterface
{
// allowedSourceTypes is an array of class names (or interface names)
// so we need to check if the $source is an instance of one of those classes/interfaces (could be a parent class as well)
$isInstanceOfOneOfTheAllowedSourceTypes = false;
foreach ($this->allowedSourceTypes as $allowedSourceType) {
if ($source instanceof $allowedSourceType) {
$isInstanceOfOneOfTheAllowedSourceTypes = true;
break;
}
}
if (! empty($this->allowedSourceTypes) && ! $isInstanceOfOneOfTheAllowedSourceTypes) {
throw new \InvalidArgumentException(sprintf(
'Source type %s is not allowed for this collector. Allowed types are: %s',
$source::class,
implode(', ', $this->allowedSourceTypes)
));
}
return $source;
}
}