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

Add Container->resolve(Closure) #13

Merged
merged 6 commits into from
May 19, 2023
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased

- Accept `Closure|string` in `getParametersToResolve()`
- Added `resolve(callable)` to `ContainerInterface`

## 0.4.0
### 2023-04-27
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ $bindings = [
$container = new Container($bindings);

$instance = $container->get(YourClass::class);

//////////////////////////////////////////////
# Extra: you can resolve closures on-the-fly using the container bindings
$resolved = $container->resolve(function (ComplexInterface $i) {
// your custom logic
return $i->...;
});
```

### Example
Expand Down
19 changes: 18 additions & 1 deletion src/Container/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Closure;
use Gacela\Container\Exception\ContainerException;
use ReflectionFunction;
use SplObjectStorage;

use function count;
Expand All @@ -17,7 +18,7 @@ class Container implements ContainerInterface
{
private ?DependencyResolver $dependencyResolver = null;

/** @var array<class-string,list<mixed>> */
/** @var array<class-string|string, list<mixed>> */
private array $cachedDependencies = [];

/** @var array<string,mixed> */
Expand Down Expand Up @@ -84,6 +85,22 @@ public function get(string $id): mixed
return $this->createInstance($id);
}

public function resolve(callable $callable): mixed
{
$callable = Closure::fromCallable($callable);
$reflectionFn = new ReflectionFunction($callable);
$callableKey = md5(serialize($reflectionFn->__toString()));

if (!isset($this->cachedDependencies[$callableKey])) {
$this->cachedDependencies[$callableKey] = $this
->getDependencyResolver()
->resolveDependencies($callable);
}

/** @psalm-suppress MixedMethodCall */
return $callable(...$this->cachedDependencies[$callableKey]);
}

public function factory(Closure $instance): Closure
{
$this->factoryInstances->attach($instance);
Expand Down
5 changes: 5 additions & 0 deletions src/Container/ContainerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ interface ContainerInterface extends PsrContainerInterface
*/
public function get(string $id): mixed;

/**
* Resolve the callable loading automatically all arguments based on current bindings.
*/
public function resolve(callable $callable): mixed;

/**
* Check if an instance exists.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use GacelaTest\Fake\PersonInterface;
use PHPUnit\Framework\TestCase;

final class ContainerTest extends TestCase
final class ClassContainerTest extends TestCase
{
public function test_static_create_without_dependencies(): void
{
Expand Down
85 changes: 85 additions & 0 deletions tests/Unit/ClosureContainerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

declare(strict_types=1);

namespace GacelaTest\Unit;

use Gacela\Container\Container;
use GacelaTest\Fake\ClassWithInterfaceDependencies;
use GacelaTest\Fake\ClassWithoutDependencies;
use GacelaTest\Fake\ClassWithRelationship;
use GacelaTest\Fake\Person;
use GacelaTest\Fake\PersonInterface;
use PHPUnit\Framework\TestCase;

final class ClosureContainerTest extends TestCase
{
public function test_static_create_without_dependencies(): void
{
$container = new Container();

$actual = $container->resolve(static fn () => '');

self::assertSame('', $actual);
}

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

$actual = $container->resolve(
static fn (ClassWithoutDependencies $object) => serialize($object),
);

self::assertEquals(
new ClassWithoutDependencies(),
unserialize($actual),
);
}

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

$actual = $container->resolve(
static fn (ClassWithRelationship $object) => serialize($object),
);

self::assertEquals(
new ClassWithRelationship(new Person(), new Person()),
unserialize($actual),
);
}

public function test_use_mapped_interface_dependency(): void
{
$container = new Container([
PersonInterface::class => Person::class,
]);

$actual = $container->resolve(
static fn (ClassWithInterfaceDependencies $object) => serialize($object),
);

self::assertEquals(
new ClassWithInterfaceDependencies(new Person()),
unserialize($actual),
);
}

public function test_resolve_object_from_callable(): void
{
$person = new Person();
$person->name = 'person-name';

$container = new Container([
PersonInterface::class => static fn () => $person,
]);

$actual = $container->resolve(
static fn (PersonInterface $object) => serialize($object),
);

self::assertEquals($person, unserialize($actual));
}
}