From 6e23e4cad456b6b4a3c3a8a1937fbdfeaccb14d1 Mon Sep 17 00:00:00 2001 From: Timo Schinkel Date: Tue, 19 Mar 2019 20:40:40 +0100 Subject: [PATCH] Allow `MethodProphecy::willThrow()` to accept Throwable as string - add additional check for existence of interface in contructor - change `is_subclass_of` to `is_a` to allow for `Throwable` and subclasses of `Throwable` - add specs for cases of `Throwable` and extensions of `Throwable` To maintain support for php 5.3 the new specs are only applicable for PHP 7.0 and higher and `ThrowPromise::isValidThrowable()` checks for both `Exception` and `Throwable`. fixes #428 --- spec/Prophecy/Promise/ThrowPromiseSpec.php | 22 ++++++++++++++++++++++ src/Prophecy/Promise/ThrowPromise.php | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/spec/Prophecy/Promise/ThrowPromiseSpec.php b/spec/Prophecy/Promise/ThrowPromiseSpec.php index b5a10bc1e..2c9859d6f 100644 --- a/spec/Prophecy/Promise/ThrowPromiseSpec.php +++ b/spec/Prophecy/Promise/ThrowPromiseSpec.php @@ -84,6 +84,28 @@ function it_throws_an_exception_by_class_name() $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); } + + function it_throws_an_extension_of_throwable_by_class_name() + { + if (!interface_exists('\Throwable')) { + throw new SkippingException('The interface Throwable, introduced in PHP 7, does not exist'); + } + + $this->beConstructedWith('\Fixtures\Prophecy\ThrowableInterface'); + + $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); + } + + function it_throws_a_throwable_by_class_name() + { + if (!interface_exists('\Throwable')) { + throw new SkippingException('The interface Throwable, introduced in PHP 7, does not exist'); + } + + $this->beConstructedWith('\Throwable'); + + $this->shouldNotThrow('Prophecy\Exception\InvalidArgumentException')->duringInstantiation(); + } } class RequiredArgumentException extends \Exception diff --git a/src/Prophecy/Promise/ThrowPromise.php b/src/Prophecy/Promise/ThrowPromise.php index 7250fa3c6..26ec19edf 100644 --- a/src/Prophecy/Promise/ThrowPromise.php +++ b/src/Prophecy/Promise/ThrowPromise.php @@ -41,7 +41,7 @@ class ThrowPromise implements PromiseInterface public function __construct($exception) { if (is_string($exception)) { - if (!class_exists($exception) || !$this->isAValidThrowable($exception)) { + if ((!class_exists($exception) && !interface_exists($exception)) || !$this->isAValidThrowable($exception)) { throw new InvalidArgumentException(sprintf( 'Exception / Throwable class or instance expected as argument to ThrowPromise, but got %s.', $exception @@ -94,6 +94,7 @@ public function execute(array $args, ObjectProphecy $object, MethodProphecy $met */ private function isAValidThrowable($exception) { - return is_a($exception, 'Exception', true) || is_subclass_of($exception, 'Throwable', true); + return is_a($exception, 'Exception', true) + || is_a($exception, 'Throwable', true); } }