4 * This file is part of the Prophecy.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
6 * Marcello Duarte <marcello.duarte@gmail.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Prophecy\Promise;
14 use Doctrine\Instantiator\Instantiator;
15 use Prophecy\Prophecy\ObjectProphecy;
16 use Prophecy\Prophecy\MethodProphecy;
17 use Prophecy\Exception\InvalidArgumentException;
23 * @author Konstantin Kudryashov <ever.zet@gmail.com>
25 class ThrowPromise implements PromiseInterface
30 * @var \Doctrine\Instantiator\Instantiator
32 private $instantiator;
35 * Initializes promise.
37 * @param string|\Exception|\Throwable $exception Exception class name or instance
39 * @throws \Prophecy\Exception\InvalidArgumentException
41 public function __construct($exception)
43 if (is_string($exception)) {
44 if (!class_exists($exception) || !$this->isAValidThrowable($exception)) {
45 throw new InvalidArgumentException(sprintf(
46 'Exception / Throwable class or instance expected as argument to ThrowPromise, but got %s.',
50 } elseif (!$exception instanceof \Exception && !$exception instanceof \Throwable) {
51 throw new InvalidArgumentException(sprintf(
52 'Exception / Throwable class or instance expected as argument to ThrowPromise, but got %s.',
53 is_object($exception) ? get_class($exception) : gettype($exception)
57 $this->exception = $exception;
61 * Throws predefined exception.
64 * @param ObjectProphecy $object
65 * @param MethodProphecy $method
69 public function execute(array $args, ObjectProphecy $object, MethodProphecy $method)
71 if (is_string($this->exception)) {
72 $classname = $this->exception;
73 $reflection = new ReflectionClass($classname);
74 $constructor = $reflection->getConstructor();
76 if ($constructor->isPublic() && 0 == $constructor->getNumberOfRequiredParameters()) {
77 throw $reflection->newInstance();
80 if (!$this->instantiator) {
81 $this->instantiator = new Instantiator();
84 throw $this->instantiator->instantiate($classname);
87 throw $this->exception;
91 * @param string $exception
95 private function isAValidThrowable($exception)
97 return is_a($exception, 'Exception', true) || is_subclass_of($exception, 'Throwable', true);