1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WebComplete\core\package; |
4
|
|
|
|
5
|
|
|
use WebComplete\core\utils\helpers\ClassHelper; |
6
|
|
|
|
7
|
|
|
class PackageManager |
8
|
|
|
{ |
9
|
|
|
|
10
|
|
|
const FILENAME = 'Package.php'; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var ClassHelper |
14
|
|
|
*/ |
15
|
|
|
protected $classHelper; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
protected $registered = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param ClassHelper $classHelper |
24
|
|
|
*/ |
25
|
|
|
public function __construct(ClassHelper $classHelper) |
26
|
|
|
{ |
27
|
|
|
$this->classHelper = $classHelper; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param $packageClassName |
32
|
|
|
* |
33
|
|
|
* @return AbstractPackage |
34
|
|
|
* @throws PackageException |
35
|
|
|
*/ |
36
|
|
|
public function getPackage($packageClassName): AbstractPackage |
37
|
|
|
{ |
38
|
|
|
if (!isset($this->registered[$packageClassName])) { |
39
|
|
|
throw new PackageException($packageClassName . ' is not registered'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $this->registered[$packageClassName]; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param $packageClassName |
47
|
|
|
* @param array $definitions |
48
|
|
|
* |
49
|
|
|
* @throws PackageException |
50
|
|
|
*/ |
51
|
|
|
public function register($packageClassName, array &$definitions) |
52
|
|
|
{ |
53
|
|
|
if (!isset($this->registered[$packageClassName])) { |
54
|
|
|
$package = new $packageClassName; |
55
|
|
|
if (!$package instanceof AbstractPackage) { |
56
|
|
|
throw new PackageException($packageClassName . ' is not an instance of ' . AbstractPackage::class); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$package->registerDependencies($definitions); |
60
|
|
|
$this->registered[$packageClassName] = $package; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param string $directory |
66
|
|
|
* @param array $definitions |
67
|
|
|
* |
68
|
|
|
* @throws \Exception |
69
|
|
|
*/ |
70
|
|
|
public function registerAll(string $directory, array &$definitions) |
71
|
|
|
{ |
72
|
|
|
$classMap = $this->findAll($directory); |
73
|
|
|
foreach ($classMap as $class) { |
74
|
|
|
$this->register($class, $definitions); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param $directory |
80
|
|
|
* |
81
|
|
|
* @return array [file => class] |
82
|
|
|
* @throws \Exception |
83
|
|
|
* @throws \InvalidArgumentException |
84
|
|
|
*/ |
85
|
|
|
public function findAll($directory): array |
86
|
|
|
{ |
87
|
|
|
return $this->classHelper->getClassMap($directory, self::FILENAME); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|