From 5d7fe43083ed6514758c088d755b6a515291e5f2 Mon Sep 17 00:00:00 2001 From: Lio Novelli Date: Wed, 17 Nov 2021 11:14:00 +0100 Subject: [PATCH 1/2] WV-4745: Add mudule_hander service trait. --- src/Core/Extension/ModuleHandlerTrait.php | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/Core/Extension/ModuleHandlerTrait.php diff --git a/src/Core/Extension/ModuleHandlerTrait.php b/src/Core/Extension/ModuleHandlerTrait.php new file mode 100644 index 0000000..b4007f7 --- /dev/null +++ b/src/Core/Extension/ModuleHandlerTrait.php @@ -0,0 +1,45 @@ +moduleHandler = $moduleHandler; + return $this; + } + + /** + * Gets the module handler. + * + * @return \Drupal\Core\Extension\ModuleHandlerInterface + * The module handler. + */ + public function getModuleHandler() { + if (empty($this->moduleHandler)) { + $this->moduleHandler = \Drupal::service('module_handler'); + } + return $this->moduleHandler; + } + +} From 83835332b8cb5120ef1793a3259b7a56d9f88636 Mon Sep 17 00:00:00 2001 From: Lio Novelli Date: Thu, 18 Nov 2021 10:34:37 +0100 Subject: [PATCH 2/2] WV-4745: Add tests for module handler trait. --- .../Core/Extension/ModuleHandlerTraitTest.php | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 tests/src/Core/Extension/ModuleHandlerTraitTest.php diff --git a/tests/src/Core/Extension/ModuleHandlerTraitTest.php b/tests/src/Core/Extension/ModuleHandlerTraitTest.php new file mode 100644 index 0000000..f166153 --- /dev/null +++ b/tests/src/Core/Extension/ModuleHandlerTraitTest.php @@ -0,0 +1,71 @@ +mockContainerWithFakeService(['calls' => 1]); + $this->assertsame($service, $this->getModuleHandler()); + // Multiple calls should fetch the service from the container only once. + $this->getModuleHandler(); + } + + /** + * @covers ::setModuleHandler + */ + public function testSetter() { + // Verify the set service is returned. + $this->mockContainerWithFakeService(['calls' => 0]); + $service = $this->prophesize() + ->willImplement(ModuleHandlerInterface::class) + ->reveal(); + /** @var \Drupal\Core\Extension\ModuleHandlerInterface $service */ + $this->setModuleHandler($service); + $this->assertsame($service, $this->getModuleHandler()); + } + + /** + * Helper to mock the container with a stub service. + * + * @param int[] $options + * An array with the following keys: + * - calls: The number of calls to get the service the mocked container + * expects. + * + * @return object + * The fake service returned by the container. + */ + protected function mockContainerWithFakeService(array $options) { + $service = new \Stdclass(); + $container = $this->prophesize(Container::class); + $prophecy = $container->get($this->serviceId); + /** @var \Prophecy\Prophecy\MethodProphecy $prophecy */ + $prophecy->shouldBeCalledTimes($options['calls']); + $prophecy->willReturn($service); + \Drupal::setContainer($container->reveal()); + return $service; + } + +}