File tree Expand file tree Collapse file tree 2 files changed +117
-0
lines changed Expand file tree Collapse file tree 2 files changed +117
-0
lines changed Original file line number Diff line number Diff line change 1
1
<?php
2
+ namespace pastuhov \Command ;
2
3
4
+ /**
5
+ * Command
6
+ * @package pastuhov\Command
7
+ */
8
+ final class Command
9
+ {
10
+ private function __construct () {}
11
+
12
+ /**
13
+ * Execute command with params.
14
+ * @param string $commandLine
15
+ * @param array $params
16
+ * @return bool|string
17
+ * @throws \Exception
18
+ */
19
+ public static function exec ($ commandLine , array $ params = array ())
20
+ {
21
+ if (empty ($ commandLine )) {
22
+ throw new \Exception ('Command line is empty ' );
23
+ }
24
+
25
+ $ commandLine = self ::bindParams ($ commandLine , $ params );
26
+
27
+ exec ($ commandLine , $ output , $ code );
28
+
29
+ if (count ($ output ) === 0 ) {
30
+ $ output = $ code ;
31
+ } else {
32
+ $ output = implode (PHP_EOL , $ output );
33
+ }
34
+
35
+ if ($ code !== 0 ) {
36
+ throw new \Exception ($ output );
37
+ }
38
+
39
+ return $ output ;
40
+ }
41
+
42
+ /**
43
+ * Bind params to command.
44
+ * @param string $commandLine
45
+ * @param array $params
46
+ * @return string
47
+ */
48
+ public static function bindParams ($ commandLine , array $ params )
49
+ {
50
+
51
+ if (count ($ params ) > 0 ) {
52
+ $ wrapper = function ($ string ) {
53
+ return '{ ' .$ string .'} ' ;
54
+ };
55
+ $ converter = function ($ var ) {
56
+ if (is_array ($ var )) {
57
+ $ var = implode (' ' , $ var );
58
+ }
59
+ return $ var ;
60
+ };
61
+
62
+ $ commandLine = str_replace (
63
+ array_map (
64
+ $ wrapper ,
65
+ array_keys ($ params )
66
+ ),
67
+ array_map (
68
+ $ converter ,
69
+ array_values ($ params )
70
+ ),
71
+ $ commandLine
72
+ );
73
+ }
74
+
75
+ return $ commandLine ;
76
+ }
77
+ }
Original file line number Diff line number Diff line change 1
1
<?php
2
+ namespace pastuhov \Command \Test ;
2
3
4
+ use pastuhov \Command \Command ;
3
5
6
+ /**
7
+ * Class FileStreamTest
8
+ * @package pastuhov\Command\Test
9
+ */
10
+ class FileStreamTest extends \PHPUnit_Framework_TestCase
11
+ {
12
+ public function testExec ()
13
+ {
14
+ $ output = Command::exec (
15
+ 'echo {phrase} ' ,
16
+ [
17
+ 'phrase ' => [
18
+ 'hello ' ,
19
+ 'world '
20
+ ]
21
+ ]
22
+ );
23
+
24
+ $ this ->assertEquals ('hello world ' , $ output );
25
+ }
26
+
27
+ public function testExecException ()
28
+ {
29
+ $ this ->setExpectedException ('Exception ' );
30
+
31
+ $ output = Command::exec (
32
+ 'echo111 '
33
+ );
34
+
35
+ }
36
+
37
+ public function testExecEmptyCommand ()
38
+ {
39
+ $ this ->setExpectedException ('Exception ' );
40
+
41
+ $ output = Command::exec (
42
+ ''
43
+ );
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments