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
|
5 |
|
} 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
|
1 |
|
public function performRoute() |
|
|
|
|
52
|
|
|
{ |
53
|
1 |
|
$task = $this->getServiceProvider()->getServiceInstance($this->options['task']); |
54
|
1 |
|
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
|
1 |
|
) |
61
|
1 |
|
); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// call the task's init function |
65
|
|
|
if ($task instanceof TaskInterface) { |
66
|
|
|
$task->init($this->options); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$taskParams = array_splice($_SERVER['argv'], 5); |
70
|
|
|
$action = $this->options['action']; |
71
|
|
|
return $task->$action($taskParams); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: