1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BFW\Core; |
4
|
|
|
|
5
|
|
|
use \Exception; |
6
|
|
|
|
7
|
|
|
class Cli |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @const ERR_NO_FILE_SPECIFIED_IN_ARG Exception code if the cli file to |
11
|
|
|
* run is not specified with the "-f" argument. |
12
|
|
|
*/ |
13
|
|
|
const ERR_NO_FILE_SPECIFIED_IN_ARG = 1315001; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @const ERR_CLI_FILE_NOT_FOUND Exception code if the cli file to run is |
17
|
|
|
* not found. |
18
|
|
|
*/ |
19
|
|
|
const ERR_FILE_NOT_FOUND = 1315002; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var string The name of the executed cli file |
23
|
|
|
*/ |
24
|
|
|
protected $executedFile = ''; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Getter to the property executedFile |
28
|
|
|
* |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
|
|
public function getExecutedFile() |
32
|
|
|
{ |
33
|
|
|
return $this->executedFile; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Obtain the file to execute from the cli arg. |
38
|
|
|
* Search the arg "f" to get the value. |
39
|
|
|
* |
40
|
|
|
* @return string The file path |
41
|
|
|
* |
42
|
|
|
* @throws \Exception If no file is declared to be executed |
43
|
|
|
*/ |
44
|
|
|
public function obtainFileFromArg() |
45
|
|
|
{ |
46
|
|
|
$cliArgs = getopt('f:'); |
47
|
|
|
if (!isset($cliArgs['f'])) { |
48
|
|
|
throw new Exception( |
49
|
|
|
'Error: No file specified.', |
50
|
|
|
$this::ERR_NO_FILE_SPECIFIED_IN_ARG |
51
|
|
|
); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return CLI_DIR.$cliArgs['f'].'.php'; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Check the file to execute and run it |
59
|
|
|
* |
60
|
|
|
* @param string $file |
61
|
|
|
* |
62
|
|
|
* @return void |
63
|
|
|
*/ |
64
|
|
|
public function run($file) |
65
|
|
|
{ |
66
|
|
|
$this->executedFile = $file; |
67
|
|
|
|
68
|
|
|
if ($this->checkFile() === true) { |
69
|
|
|
$this->execFile(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Check the file to execute. |
75
|
|
|
* |
76
|
|
|
* @return boolean |
77
|
|
|
* |
78
|
|
|
* @throws Exception |
79
|
|
|
*/ |
80
|
|
|
protected function checkFile() |
81
|
|
|
{ |
82
|
|
|
if (!file_exists($this->executedFile)) { |
83
|
|
|
throw new Exception( |
84
|
|
|
'File to execute not found.', |
85
|
|
|
$this::ERR_FILE_NOT_FOUND |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return true; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* Execute the cli file into a different scope. |
94
|
|
|
* The new scope have access to $this of this class. |
95
|
|
|
* |
96
|
|
|
* @return void |
97
|
|
|
*/ |
98
|
|
|
protected function execFile() |
99
|
|
|
{ |
100
|
|
|
$fctRunCliFile = function() { |
101
|
|
|
require($this->executedFile); |
102
|
|
|
}; |
103
|
|
|
|
104
|
|
|
$fctRunCliFile(); |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|