-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Automatic resolution doc+example+test
- Loading branch information
Showing
2 changed files
with
138 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
<?php | ||
declare(strict_types=1); | ||
|
||
namespace Dakujem\Tests; | ||
|
||
use Closure; | ||
use Dakujem\WireGenie; | ||
use Dakujem\WireLimiter; | ||
use Error; | ||
use PHPUnit\Framework\TestCase; | ||
use ReflectionException; | ||
use ReflectionFunction; | ||
use ReflectionParameter; | ||
use RuntimeException; | ||
|
||
require_once 'ContainerProvider.php'; | ||
|
||
final class ArgumentReflector | ||
{ | ||
public static function types(Closure $closure): array | ||
{ | ||
$rf = new ReflectionFunction($closure); | ||
return array_map(function (ReflectionParameter $rp): string { | ||
$type = ($rp->getClass())->name ?? null; | ||
if ($type === null) { | ||
throw new RuntimeException(sprintf('Unable to reflect type of parameter "%s".', $rp->getName())); | ||
} | ||
return $type; | ||
}, $rf->getParameters()); | ||
} | ||
} | ||
|
||
/** | ||
* AutomaticResolutionTest | ||
*/ | ||
final class AutomaticResolutionTest extends TestCase | ||
{ | ||
private function wireAndExecute(Closure $closure) | ||
{ | ||
$genie = new WireGenie(ContainerProvider::createContainer()); | ||
return $genie->provide(...ArgumentReflector::types($closure))->invoke($closure); | ||
} | ||
|
||
public function testCorrectResolution(): void | ||
{ | ||
$run = false; | ||
$this->wireAndExecute(function (?WireGenie $wg = null, ?Error $e = null) use (&$run) { | ||
$run = true; | ||
$this->assertSame(WireGenie::class, get_class($wg)); | ||
$this->assertSame(Error::class, get_class($e)); | ||
}); | ||
$this->assertTrue($run); | ||
} | ||
|
||
public function testFailedResolution(): void | ||
{ | ||
$run = false; | ||
$this->wireAndExecute(function (?WireLimiter $foo = null) use (&$run) { | ||
$run = true; | ||
$this->assertSame(null, $foo); | ||
}); | ||
$this->assertTrue($run); | ||
} | ||
|
||
public function testFailedReflection(): void | ||
{ | ||
$this->expectException(RuntimeException::class); | ||
$this->wireAndExecute(function (int $foo = null) { | ||
}); | ||
} | ||
} |