Skip to content

Commit

Permalink
feat: multy pattern (#231)
Browse files Browse the repository at this point in the history
support multy pattern matching
  • Loading branch information
SonyPradana authored Oct 30, 2023
1 parent 64ee717 commit 2b3558d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/System/Integrate/ValueObjects/CommandMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __construct(array $command)
}

/**
* Command rule.
* Command rule wrap to array.
*
* @return string[]
*/
Expand All @@ -44,6 +44,18 @@ public function mode(): string
return $this->command['mode'] ?? 'full';
}

/**
* Pattern rule wrap to array.
*
* @return string[]
*/
public function patterns()
{
$pattern = $this->command['pattern'];

return is_array($pattern) ? $pattern : [$pattern];
}

public function class(): string
{
if (is_array($this->fn()) && array_key_exists(0, $this->fn())) {
Expand Down Expand Up @@ -79,9 +91,18 @@ public function defaultOption()
public function match()
{
if (array_key_exists('pattern', $this->command)) {
$pattern = $this->command['pattern'];
$pattern = $this->command['pattern'];
$patterns = is_array($pattern) ? $pattern : [$pattern];

return fn ($given): bool => $given == $pattern;
return function ($given) use ($patterns): bool {
foreach ($patterns as $cmd) {
if ($given == $cmd) {
return true;
}
}

return false;
};
}

if (array_key_exists('match', $this->command)) {
Expand Down
27 changes: 27 additions & 0 deletions tests/Integrate/Console/KarnelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ public function itCanCallCommandUsingPatternCommand()
$this->assertTrue($hasContent);
}

/** @test */
public function itCanCallCommandUsingPatternGroupCommand()
{
$karnel = new NormalCommand($this->app);
ob_start();
$exit = $karnel->handle(['cli', 'pattern1']);
$out = ob_get_clean();

$this->assertEquals(0, $exit);
$hasContent = Str::contains($out, 'command has founded');
$this->assertTrue($hasContent);

// 2
$karnel = new NormalCommand($this->app);
ob_start();
$exit = $karnel->handle(['cli', 'pattern2']);
$out = ob_get_clean();

$this->assertEquals(0, $exit);
$hasContent = Str::contains($out, 'command has founded');
$this->assertTrue($hasContent);
}

/** @test */
public function itCanCallCommandWithDefaultOption()
{
Expand Down Expand Up @@ -185,6 +208,10 @@ protected function commands()
'pattern' => 'use:pattern',
'fn' => [FoundedCommand::class, 'main'],
]),
new CommandMap([
'pattern' => ['pattern1', 'pattern2'],
'fn' => [FoundedCommand::class, 'main'],
]),
new CommandMap([
'pattern' => 'use:default_option',
'fn' => [FoundedCommand::class, 'default'],
Expand Down

0 comments on commit 2b3558d

Please sign in to comment.