|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tempest\Console\Middleware; |
| 4 | + |
| 5 | +use Tempest\Console\ConsoleMiddleware; |
| 6 | +use Tempest\Console\ConsoleMiddlewareCallable; |
| 7 | +use Tempest\Console\Exceptions\UnknownArgumentsException; |
| 8 | +use Tempest\Console\ExitCode; |
| 9 | +use Tempest\Console\GlobalFlags; |
| 10 | +use Tempest\Console\Initializers\Invocation; |
| 11 | +use Tempest\Console\Input\ConsoleArgumentDefinition; |
| 12 | +use Tempest\Console\Input\ConsoleInputArgument; |
| 13 | +use Tempest\Core\Priority; |
| 14 | + |
| 15 | +use function Tempest\Support\arr; |
| 16 | + |
| 17 | +#[Priority(Priority::FRAMEWORK - 6)] |
| 18 | +final class ValidateNamedArgumentsMiddleware implements ConsoleMiddleware |
| 19 | +{ |
| 20 | + public function __invoke(Invocation $invocation, ConsoleMiddlewareCallable $next): ExitCode|int |
| 21 | + { |
| 22 | + $allowedParameterNames = arr($invocation->consoleCommand->getArgumentDefinitions()) |
| 23 | + ->flatMap(function (ConsoleArgumentDefinition $definition) { |
| 24 | + return [$definition->name, ...$definition->aliases]; |
| 25 | + }) |
| 26 | + ->map(function (string $name) { |
| 27 | + return ltrim($name, '-'); |
| 28 | + }); |
| 29 | + |
| 30 | + $invalidInput = arr($invocation->argumentBag->arguments) |
| 31 | + ->filter(fn (ConsoleInputArgument $argument) => $argument->name !== null) |
| 32 | + ->filter(fn (ConsoleInputArgument $argument) => ! $allowedParameterNames->contains(ltrim($argument->name, '-'))) |
| 33 | + ->filter(fn (ConsoleInputArgument $argument) => ! in_array($argument->name, GlobalFlags::values(), strict: true)); |
| 34 | + |
| 35 | + if ($invalidInput->isNotEmpty()) { |
| 36 | + throw new UnknownArgumentsException( |
| 37 | + consoleCommand: $invocation->consoleCommand, |
| 38 | + invalidArguments: $invalidInput, |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + return $next($invocation); |
| 43 | + } |
| 44 | +} |
0 commit comments