1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Prophecy. |
5
|
|
|
* (c) Konstantin Kudryashov <[email protected]> |
6
|
|
|
* Marcello Duarte <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Prophecy\Promise; |
13
|
|
|
|
14
|
|
|
use Prophecy\Prophecy\ObjectProphecy; |
15
|
|
|
use Prophecy\Prophecy\MethodProphecy; |
16
|
|
|
use Prophecy\Exception\InvalidArgumentException; |
17
|
|
|
use Closure; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Callback promise. |
21
|
|
|
* |
22
|
|
|
* @author Konstantin Kudryashov <[email protected]> |
23
|
|
|
*/ |
24
|
|
View Code Duplication |
class 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
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.