Completed
Pull Request — master (#580)
by Greg
03:30
created

CallableTask::getState()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
namespace Robo\Collection;
3
4
use Robo\Result;
5
use Robo\Contract\TaskInterface;
6
use Robo\State\StateAwareInterface;
7
use Robo\ResultData;
8
9
/**
10
 * Creates a task wrapper that converts any Callable into an
11
 * object that can be used directly with a task collection.
12
 *
13
 * It is not necessary to use this class directly; Collection will
14
 * automatically wrap Callables when they are added.
15
 */
16
class CallableTask implements TaskInterface
17
{
18
    /**
19
     * @var callable
20
     */
21
    protected $fn;
22
23
    /**
24
     * @var \Robo\Contract\TaskInterface
25
     */
26
    protected $reference;
27
28
    public function __construct(callable $fn, TaskInterface $reference)
29
    {
30
        $this->fn = $fn;
31
        $this->reference = $reference;
32
    }
33
34
    /**
35
     * @return \Robo\Result
36
     */
37
    public function run()
38
    {
39
        $result = call_user_func($this->fn, $this->getState());
40
        // If the function returns no result, then count it
41
        // as a success.
42
        if (!isset($result)) {
43
            $result = Result::success($this->reference);
44
        }
45
        // If the function returns a result, it must either return
46
        // a \Robo\Result or an exit code.  In the later case, we
47
        // convert it to a \Robo\Result.
48
        if (!$result instanceof Result) {
49
            $result = new Result($this->reference, $result);
50
        }
51
52
        return $result;
53
    }
54
55
    public function getState()
56
    {
57
        if ($this->reference instanceof StateAwareInterface) {
58
            return $this->reference->getState();
59
        }
60
        return new ResultData();
61
    }
62
}
63