Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Argument Bag, aliases, help lines #1

Merged
merged 8 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/Console/FailCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
final readonly class FailCommand
{
#[ConsoleCommand('fail')]
public function __invoke(string $input)
public function __invoke(string $input = 'default')
{
failingFunction($input);
}
Expand Down
15 changes: 12 additions & 3 deletions app/Console/Hello.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Console;

use Tempest\Console\ConsoleArgument;
use Tempest\Console\ConsoleCommand;
use Tempest\Console\ConsoleOutput;

Expand All @@ -22,9 +23,17 @@ public function world(string $input)
$this->output->error($input);
}

#[ConsoleCommand]
public function test(?int $optionalValue = null, bool $flag = false)
{
#[ConsoleCommand(
aliases: ['t']
)]
public function test(
#[ConsoleArgument(
help: 'The path to the file',
aliases: ['ov']
)]
?int $optionalValue = null,
bool $flag = false
) {
$value = $optionalValue ?? 'null';

$this->output->info("{$value}");
Expand Down
4 changes: 2 additions & 2 deletions src/Actions/RenderConsoleCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ public function __invoke(ConsoleCommand $consoleCommand): void
$parts[] = $this->renderParameter($parameter);
}

if ($consoleCommand->getDescription() !== null && $consoleCommand->getDescription() !== '') {
$parts[] = "- {$consoleCommand->getDescription()}";
if ($consoleCommand->description !== null && $consoleCommand->description !== '') {
$parts[] = "- {$consoleCommand->description}";
}

$this->output->writeln(' ' . implode(' ', $parts));
Expand Down
47 changes: 18 additions & 29 deletions src/ConsoleApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Tempest\Console;

use ArgumentCountError;
use ReflectionMethod;
use Tempest\AppConfig;
use Tempest\Application;
use Tempest\Console\Actions\RenderConsoleCommandOverview;
Expand All @@ -32,7 +31,7 @@ public static function boot(
$container = $kernel->init();

$application = new self(
args: $_SERVER['argv'],
argumentBag: new ConsoleArgumentBag($_SERVER['argv']),
container: $container,
appConfig: $appConfig,
);
Expand All @@ -48,7 +47,7 @@ public static function boot(
}

public function __construct(
private array $args,
private ConsoleArgumentBag $argumentBag,
private Container $container,
private AppConfig $appConfig,
) {
Expand All @@ -57,7 +56,7 @@ public function __construct(
public function run(): void
{
try {
$commandName = $this->args[1] ?? null;
$commandName = $this->argumentBag->getCommandName();

if (! $commandName) {
$this->container->get(RenderConsoleCommandOverview::class)();
Expand Down Expand Up @@ -94,40 +93,30 @@ private function handleCommand(string $commandName): void

$handler = $consoleCommand->handler;

$params = $this->resolveParameters($handler);

$commandClass = $this->container->get($handler->getDeclaringClass()->getName());

try {
$handler->invoke($commandClass, ...$params);
$handler->invoke(
$commandClass,
...$this->buildInput($consoleCommand),
);
} catch (ArgumentCountError) {
throw new InvalidCommandException($commandName, $consoleCommand);
}
}

private function resolveParameters(ReflectionMethod $handler): array
/**
* Returns resolved key-value pair of parameters.
*
* @return array<string, mixed>
*/
private function buildInput(ConsoleCommand $command): array
przemyslaw-przylucki marked this conversation as resolved.
Show resolved Hide resolved
{
$parameters = $handler->getParameters();
$inputArguments = $this->args;
unset($inputArguments[0], $inputArguments[1]);
$inputArguments = array_values($inputArguments);

$result = [];

foreach ($inputArguments as $i => $argument) {
if (str_starts_with($argument, '--')) {
$parts = explode('=', str_replace('--', '', $argument));

$key = $parts[0];

$result[$key] = $parts[1] ?? true;
} else {
$key = ($parameters[$i] ?? null)?->getName();

$result[$key ?? $i] = $argument;
}
}
$builder = new ConsoleInputBuilder(
$command->getDefinition(),
$this->argumentBag,
);

return $result;
return $builder->build();
}
}
18 changes: 18 additions & 0 deletions src/ConsoleArgument.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace Tempest\Console;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER)]
final class ConsoleArgument
{
public function __construct(
public readonly ?string $description = null,
public readonly string $help = '',
public readonly array $aliases = [],
) {
}
}
53 changes: 53 additions & 0 deletions src/ConsoleArgumentBag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Tempest\Console;

final class ConsoleArgumentBag
{
/** @var ConsoleInputArgument[] */
protected array $arguments = [];

/** @var string[] */
protected array $path = [];

/**
* @param array<string|int, mixed> $arguments
*/
public function __construct(array $arguments)
{
$this->path = array_filter([
$arguments[0] ?? null,
$arguments[1] ?? null,
]);

unset($arguments[0], $arguments[1]);

foreach (array_values($arguments) as $position => $argument) {
$this->add(
ConsoleInputArgument::fromString($argument, $position)
);
}
}

/**
* @return ConsoleInputArgument[]
*/
public function all(): array
{
return $this->arguments;
}

private function add(ConsoleInputArgument $argument): self
{
$this->arguments[] = $argument;

return $this;
}

public function getCommandName(): string
{
return $this->path[1] ?? '';
}
}
60 changes: 60 additions & 0 deletions src/ConsoleArgumentDefinition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace Tempest\Console;

use ReflectionParameter;

final class ConsoleArgumentDefinition
przemyslaw-przylucki marked this conversation as resolved.
Show resolved Hide resolved
{
public function __construct(
public readonly string $name,
public readonly string $type,
public readonly mixed $default,
public readonly bool $hasDefault,
public readonly int $position,
public readonly ?string $description = null,
public readonly array $aliases = [],
public readonly string $help = '',
) {
}

public static function fromParameter(ReflectionParameter $parameter): ConsoleArgumentDefinition
{
$attributes = $parameter->getAttributes(ConsoleArgument::class);

/** @var ?ConsoleArgument $attribute */
$attribute = ($attributes[0] ?? null)?->newInstance();

return new ConsoleArgumentDefinition(
name: $parameter->getName(),
type: $parameter->getType()->getName(),

Check failure on line 32 in src/ConsoleArgumentDefinition.php

View workflow job for this annotation

GitHub Actions / Perform Static Analysis

Call to an undefined method ReflectionType::getName().
default: $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
hasDefault: $parameter->isDefaultValueAvailable(),
position: $parameter->getPosition(),
description: $attribute?->description,
aliases: $attribute->aliases ?? [],
help: $attribute?->help,
);
}

public function matchesArgument(ConsoleInputArgument $argument): bool
{
if ($argument->position === $this->position) {
return true;
}

if (! $argument->name) {
return false;
}

foreach ([$argument->name, ...$this->aliases] as $alias) {
if ($alias === $argument->name) {
return true;
}

return false;
}
}
}
31 changes: 25 additions & 6 deletions src/ConsoleCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,25 @@

use Attribute;
use ReflectionMethod;
use Tempest\Support\ArrayHelper;

#[Attribute]
final class ConsoleCommand
{
public ReflectionMethod $handler;

/** @var string[] */
public readonly array $help;

public function __construct(
private readonly ?string $name = null,
private readonly ?string $description = null,
public readonly ?string $description = null,
/** @var string[] */
public readonly array $aliases = [],
/** @var string|string[] $help */
string|array $help = [],
) {
$this->help = ArrayHelper::wrap($help);
}

public function setHandler(ReflectionMethod $handler): self
Expand All @@ -36,18 +45,15 @@ public function getName(): string
: strtolower($this->handler->getDeclaringClass()->getShortName() . ':' . $this->handler->getName());
}

public function getDescription(): ?string
{
return $this->description;
}

public function __serialize(): array
{
return [
'name' => $this->name,
'description' => $this->description,
'handler_class' => $this->handler->getDeclaringClass()->getName(),
'handler_method' => $this->handler->getName(),
'aliases' => $this->aliases,
'help' => $this->help,
];
}

Expand All @@ -59,5 +65,18 @@ public function __unserialize(array $data): void
objectOrMethod: $data['handler_class'],
method: $data['handler_method'],
);
$this->aliases = $data['aliases'];
$this->help = $data['help'];
}

public function getDefinition(): ConsoleCommandDefinition
{
$arguments = [];

foreach ($this->handler->getParameters() as $parameter) {
$arguments[$parameter->getName()] = ConsoleArgumentDefinition::fromParameter($parameter);
}

return new ConsoleCommandDefinition($arguments);
}
}
15 changes: 15 additions & 0 deletions src/ConsoleCommandDefinition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Tempest\Console;

final class ConsoleCommandDefinition
{
public function __construct(
/** @var ConsoleArgumentDefinition[] */
public readonly array $argumentDefinitionList,
brendt marked this conversation as resolved.
Show resolved Hide resolved
) {

}
}
8 changes: 8 additions & 0 deletions src/ConsoleConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ public function addCommand(ReflectionMethod $handler, ConsoleCommand $consoleCom

$this->commands[$consoleCommand->getName()] = $consoleCommand;

foreach ($consoleCommand->aliases as $alias) {
if (array_key_exists($alias, $this->commands)) {
continue;
}

$this->commands[$alias] = $consoleCommand;
}

return $this;
}
}
Loading
Loading