Skip to content

Commit daefb4a

Browse files
innocenziregnerisch
authored andcommitted
feat(discovery): support containers with autowiring (tempestphp#2084)
1 parent 8e52983 commit daefb4a

3 files changed

Lines changed: 35 additions & 5 deletions

File tree

packages/discovery/src/BootDiscovery.php

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44

55
namespace Tempest\Discovery;
66

7+
use ArgumentCountError;
78
use AssertionError;
89
use Closure;
910
use Pest\Exceptions\InvalidPestCommand;
1011
use Psr\Container\ContainerInterface;
11-
use Tempest\Container\GenericContainer;
12+
use Psr\Container\NotFoundExceptionInterface;
13+
use Tempest\Discovery\Exceptions\DiscoveryClassCouldNotBeResolved;
1214
use Tempest\Reflection\ClassReflector;
1315
use Tempest\Support\Filesystem;
1416
use Throwable;
@@ -260,18 +262,28 @@ private function discoverPath(string $input, DiscoveryLocation $location, array
260262
/**
261263
* Create a discovery instance from a class name.
262264
* Optionally set the cached discovery items whenever caching is enabled.
265+
*
263266
* @template T of Discovery
264267
* @param class-string<T> $discoveryClass
265268
* @return T
266269
*/
267270
private function resolveDiscovery(string $discoveryClass): Discovery
268271
{
269-
if ($this->container instanceof GenericContainer || $this->container->has($discoveryClass)) {
272+
$discovery = null;
273+
274+
try {
270275
/** @var Discovery $discovery */
271276
$discovery = $this->container->get($discoveryClass);
272-
} else {
273-
/** @var Discovery $discovery */
274-
$discovery = new $discoveryClass();
277+
} catch (NotFoundExceptionInterface) {
278+
// @mago-expect lint:no-empty-catch-clause
279+
}
280+
281+
if ($discovery === null) {
282+
try {
283+
$discovery = new $discoveryClass();
284+
} catch (ArgumentCountError) { // @phpstan-ignore catch.neverThrown
285+
throw DiscoveryClassCouldNotBeResolved::forDiscoveryClass($discoveryClass);
286+
}
275287
}
276288

277289
$discovery->setItems(new DiscoveryItems());
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace Tempest\Discovery\Exceptions;
4+
5+
use Exception;
6+
7+
final class DiscoveryClassCouldNotBeResolved extends Exception implements DiscoveryException
8+
{
9+
public static function forDiscoveryClass(string $discoveryClass): self
10+
{
11+
return new self("Failed to resolve discovery class [{$discoveryClass}]: it is not bound in the container and cannot be instantiated without constructor arguments.");
12+
}
13+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
3+
namespace Tempest\Discovery\Exceptions;
4+
5+
interface DiscoveryException {}

0 commit comments

Comments
 (0)