Skip to content

Commit 5c6e57e

Browse files
committed
Merge pull request #70 from php-school/missing-args-pretty-error
Print error when missing command arguments
2 parents 48e8f8e + 673ed43 commit 5c6e57e

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

src/Application.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
use DI\ContainerBuilder;
77
use PhpSchool\PhpWorkshop\Check\CheckInterface;
88
use PhpSchool\PhpWorkshop\Check\CheckRepository;
9+
use PhpSchool\PhpWorkshop\Exception\MissingArgumentException;
910
use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
11+
use PhpSchool\PhpWorkshop\Output\OutputInterface;
1012
use PhpSchool\PhpWorkshop\ResultRenderer\ResultRendererInterface;
1113

1214
/**
@@ -161,7 +163,21 @@ public function run()
161163
$checkRepository->registerCheck($check);
162164
});
163165

164-
$router = $container->get(CommandRouter::class);
165-
return $router->route();
166+
try {
167+
$exitCode = $container->get(CommandRouter::class)->route();
168+
} catch (MissingArgumentException $e) {
169+
$container
170+
->get(OutputInterface::class)
171+
->printError(
172+
sprintf(
173+
'Argument%s: "%s" %s missing!',
174+
count($e->getMissingArguments()) > 1 ? 's' : '',
175+
implode('", "', $e->getMissingArguments()),
176+
count($e->getMissingArguments()) > 1 ? 'are' : 'is'
177+
)
178+
);
179+
return 1;
180+
}
181+
return $exitCode;
166182
}
167183
}

src/Exception/MissingArgumentException.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,18 @@
1111
*/
1212
class MissingArgumentException extends RuntimeException
1313
{
14+
/**
15+
* @var array
16+
*/
17+
private $missingArguments = [];
18+
1419
/**
1520
* @param $commandName
1621
* @param array $missingArguments
1722
*/
1823
public function __construct($commandName, array $missingArguments)
1924
{
25+
$this->missingArguments = $missingArguments;
2026
parent::__construct(
2127
sprintf(
2228
'Command: "%s" is missing the following arguments: "%s"',
@@ -25,4 +31,12 @@ public function __construct($commandName, array $missingArguments)
2531
)
2632
);
2733
}
34+
35+
/**
36+
* @return array
37+
*/
38+
public function getMissingArguments()
39+
{
40+
return $this->missingArguments;
41+
}
2842
}

test/Exception/MissingArgumentExceptionTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,7 @@ public function testException()
1919
'Command: "some-route" is missing the following arguments: "arg1", "arg2"',
2020
$e->getMessage()
2121
);
22+
23+
$this->assertSame(['arg1', 'arg2'], $e->getMissingArguments());
2224
}
2325
}

0 commit comments

Comments
 (0)