|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace BEAR\Package; |
|
6
|
|
|
|
|
7
|
|
|
use BEAR\AppMeta\AbstractAppMeta; |
|
8
|
|
|
use BEAR\Package\Exception\InvalidContextException; |
|
9
|
|
|
use BEAR\Package\Module\AppMetaModule; |
|
|
|
|
|
|
10
|
|
|
use Ray\Di\AbstractModule; |
|
11
|
|
|
use Ray\Di\AssistedModule; |
|
12
|
|
|
|
|
13
|
|
|
use function array_reverse; |
|
14
|
|
|
use function class_exists; |
|
15
|
|
|
use function explode; |
|
16
|
|
|
use function is_a; |
|
17
|
|
|
use function is_subclass_of; |
|
18
|
|
|
use function ucwords; |
|
19
|
|
|
|
|
20
|
|
|
class Module |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* Return module from $appMeta and $context |
|
24
|
|
|
*/ |
|
25
|
|
|
public function __invoke(AbstractAppMeta $appMeta, string $context): AbstractModule |
|
26
|
|
|
{ |
|
27
|
|
|
$contextsArray = array_reverse(explode('-', $context)); |
|
28
|
|
|
$module = new AssistedModule(); |
|
29
|
|
|
foreach ($contextsArray as $contextItem) { |
|
30
|
|
|
$module = $this->installContextModule($appMeta, $contextItem, $module); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$module->override(new AppMetaModule($appMeta)); |
|
34
|
|
|
|
|
35
|
|
|
return $module; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
private function installContextModule(AbstractAppMeta $appMeta, string $contextItem, AbstractModule $module): AbstractModule |
|
39
|
|
|
{ |
|
40
|
|
|
$class = $appMeta->name . '\Module\\' . ucwords($contextItem) . 'Module'; |
|
41
|
|
|
if (! class_exists($class)) { |
|
42
|
|
|
$class = 'BEAR\Package\Context\\' . ucwords($contextItem) . 'Module'; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
if (! is_a($class, AbstractModule::class, true)) { |
|
46
|
|
|
throw new InvalidContextException($contextItem); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** @psalm-suppress UnsafeInstantiation */ |
|
50
|
|
|
$module = is_subclass_of($class, AbstractAppModule::class) ? new $class($appMeta, $module) : new $class($module); |
|
51
|
|
|
|
|
52
|
|
|
return $module; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: