Skip to content

Commit

Permalink
refactor!: change registering functionality
Browse files Browse the repository at this point in the history
- `register()` now receives `ResolverInterface` as second parameter
- remove `factory()` method
- remove `hasFactory()` method
  • Loading branch information
lombervid committed Jul 24, 2023
1 parent d635b11 commit b8e491e
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 133 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## [Unreleased]

### Changed

- **Breaking:** `register()` now receives `ResolverInterface` as second parameter

### Removed

- **Breaking:** remove `factory()` method
- **Breaking:** remove `hasFactory()` method

### Fixed

- Thrown exception when an already registered identifier is being used.
Expand Down
48 changes: 12 additions & 36 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Phetit\DependencyInjection\Exception\DuplicateEntryIdentifierException;
use Phetit\DependencyInjection\Exception\EntryNotFoundException;
use Phetit\DependencyInjection\Exception\InvalidEntryIdentifierException;
use Phetit\DependencyInjection\Resolver\ResolverInterface;
use Psr\Container\ContainerInterface;

class Container implements ContainerInterface
Expand All @@ -21,20 +22,13 @@ class Container implements ContainerInterface
/**
* The container's services
*
* @var callable[]
* @var ResolverInterface[]
*/
protected array $services = [];

/**
* The container's factories
*
* @var callable[]
*/
protected array $factories = [];

public function has(string $id): bool
{
return $this->hasParameter($id) || $this->hasService($id) || $this->hasFactory($id);
return $this->hasParameter($id) || $this->hasService($id);
}

public function get(string $id): mixed
Expand All @@ -44,20 +38,17 @@ public function get(string $id): mixed
}

if ($this->hasService($id)) {
$this->parameters[$id] = $this->services[$id]($this);

return $this->parameters[$id];
}

if ($this->hasFactory($id)) {
return $this->factories[$id]($this);
return $this->services[$id]->resolve($this);
}

throw new EntryNotFoundException();
}

/**
* Register parameters that returns the value set
*
* @param string $id Parameter identifier
* @param mixed $value Parameter value
*/
public function parameter(string $id, mixed $value): void
{
Expand All @@ -67,25 +58,18 @@ public function parameter(string $id, mixed $value): void
}

/**
* Register a service that is resolved only the first time `get()` is called
* Register a service to the container
*
* @param string $id Service identifier
* @param ResolverInterface $resolver The service resolver
*/
public function register(string $id, callable $resolver): void
public function register(string $id, ResolverInterface $resolver): void
{
$this->validateIdentifier($id);

$this->services[$id] = $resolver;
}

/**
* Register a service that is resolved in every call to `get()` method
*/
public function factory(string $id, callable $resolver): void
{
$this->validateIdentifier($id);

$this->factories[$id] = $resolver;
}

/**
* Validate entry identifier
*
Expand Down Expand Up @@ -117,12 +101,4 @@ public function hasService(string $id): bool
{
return isset($this->services[$id]);
}

/**
* Returns true is a static service exists under the given identifier.
*/
public function hasFactory(string $id): bool
{
return isset($this->factories[$id]);
}
}
20 changes: 20 additions & 0 deletions src/Resolver/FactoryServiceResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Phetit\DependencyInjection\Resolver;

use Closure;
use Phetit\DependencyInjection\Container;

class FactoryServiceResolver implements ResolverInterface
{
public function __construct(protected Closure $callback)
{
}

public function resolve(Container $container): mixed
{
return ($this->callback)($container);
}
}
12 changes: 12 additions & 0 deletions src/Resolver/ResolverInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Phetit\DependencyInjection\Resolver;

use Phetit\DependencyInjection\Container;

interface ResolverInterface
{
public function resolve(Container $container): mixed;
}
26 changes: 26 additions & 0 deletions src/Resolver/ServiceResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Phetit\DependencyInjection\Resolver;

use Closure;
use Phetit\DependencyInjection\Container;

class ServiceResolver implements ResolverInterface
{
protected mixed $instance = null;

public function __construct(protected Closure $callback)
{
}

public function resolve(Container $container): mixed
{
if (is_null($this->instance)) {
$this->instance = ($this->callback)($container);
}

return $this->instance;
}
}
123 changes: 26 additions & 97 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
namespace Phetit\DependencyInjection\Tests;

use Closure;
use InvalidArgumentException;
use Phetit\DependencyInjection\Container;
use Phetit\DependencyInjection\Exception\DuplicateEntryIdentifierException;
use Phetit\DependencyInjection\Exception\EntryNotFoundException;
use Phetit\DependencyInjection\Tests\Fixtures\Service;
use Phetit\DependencyInjection\Exception\InvalidEntryIdentifierException;
use Phetit\DependencyInjection\Resolver\ResolverInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

class ContainerTest extends TestCase
Expand All @@ -27,24 +28,26 @@ public function testHasReturnsTrueOnRegisteredEntry(): void
{
$container = new Container();

$container->parameter('foo', fn() => 'bar');
$container->register('foo_service', fn() => 'bar_service');
$container->factory('foo_factory', fn() => 'bar_factory');

$container->parameter('foo', 'bar');
self::assertTrue($container->has('foo'));
self::assertTrue($container->has('foo_service'));
self::assertTrue($container->has('foo_factory'));

$container->register('service', $this->createMock(ResolverInterface::class));
self::assertTrue($container->has('service'));
}

public function testResolvesClosureEntry(): void
public function testShouldCallResolveMethodInResolverPassingSelfReference(): void
{
$container = new Container();
$container->parameter('bar', 45);

$container->factory('foo', fn() => 'bar');

$resolve = $container->get('foo');
/** @var ResolverInterface&MockObject */
$service = $this->createMock(ResolverInterface::class);
$service->expects(self::once())
->method('resolve')
->with(self::isInstanceOf(Container::class));

self::assertEquals('bar', $resolve);
$container->register('foo', $service);
$container->get('foo');
}

public function testThrowsExceptionWhenTryingToResolveMissingEntry(): void
Expand All @@ -57,37 +60,7 @@ public function testThrowsExceptionWhenTryingToResolveMissingEntry(): void
$container->get('foo');
}

public function testServiceShouldBeTheSame(): void
{
$container = new Container();

$container->register('service', fn () => new Service());

$serviceOne = $container->get('service');
self::assertInstanceOf(Service::class, $serviceOne);

$serviceTwo = $container->get('service');
self::assertInstanceOf(Service::class, $serviceTwo);

self::assertSame($serviceOne, $serviceTwo);
}

public function testFactoriesShouldBeDifferent(): void
{
$container = new Container();

$container->factory('service', fn() => new Service());

$serviceOne = $container->get('service');
self::assertInstanceOf(Service::class, $serviceOne);

$serviceTwo = $container->get('service');
self::assertInstanceOf(Service::class, $serviceTwo);

self::assertNotSame($serviceOne, $serviceTwo);
}

public function testSettingParameters(): void
public function testShouldSetParameters(): void
{
$container = new Container();

Expand Down Expand Up @@ -118,83 +91,39 @@ public function testResolvesNullValueParameters(): void
self::assertNull($container->get('foo'));
}

public function testContainerShouldBeInjectedToServiceResolver(): void
public function testExceptionShouldBeThrownRegisteringParameterWithEmptyId(): void
{
$container = new Container();

$container->parameter('value2', 78);
$container->register('service2', fn(Container $c) => new Service($c->get('value2')));

$service2 = $container->get('service2');

self::assertInstanceOf(Service::class, $service2);
self::assertSame(78, $service2->value);
}

public function testContainerShouldBeInjectedToFactoryResolver(): void
{
$container = new Container();

$container->parameter('value', 67);
$container->factory('service', fn (Container $c) => new Service($c->get('value')));

$service = $container->get('service');

self::assertInstanceOf(Service::class, $service);
self::assertSame(67, $service->value);
}

public function testExceptionShouldBeThrownSettingParameterWithEmptyId(): void
{
$container = new Container();

self::expectException(InvalidArgumentException::class);
self::expectException(InvalidEntryIdentifierException::class);
$container->parameter('', 'empty');
}

public function testExceptionShouldBeThrownSettingServiceWithEmptyId(): void
public function testExceptionShouldBeThrownRegisteringServiceWithEmptyId(): void
{
$container = new Container();

self::expectException(InvalidArgumentException::class);
$container->register('', fn () => new Service());
}

public function testExceptionShouldBeThrownSettingFactoryWithEmptyId(): void
{
$container = new Container();

self::expectException(InvalidArgumentException::class);
$container->factory('', fn() => new Service());
}

public function testExceptionShouldBeThrownWithDuplicateServiceId(): void
{
$container = new Container();

$container->parameter('foo', 'bar');

self::expectException(DuplicateEntryIdentifierException::class);
$container->register('foo', fn() => new Service());
self::expectException(InvalidEntryIdentifierException::class);
$container->register('', $this->createMock(ResolverInterface::class));
}

public function testExceptionShouldBeThrownWithDuplicateParameterId(): void
{
$container = new Container();

$container->factory('foo', fn() => new Service());
$container->register('foo', $this->createMock(ResolverInterface::class));

self::expectException(DuplicateEntryIdentifierException::class);
$container->parameter('foo', 'bar');
}

public function testExceptionShouldBeThrownWithDuplicateFactoryId(): void
public function testExceptionShouldBeThrownWithDuplicateServiceId(): void
{
$container = new Container();

$container->register('foo', fn() => new Service());
$container->parameter('foo', 'bar');

self::expectException(DuplicateEntryIdentifierException::class);
$container->factory('foo', fn () => new Service());
$container->register('foo', $this->createMock(ResolverInterface::class));
}
}

0 comments on commit b8e491e

Please sign in to comment.