Skip to content

Commit

Permalink
Try stricter API for Command args existence.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Apr 6, 2024
1 parent d3dd712 commit d0ab55c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
20 changes: 20 additions & 0 deletions src/Console/Arguments.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ public function hasArgumentAt(int $index): bool
*/
public function hasArgument(string $name): bool
{
$this->assertArgumentExists($name);

$offset = array_search($name, $this->argNames, true);
if ($offset === false) {
return false;
Expand All @@ -120,6 +122,8 @@ public function hasArgument(string $name): bool
*/
public function getArgument(string $name): ?string
{
$this->assertArgumentExists($name);

$offset = array_search($name, $this->argNames, true);
if ($offset === false || !isset($this->args[$offset])) {
return null;
Expand Down Expand Up @@ -205,4 +209,20 @@ public function hasOption(string $name): bool
{
return isset($this->options[$name]);
}

/**
* @param string $name
* @return void
*/
protected function assertArgumentExists(string $name): void
{
if (in_array($name, $this->argNames, true)) {
return;
}

throw new ConsoleException(sprintf(
'Argument `%s` is not defined on this Command. Could this be an option maybe?',
$name
));
}
}
19 changes: 15 additions & 4 deletions tests/TestCase/Console/ArgumentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@ public function testHasArgument(): void
$args = new Arguments($values, [], $names);
$this->assertTrue($args->hasArgument('size'));
$this->assertTrue($args->hasArgument('color'));
$this->assertFalse($args->hasArgument('hair'));
$this->assertFalse($args->hasArgument('Hair'), 'casing matters');
$this->assertFalse($args->hasArgument('odd'));
}

Expand All @@ -85,8 +83,7 @@ public function testGetArgument(): void
$args = new Arguments($values, [], $names);
$this->assertSame($values[0], $args->getArgument('size'));
$this->assertSame($values[1], $args->getArgument('color'));
$this->assertNull($args->getArgument('Color'));
$this->assertNull($args->getArgument('hair'));
$this->assertNull($args->getArgument('odd'));
}

/**
Expand All @@ -101,6 +98,20 @@ public function testGetArgumentMissing(): void
$this->assertNull($args->getArgument('color'));
}

/**
* get arguments by name
*/
public function testGetArgumentInvalid(): void
{
$values = [];
$names = ['size'];
$args = new Arguments($values, [], $names);

$this->expectException(ConsoleException::class);

$args->getArgument('color');
}

/**
* test getOptions()
*/
Expand Down

0 comments on commit d0ab55c

Please sign in to comment.