diff --git a/src/ServiceContainer.php b/src/ServiceContainer.php index 0eab48e..1066ee7 100644 --- a/src/ServiceContainer.php +++ b/src/ServiceContainer.php @@ -174,16 +174,8 @@ public function make(string $id) if (null === $instance) { throw new EmptyResultFromFactoryException($id); } - } catch (NotFoundExceptionInterface|ContainerExceptionInterface $exception) { - throw $exception; - } catch (\ReflectionException $exception) { - throw new ReflectionError($exception); } catch (\Throwable $error) { - if (sprintf("Class '%s' not found", $id) === $error->getMessage()) { - throw new ServiceNotFoundException($id, $error); - } else { - throw new CannotMakeServiceException($id, $error); - } + $this->handleError($id, $error); } return $instance; @@ -269,6 +261,40 @@ public function unset(string $id): bool { return false; } + /** + * Handles an error when making a service + * + * @param string $id ID of entry we're creating + * @param \Throwable $error en error + * + * @return void + */ + private function handleError(string $id, \Throwable $error): void { + if ($error instanceof NotFoundExceptionInterface) { + throw $error; + } + + if ($error instanceof ContainerExceptionInterface) { + throw $error; + } + + if ($error instanceof \ReflectionException) { + throw new ReflectionError($error); + } + + if (\sprintf("Class '%s' not found", $id) === $error->getMessage()) { + throw new ServiceNotFoundException($id, $error); + } + + if (!$this->autowireEnabled) { + if ($error instanceof \ArgumentCountError) { + throw new CannotMakeServiceException($id, $error); + } + } + + throw $error; + } + private static function buildFactory($classname) { try { diff --git a/tests/ServiceContainerTest.php b/tests/ServiceContainerTest.php index 1ed5594..01bbed7 100644 --- a/tests/ServiceContainerTest.php +++ b/tests/ServiceContainerTest.php @@ -25,11 +25,11 @@ function testGettingNonExistingClass(string $id) { $container->get($id); } - function testGettingClassWithConstructorError() { + function testThatExceptionNotRelatedWithServiceMakingAreDisclosed() { $container = new ServiceContainer; - $this->expectException(CannotMakeServiceException::class); - $this->expectExceptionMessage('Cannot make service, id: ClassWithFalseConstructor'); + $this->expectException('Exception'); + $this->expectExceptionMessage('blah blah'); $container->get(ClassWithFalseConstructor::class); }