Add Container class
This class is used as DI Container for easier injecting classes in integration tests. It can be also reused during a standalone usage. [MAILPOET-6216]
This commit is contained in:
28
packages/php/email-editor/src/Container.php
Normal file
28
packages/php/email-editor/src/Container.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php declare(strict_types = 1);
|
||||||
|
|
||||||
|
namespace MailPoet\EmailEditor;
|
||||||
|
|
||||||
|
class Container {
|
||||||
|
protected array $services = [];
|
||||||
|
protected array $instances = [];
|
||||||
|
|
||||||
|
public function set(string $name, callable $callable): void {
|
||||||
|
$this->services[$name] = $callable;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get(string $name) {
|
||||||
|
// Check if the service is already instantiated
|
||||||
|
if (isset($this->instances[$name])) {
|
||||||
|
return $this->instances[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the service is registered
|
||||||
|
if (!isset($this->services[$name])) {
|
||||||
|
throw new \Exception("Service not found: $name");
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->instances[$name] = $this->services[$name]($this);
|
||||||
|
|
||||||
|
return $this->instances[$name];
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,44 @@
|
|||||||
|
<?php declare(strict_types = 1);
|
||||||
|
|
||||||
|
use MailPoet\EmailEditor\Container;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
class ContainerTest extends TestCase {
|
||||||
|
public function testSetAndGetService(): void {
|
||||||
|
$container = new Container();
|
||||||
|
|
||||||
|
$container->set('simple_service', function () {
|
||||||
|
return new stdClass();
|
||||||
|
});
|
||||||
|
|
||||||
|
$service = $container->get('simple_service');
|
||||||
|
|
||||||
|
$this->assertInstanceOf(stdClass::class, $service);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGetReturnsSameInstance(): void {
|
||||||
|
$container = new Container();
|
||||||
|
|
||||||
|
$container->set('singleton_service', function () {
|
||||||
|
return new stdClass();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Retrieve the service twice
|
||||||
|
$service1 = $container->get('singleton_service');
|
||||||
|
$service2 = $container->get('singleton_service');
|
||||||
|
|
||||||
|
// Check that both instances are the same
|
||||||
|
$this->assertSame($service1, $service2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testExceptionForNonExistingService(): void {
|
||||||
|
// Create the container instance
|
||||||
|
$container = new Container();
|
||||||
|
|
||||||
|
// Attempt to get a non-existing service should throw an exception
|
||||||
|
$this->expectException(Exception::class);
|
||||||
|
$this->expectExceptionMessage('Service not found: non_existing_service');
|
||||||
|
|
||||||
|
$container->get('non_existing_service');
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user