From 48900cd4c784997ae0ced630893dc18658becbfe Mon Sep 17 00:00:00 2001 From: StavoveiC <94967064+StavoveiC@users.noreply.github.com> Date: Thu, 6 Oct 2022 15:33:33 +0300 Subject: [PATCH] feat: LDP-1689: Add database connection trait. (#23) * feat: LDP-1689: Add database connection trait. * LDP-1689: Fix phpcs errors. * test: LDP-1689: Add tests for database connection trait. * LDP-1689: Improve test for watchdog errors. --- src/Core/Database/DatabaseConnectionTrait.php | 45 ++++++++++++ .../Database/DatabaseConnectionTraitTest.php | 73 +++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 src/Core/Database/DatabaseConnectionTrait.php create mode 100644 tests/src/Core/Database/DatabaseConnectionTraitTest.php diff --git a/src/Core/Database/DatabaseConnectionTrait.php b/src/Core/Database/DatabaseConnectionTrait.php new file mode 100644 index 0000000..df29241 --- /dev/null +++ b/src/Core/Database/DatabaseConnectionTrait.php @@ -0,0 +1,45 @@ +connection = $connection; + return $this; + } + + /** + * Gets database connection service. + * + * @return \Drupal\Core\Database\Connection + * The database connection service. + */ + public function getDatabaseConnection() { + if (empty($this->connection)) { + $this->connection = \Drupal::service('database'); + } + return $this->connection; + } + +} diff --git a/tests/src/Core/Database/DatabaseConnectionTraitTest.php b/tests/src/Core/Database/DatabaseConnectionTraitTest.php new file mode 100644 index 0000000..19236b9 --- /dev/null +++ b/tests/src/Core/Database/DatabaseConnectionTraitTest.php @@ -0,0 +1,73 @@ +mockContainerWithFakeService(['calls' => 1]); + $this->assertsame($service, $this->getDatabaseConnection()); + // Multiple calls should fetch the service from the container only once. + $this->getDatabaseConnection(); + } + + /** + * @covers ::setDatabaseConnection + */ + public function testSetter() { + // Verify the set service is returned. + $this->mockContainerWithFakeService(['calls' => 0]); + $service = $this->prophesize() + ->willExtend(Connection::class) + ->reveal(); + $this->setDatabaseConnection($service); + $this->assertsame($service, $this->getDatabaseConnection()); + } + + /** + * 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; + } + +}