1<?php 2 3/* 4 * This file is part of the Prophecy. 5 * (c) Konstantin Kudryashov <ever.zet@gmail.com> 6 * Marcello Duarte <marcello.duarte@gmail.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Prophecy\Promise; 13 14use Prophecy\Prophecy\ObjectProphecy; 15use Prophecy\Prophecy\MethodProphecy; 16use Prophecy\Exception\InvalidArgumentException; 17use Closure; 18 19/** 20 * Callback promise. 21 * 22 * @author Konstantin Kudryashov <ever.zet@gmail.com> 23 */ 24class CallbackPromise implements PromiseInterface 25{ 26 private $callback; 27 28 /** 29 * Initializes callback promise. 30 * 31 * @param callable $callback Custom callback 32 * 33 * @throws \Prophecy\Exception\InvalidArgumentException 34 */ 35 public function __construct($callback) 36 { 37 if (!is_callable($callback)) { 38 throw new InvalidArgumentException(sprintf( 39 'Callable expected as an argument to CallbackPromise, but got %s.', 40 gettype($callback) 41 )); 42 } 43 44 $this->callback = $callback; 45 } 46 47 /** 48 * Evaluates promise callback. 49 * 50 * @param array $args 51 * @param ObjectProphecy $object 52 * @param MethodProphecy $method 53 * 54 * @return mixed 55 */ 56 public function execute(array $args, ObjectProphecy $object, MethodProphecy $method) 57 { 58 $callback = $this->callback; 59 60 if ($callback instanceof Closure && method_exists('Closure', 'bind')) { 61 $callback = Closure::bind($callback, $object); 62 } 63 64 return call_user_func($callback, $args, $object, $method); 65 } 66} 67