Skip to content

Commit

Permalink
feat: add karnel command similar
Browse files Browse the repository at this point in the history
  • Loading branch information
SonyPradana committed Nov 22, 2023
1 parent 19baba9 commit 18bfb3c
Showing 1 changed file with 59 additions and 9 deletions.
68 changes: 59 additions & 9 deletions src/System/Integrate/Console/Karnel.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ public function handle($arguments)
{
// handle command empty
$baseArgs = $arguments[1] ?? '--help';
$commands = [];

foreach ($this->commands() as $cmd) {
$commands = array_merge($commands, $cmd->patterns(), $cmd->cmd());

if ($cmd->isMatch($baseArgs)) {
$this->app->set(
$cmd->class(),
Expand All @@ -50,20 +53,67 @@ public function handle($arguments)
}
}

// did you mean
$count = 0;
$best = 4;
$similar = (new Style('Did you mean?'))->textLightYellow()->newLines();
foreach ($this->similar($baseArgs, $commands) as $term => $level) {
if ($level > $best) {
break;
}
$similar->push(' > ')->push($term)->textYellow()->newLines();
$count++;
}

// if command not register
(new Style())
->push('Command Not Found, run help command')->textRed()->newLines(2)
->push('> ')->textDim()
->push('php ')->textYellow()
->push('cli ')
->push('--help')->textDim()
->newLines()
->out()
;
if ($count === 0) {
(new Style())
->push('Command Not Found, run help command')->textRed()->newLines(2)
->push('> ')->textDim()
->push('php ')->textYellow()
->push('cli ')
->push('--help')->textDim()
->newLines()
->out()
;

return $this->exit_code = 1;
}

$similar->out();

return $this->exit_code = 1;
}

/**
* Return similar from given array, compare with key.
*
* @param string[] $matchs
*
* @return array<string, int> Sorted from simalar
*/
private function similar(string $find, $matchs)
{
$shortest = -1;

foreach ($matchs as $match) {
$level = levenshtein($find, $match);
if (0 === $level) {
$closest[$match] = $level;
$shortest = 0;

break;
}
if ($level <= $shortest || $shortest < 0) {
$closest[$match] = $level;
$shortest = $level;
}
}
asort($closest);

Check failure on line 112 in src/System/Integrate/Console/Karnel.php

View workflow job for this annotation

GitHub Actions / PHPStan prefer-stable

Variable $closest might not be defined.

return $closest;

Check failure on line 114 in src/System/Integrate/Console/Karnel.php

View workflow job for this annotation

GitHub Actions / PHPStan prefer-stable

Variable $closest might not be defined.
}

/**
* Get karne exit status code.
*
Expand Down

0 comments on commit 18bfb3c

Please sign in to comment.