CliTaskHandler::isAppropriate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 1
dl 0
loc 23
ccs 13
cts 13
cp 1
crap 5
rs 9.2408
c 0
b 0
f 0
1
<?php
2
3
namespace Vectorface\SnappyRouter\Handler;
4
5
use \Exception;
6
use Vectorface\SnappyRouter\Exception\ResourceNotFoundException;
7
use Vectorface\SnappyRouter\Task\TaskInterface;
8
9
/**
10
 * A CLI handler for task/action scripts.
11
 * @copyright Copyright (c) 2014, VectorFace, Inc.
12
 * @author Dan Bruce <[email protected]>
13
 */
14
class CliTaskHandler extends AbstractCliHandler
15
{
16
    /**
17
     * Determines whether the current handler is appropriate for the given
18
     * path components.
19
     * @param array $components The path components as an array.
20
     * @return boolean Returns true if the handler is appropriate and false
21
     *         otherwise.
22
     */
23 5
    public function isAppropriate($components)
24
    {
25 5
        $components = array_values(array_filter(array_map('trim', $components), 'strlen'));
26 5
        $this->options = array();
27 5
        if (count($components) < 5) {
28 1
            return false;
29
        }
30
31 5
        if ($components[1] !== '--task' || $components[3] !== '--action') {
32 1
            return false;
33
        }
34 5
        $this->options['task'] = $components[2];
35 5
        $this->options['action'] = $components[4];
36
37
        try {
38
            // ensure we have this task registered
39 5
            $this->getServiceProvider()->get($this->options['task']);
40 3
        } catch (Exception $e) {
41 3
            return false;
42
        }
43
44 4
        return true;
45
    }
46
47
    /**
48
     * Performs the actual routing.
49
     * @return mixed Returns the result of the route.
50
     */
51 3
    public function performRoute()
52
    {
53 3
        $task = $this->getServiceProvider()->getServiceInstance($this->options['task']);
54 3
        if (false === method_exists($task, $this->options['action'])) {
55 1
            throw new ResourceNotFoundException(
56 1
                sprintf(
57 1
                    '%s task does not have action %s.',
58 1
                    $this->options['task'],
59 1
                    $this->options['action']
60
                )
61
            );
62
        }
63
64
        // call the task's init function
65 2
        if ($task instanceof TaskInterface) {
66 2
            $task->init($this->options);
67
        }
68
69 2
        $taskParams = array_splice($_SERVER['argv'], 5);
70 2
        $action = $this->options['action'];
71 2
        return $task->$action($taskParams);
72
    }
73
}
74