Skip to content

Commit a756380

Browse files
committed
Use custom exceptions
Use InvalidArgumentException for the invalid argument case, and introduce a new CommandException class for the rest.
1 parent 9af8afd commit a756380

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

src/Command.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ private function __construct()
2323
public static function exec($command, array $params = array())
2424
{
2525
if (empty($command)) {
26-
throw new \Exception('Command line is empty');
26+
throw new \InvalidArgumentException('Command line is empty');
2727
}
2828

2929
$command = self::bindParams($command, $params);
@@ -37,7 +37,7 @@ public static function exec($command, array $params = array())
3737
}
3838

3939
if ($code !== 0) {
40-
throw new \Exception($output . ' Command line: ' . $command);
40+
throw new CommandException($command, $output, $code);
4141
}
4242

4343
return $output;

src/CommandException.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
namespace pastuhov\Command;
3+
4+
class CommandException extends \RuntimeException
5+
{
6+
protected $command;
7+
protected $output;
8+
protected $returnCode;
9+
10+
public function __construct($command, $output, $returnCode)
11+
{
12+
$this->command = $command;
13+
$this->output = $output;
14+
$this->returnCode = $returnCode;
15+
16+
if ($this->returnCode == 127) {
17+
$message = 'Command not found: "' . $this->getCommand() . '"';
18+
} else {
19+
$message = 'Command "' . $this->getCommand() . '" exited with code ' . $this->getReturnCode() . ': ' . $this->getOutput();
20+
}
21+
22+
parent::__construct($message);
23+
}
24+
25+
public function getCommand()
26+
{
27+
return $this->command;
28+
}
29+
30+
public function getOutput()
31+
{
32+
return $this->output;
33+
}
34+
35+
public function getReturnCode()
36+
{
37+
return $this->returnCode;
38+
}
39+
}

tests/CommandTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public function testExec()
3131
*/
3232
public function testExecException()
3333
{
34-
$this->setExpectedException('Exception');
34+
$this->setExpectedException('pastuhov\Command\CommandException');
3535

3636
$output = Command::exec(
3737
'echo111'
@@ -43,7 +43,7 @@ public function testExecException()
4343
*/
4444
public function testExecEmptyCommand()
4545
{
46-
$this->setExpectedException('Exception');
46+
$this->setExpectedException('InvalidArgumentException');
4747

4848
$output = Command::exec(
4949
''

0 commit comments

Comments
 (0)