1: <?php
2: /**
3: * @author Jefferson González
4: * @license MIT
5: * @link http://github.com/peg-org/peg-custom Source code.
6: */
7:
8: namespace Peg\Custom\CommandLine;
9:
10: /**
11: * A sub command processed by the application. Example peg init
12: */
13: class Command
14: {
15:
16: /**
17: * Name of the command.
18: * @var string
19: */
20: public $name;
21:
22: /**
23: * Description of the command displayed on help.
24: * @var string
25: */
26: public $description;
27:
28: /**
29: * Array of Options processed by the command.
30: * @var \Peg\Custom\CommandLine\Option[]
31: */
32: public $options;
33:
34: /**
35: * In case the command supports values. Example: peg init something
36: * where 'init' is the command and 'something' is the value.
37: * @var string
38: */
39: public $value;
40:
41: /**
42: * Flag that indicates if a value is required for the command.
43: * @var boolean
44: */
45: public $value_required;
46:
47: /**
48: * Array of Actions called if this command gets executed.
49: * @var \Peg\Custom\CommandLine\Action[]
50: */
51: public $actions;
52:
53: /**
54: * Initialize the command.
55: * @param string $name Name of the Sub-command
56: * @param \Peg\Custom\CommandLine\Option[] $options List of options
57: * @param \Peg\Custom\CommandLine\Action[] $actions List of actions
58: */
59: public function __construct($name, $options = array(), $actions = array())
60: {
61: $this->name = $name;
62: $this->options = $options;
63: $this->value = "";
64:
65: $this->actions = $actions;
66: }
67:
68: /**
69: * Define a new option accepted by the command.
70: * @param \Peg\Custom\CommandLine\Option $option
71: */
72: public function AddOption(Option $option)
73: {
74: $this->options[] = $option;
75: }
76:
77: /**
78: * Gets an option by its long or short name.
79: * @param type $name
80: * @return null|\Peg\Custom\CommandLine\Option
81: */
82: public function GetOption($name)
83: {
84: foreach($this->options as $option)
85: {
86: if($option->long_name == $name || $option->short_name == $name)
87: {
88: return $option;
89: }
90: }
91:
92: return null;
93: }
94:
95: /**
96: * Execute each action associated to the command.
97: */
98: public function Execute()
99: {
100: foreach($this->actions as $action)
101: {
102: $action->OnCall($this);
103: }
104: }
105:
106: /**
107: * Register actions that get call when command is executed.
108: * @param \Peg\Custom\CommandLine\Action $action
109: */
110: public function RegisterAction(Action $action)
111: {
112: $this->actions[] = $action;
113: }
114:
115: }