Skip to content

Commit

Permalink
Merge pull request #597 from Deuchnord/feat/check-class-exists-before…
Browse files Browse the repository at this point in the history
…-prophesizing

feat: add control over class/interface existence before trying to prophesize it
  • Loading branch information
stof committed Jun 21, 2023
2 parents 8168610 + 2dfa9d7 commit e0ae099
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
13 changes: 13 additions & 0 deletions spec/Prophecy/ProphetSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,17 @@ function it_exposes_doubler_through_getter($doubler)
{
$this->getDoubler()->shouldReturn($doubler);
}

function it_throws_ClassNotFound_if_class_to_prophesize_does_not_exist()
{
$this->shouldThrow('Prophecy\Exception\Doubler\ClassNotFoundException')
->duringProphesize('This\ClassOrInterface\Does\Not\Exist');

}

function it_does_not_throw_when_creating_void_mock()
{
$this->shouldNotThrow()
->duringProphesize();
}
}
18 changes: 13 additions & 5 deletions src/Prophecy/Prophet.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Prophecy\Doubler\Doubler;
use Prophecy\Doubler\LazyDouble;
use Prophecy\Doubler\ClassPatch;
use Prophecy\Exception\Doubler\ClassNotFoundException;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophecy\RevealerInterface;
use Prophecy\Prophecy\Revealer;
Expand Down Expand Up @@ -83,12 +84,19 @@ public function prophesize($classOrInterface = null)
$this->revealer
);

if ($classOrInterface && class_exists($classOrInterface)) {
return $prophecy->willExtend($classOrInterface);
}
if ($classOrInterface) {
if (class_exists($classOrInterface)) {
return $prophecy->willExtend($classOrInterface);
}

if (interface_exists($classOrInterface)) {
return $prophecy->willImplement($classOrInterface);
}

if ($classOrInterface && interface_exists($classOrInterface)) {
return $prophecy->willImplement($classOrInterface);
throw new ClassNotFoundException(sprintf(
'Cannot prophesize class %s, because it cannot be found.',
$classOrInterface
), $classOrInterface);
}

return $prophecy;
Expand Down

0 comments on commit e0ae099

Please sign in to comment.