Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to load all modules from dependecy array #35

Open
wants to merge 7 commits into
base: 2.12.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
[![Build Status](https://github.com/laminas/laminas-modulemanager/workflows/Continuous%20Integration/badge.svg)](https://github.com/laminas/laminas-modulemanager/actions?query=workflow%3A"Continuous+Integration")

> ## 🇷🇺 Русским гражданам
>
>
> Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
>
>
> У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
>
>
> Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
>
>
> ## 🇺🇸 To Citizens of Russia
>
>
> We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
>
>
> One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
>
>
> You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

`Laminas\ModuleManager` introduces a new and powerful approach to modules. This new
Expand Down
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
"psr-4": {
"ListenerTestModule\\": "test/TestAsset/ListenerTestModule/",
"ModuleAsClass\\": "test/TestAsset/ModuleAsClass/",
"DependencyModule\\": "test/TestAsset/DependencyModule/",
"SomeModule\\": "test/TestAsset/SomeModule/",
"LaminasTest\\ModuleManager\\": "test/"
}
},
Expand Down
423 changes: 217 additions & 206 deletions composer.lock

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions docs/book/module-manager.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,36 @@ loaded. When a module class implements
against the loaded modules list: if one of the values is not in that list, a
`Laminas\ModuleManager\Exception\MissingDependencyModuleException` is thrown.

> ### Enable the Dependency Autoloader
>
> If the option load dependencies is activated, the ModuleDependencyCheckerListener will try to reload a missing
> dependency. So no `Laminas\ModuleManager\Exception\MissingDependencyModuleException` is thrown!
>
> - Since 2.12.0
>
> If you are using Composer to autoload, you may not need to use the
> `ModuleAutoloader`. As such, you can enable it by passing the following
> option to the `ListenerOptions` class:
>
> ```php
> 'load_dependencies' => true,
> ```
>
> If your project was begun from the [laminas-mvc-skeleton](https://github.com/laminas/laminas-mvc-skeleton),
> place the above within the `module_listener_options` configuration of your
> `config/application.config.php` file:
>
> ```php
> return [
> /* ... */
> 'module_listener_options' => [
> 'load_dependencies' => true,
> /* ... */
> ],
> /* ... */
> ];
> ```

### ConfigListener

If a module class has a `getConfig()` method, or implements
Expand Down
2 changes: 1 addition & 1 deletion src/Listener/DefaultListenerAggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function attach(EventManagerInterface $events, $priority = 1)
if ($options->getCheckDependencies()) {
$this->listeners[] = $events->attach(
ModuleEvent::EVENT_LOAD_MODULE,
new ModuleDependencyCheckerListener(),
new ModuleDependencyCheckerListener($options),
8000
);
}
Expand Down
28 changes: 27 additions & 1 deletion src/Listener/ListenerOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ class ListenerOptions extends AbstractOptions
/** @var bool */
protected $checkDependencies = true;

/** @var bool */
protected $loadDependencies = false;

/** @var bool */
protected $moduleMapCacheEnabled = false;

Expand Down Expand Up @@ -336,7 +339,7 @@ public function getModuleMapCacheFile()
}

/**
* Set whether to check dependencies during module loading or not
* Get whether to check dependencies during module loading or not
*
* @return bool
*/
Expand All @@ -358,6 +361,29 @@ public function setCheckDependencies($checkDependencies)
return $this;
}

/**
* Set whether to load missing dependencies before throwing an exception
*
* @param bool $loadDependencies should missing dependencies are loaded
* @return ListenerOptions
*/
public function setLoadDependencies($loadDependencies)
{
$this->loadDependencies = (bool) $loadDependencies;

return $this;
}

/**
* Get whether to load missing dependencies before throwing an exception
*
* @return bool
*/
public function getLoadDependencies()
{
return $this->loadDependencies;
}

/**
* Whether or not to use laminas-loader to autoload modules.
*
Expand Down
20 changes: 12 additions & 8 deletions src/Listener/ModuleDependencyCheckerListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use function method_exists;
use function sprintf;

class ModuleDependencyCheckerListener
class ModuleDependencyCheckerListener extends AbstractListener
{
/** @var array of already loaded modules, indexed by module name */
protected $loaded = [];
Expand All @@ -26,13 +26,17 @@ public function __invoke(ModuleEvent $e)

foreach ($dependencies as $dependencyModule) {
if (! isset($this->loaded[$dependencyModule])) {
throw new Exception\MissingDependencyModuleException(
sprintf(
'Module "%s" depends on module "%s", which was not initialized before it',
$e->getModuleName(),
$dependencyModule
)
);
if ($this->getOptions()->getLoadDependencies()) {
$e->getTarget()->loadModule($dependencyModule);
} else {
throw new Exception\MissingDependencyModuleException(
sprintf(
'Module "%s" depends on module "%s", which was not initialized before it',
$e->getModuleName(),
$dependencyModule
)
);
}
}
}
}
Expand Down
54 changes: 54 additions & 0 deletions test/Listener/ModuleDependencyCheckerListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@

namespace LaminasTest\ModuleManager\Listener;

use DependencyModule\Module as DependencyModule;
use Laminas\ModuleManager\Exception;
use Laminas\ModuleManager\Feature;
use Laminas\ModuleManager\Listener\ListenerOptions;
use Laminas\ModuleManager\Listener\ModuleDependencyCheckerListener;
use Laminas\ModuleManager\Listener\ModuleResolverListener;
use Laminas\ModuleManager\ModuleEvent;
use Laminas\ModuleManager\ModuleManager;
use PHPUnit\Framework\TestCase;
use SomeModule\Module as SomeModule;
use stdClass;

/**
Expand Down Expand Up @@ -62,4 +67,53 @@ public function testNotFulfilledDependencyThrowsException()
$this->expectException(Exception\MissingDependencyModuleException::class);
$listener->__invoke($event);
}

/** @covers \Laminas\ModuleManager\Listener\ModuleDependencyCheckerListener::__invoke */
public function testNotFulfilledDependencyThrowsExceptionViaEvent()
{
$listenerOptions = new ListenerOptions();

$moduleManager = new ModuleManager([]);
$moduleManager->getEventManager()->attach(
ModuleEvent::EVENT_LOAD_MODULE_RESOLVE,
new ModuleResolverListener(),
1000
);
$moduleManager->getEventManager()->attach(
ModuleEvent::EVENT_LOAD_MODULE,
new ModuleDependencyCheckerListener($listenerOptions),
2000
);

$this->expectException(Exception\MissingDependencyModuleException::class);

$moduleManager->loadModule(DependencyModule::class);
}

/** @covers \Laminas\ModuleManager\Listener\ModuleDependencyCheckerListener::__invoke */
public function testNotFulfilledDependencyIsLoadedViaEvent()
{
$listenerOptions = new ListenerOptions();
$listenerOptions->setLoadDependencies(true);

$moduleManager = new ModuleManager([]);
$moduleManager->getEventManager()->attach(
ModuleEvent::EVENT_LOAD_MODULE_RESOLVE,
new ModuleResolverListener(),
1000
);
$moduleManager->getEventManager()->attach(
ModuleEvent::EVENT_LOAD_MODULE,
new ModuleDependencyCheckerListener($listenerOptions),
2000
);
$moduleManager->loadModule(DependencyModule::class);

$loadedModules = $moduleManager->getLoadedModules();

self::assertCount(2, $loadedModules);

self::assertArrayHasKey(DependencyModule::class, $loadedModules);
self::assertArrayHasKey(SomeModule::class, $loadedModules);
}
}
14 changes: 7 additions & 7 deletions test/ModuleManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Laminas\ModuleManager\ModuleManager;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use SomeModule\Module;
use SomeModule\Module as SomeModule;
use stdClass;
use SubModule\Sub\Module as SubModule;

Expand Down Expand Up @@ -62,7 +62,7 @@ public function testCanLoadSomeModule()
$this->defaultListeners->attach($this->events);
$moduleManager->loadModules();
$loadedModules = $moduleManager->getLoadedModules();
self::assertInstanceOf('SomeModule\Module', $loadedModules['SomeModule']);
self::assertInstanceOf(SomeModule::class, $loadedModules['SomeModule']);
$config = $configListener->getMergedConfig();
self::assertSame($config->some, 'thing', var_export($config, true));
}
Expand Down Expand Up @@ -181,13 +181,13 @@ public function testCanLoadSomeObjectModule()
require_once __DIR__ . '/TestAsset/SubModule/Sub/Module.php';
$configListener = $this->defaultListeners->getConfigListener();
$moduleManager = new ModuleManager([
'SomeModule' => new Module(),
'SomeModule' => new SomeModule(),
'SubModule' => new SubModule(),
], $this->events);
$this->defaultListeners->attach($this->events);
$moduleManager->loadModules();
$loadedModules = $moduleManager->getLoadedModules();
self::assertInstanceOf('SomeModule\Module', $loadedModules['SomeModule']);
self::assertInstanceOf(SomeModule::class, $loadedModules['SomeModule']);
$config = $configListener->getMergedConfig();
self::assertSame($config->some, 'thing');
}
Expand All @@ -196,11 +196,11 @@ public function testCanLoadMultipleModulesObjectWithString()
{
require_once __DIR__ . '/TestAsset/SomeModule/Module.php';
$configListener = $this->defaultListeners->getConfigListener();
$moduleManager = new ModuleManager(['SomeModule' => new Module(), 'BarModule'], $this->events);
$moduleManager = new ModuleManager(['SomeModule' => new SomeModule(), 'BarModule'], $this->events);
$this->defaultListeners->attach($this->events);
$moduleManager->loadModules();
$loadedModules = $moduleManager->getLoadedModules();
self::assertInstanceOf('SomeModule\Module', $loadedModules['SomeModule']);
self::assertInstanceOf(SomeModule::class, $loadedModules['SomeModule']);
$config = $configListener->getMergedConfig();
self::assertSame($config->some, 'thing');
}
Expand All @@ -209,7 +209,7 @@ public function testCanNotLoadSomeObjectModuleWithoutIdentifier()
{
require_once __DIR__ . '/TestAsset/SomeModule/Module.php';
$this->defaultListeners->getConfigListener();
$moduleManager = new ModuleManager([new Module()], $this->events);
$moduleManager = new ModuleManager([new SomeModule()], $this->events);
$this->defaultListeners->attach($this->events);
$this->expectException(Exception\RuntimeException::class);
$moduleManager->loadModules();
Expand Down
30 changes: 30 additions & 0 deletions test/TestAsset/DependencyModule/Module.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace DependencyModule;

use Laminas\ModuleManager\Feature\ConfigProviderInterface;
use Laminas\ModuleManager\Feature\DependencyIndicatorInterface;
use SomeModule\Module as SomeModule;

class Module implements ConfigProviderInterface, DependencyIndicatorInterface
{
/**
* @return array
*/
public function getConfig()
{
return [];
}

/**
* @return string[]
*/
public function getModuleDependencies()
{
return [
SomeModule::class,
];
}
}