Skip to content

Commit

Permalink
Allow MethodProphecy::willThrow() to accept Throwable as string
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
timoschinkel committed Mar 19, 2019
1 parent 7e27218 commit 6e23e4c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
22 changes: 22 additions & 0 deletions spec/Prophecy/Promise/ThrowPromiseSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/Prophecy/Promise/ThrowPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 6e23e4c

Please sign in to comment.