1: <?php
2: namespace Contrib\Component\System;
3:
4: /**
5: * System command.
6: *
7: * @author Kitamura Satoshi <with.no.parachute@gmail.com>
8: */
9: abstract class SystemCommand
10: {
11: /**
12: * Command name or path.
13: *
14: * @var string
15: */
16: protected $commandPath;
17:
18: // API
19:
20: /**
21: * Execute command.
22: *
23: * @return array
24: */
25: public function execute()
26: {
27: $command = $this->createCommand();
28:
29: return $this->executeCommand($command);
30: }
31:
32: // internal method
33:
34: /**
35: * Execute command.
36: *
37: * @param string $command
38: * @return array
39: * @throws \RuntimeException
40: */
41: protected function executeCommand($command)
42: {
43: exec($command, $result, $returnValue);
44:
45: if ($returnValue === 0) {
46: return $result;
47: }
48:
49: throw new \RuntimeException(sprintf('Failed to execute command: %s', $command), $returnValue);
50: }
51:
52: /**
53: * Create command.
54: *
55: * @param string $args Command arguments.
56: * @return string
57: */
58: protected function createCommand($args = null)
59: {
60: if ($args === null) {
61: return $this->commandPath;
62: }
63:
64: // escapeshellarg($args) ?
65: return sprintf('%s %s', $this->commandPath, $args);
66: }
67:
68: // accessor
69:
70: /**
71: * Set command path.
72: *
73: * @param string $commandPath Command name or path.
74: * @return void
75: */
76: public function setCommandPath($commandPath)
77: {
78: $this->commandPath = $commandPath;
79: }
80:
81: /**
82: * Return command path.
83: *
84: * @return string
85: */
86: public function getCommandPath()
87: {
88: return $this->commandPath;
89: }
90: }
91: