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 7 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
12 changes: 10 additions & 2 deletions app/Console/Hello.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

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

final readonly class Hello
{
Expand All @@ -22,8 +23,15 @@ 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';

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();
}
}
27 changes: 27 additions & 0 deletions src/ConsoleArgument.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Tempest\Console;

use Attribute;
use Tempest\Support\ArrayHelper;

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER)]
final class ConsoleArgument
{
/** @var string[] */
public readonly array $help;

/**
* @param string|string[] $help
* @param string[] $aliases
*/
public function __construct(
public readonly ?string $description = null,
array|string $help = [],
przemyslaw-przylucki marked this conversation as resolved.
Show resolved Hide resolved
public readonly array $aliases = [],
) {
$this->help = ArrayHelper::wrap($help);
}
}
93 changes: 93 additions & 0 deletions src/ConsoleArgumentBag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?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) {
if (str_starts_with($argument, '--')) {
[$key, $value] = $this->parseNamedArgument($argument);

$this->add(
new ConsoleInputArgument(
name: $key,
value: $value,
position: $position,
)
);

continue;
przemyslaw-przylucki marked this conversation as resolved.
Show resolved Hide resolved
}

$this->add(
new ConsoleInputArgument(
name: null,
value: $argument,
position: $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] ?? '';
}

/**
* @param string $argument
*
* @return array{0: string, 1: mixed}
*/
private function parseNamedArgument(string $argument): array
{
$parts = explode('=', str_replace('--', '', $argument));

$key = $parts[0];

$value = $parts[1] ?? true;

$value = match ($value) {
'true' => true,
'false' => false,
default => $value,
};

return [$key, $value];
}
}
47 changes: 47 additions & 0 deletions src/ConsoleArgumentDefinition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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 readonly array $help;

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 = [],
string|array $help = [],
)
{
$this->help = $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(),
default: $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
hasDefault: $parameter->isDefaultValueAvailable(),
position: $parameter->getPosition(),
description: $attribute?->description,
aliases: $attribute->aliases ?? [],
help: $attribute?->help ?? [],
);
}

}
34 changes: 28 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,21 @@ public function __unserialize(array $data): void
objectOrMethod: $data['handler_class'],
method: $data['handler_method'],
);
$this->aliases = $data['aliases'];
$this->help = $data['help'];
}

/**
* @return ConsoleArgumentDefinition[]
*/
public function getDefinition(): array
przemyslaw-przylucki marked this conversation as resolved.
Show resolved Hide resolved
{
$arguments = [];

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

return $arguments;
}
}
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