PHPackages                             kobylinski/beetroot - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. kobylinski/beetroot

ActiveLibrary[CLI &amp; Console](/categories/cli)

kobylinski/beetroot
===================

Helpers to extend Laravel's console commands with validation rules and support for subcommands with nested arguments.

v0.1.2(1y ago)051MITPHPPHP &gt;=8.0

Since Dec 13Pushed 1y ago1 watchersCompare

[ Source](https://github.com/kobylinski/beetroot)[ Packagist](https://packagist.org/packages/kobylinski/beetroot)[ RSS](/packages/kobylinski-beetroot/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (6)Used By (0)

Beetroot
========

[](#beetroot)

This package provides tools to enhance Laravel commands with additional features, like validation for input arguments and options.

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require kobylinski/beetroot
```

Input Validation
----------------

[](#input-validation)

The WithValidate trait allows you to define validation rules for your command's input arguments and options. This ensures that the data passed to your command is clean and adheres to specific requirements.

### Usage

[](#usage)

1. Add the WithValidate trait to your command.
2. Define a rules method in your command class to specify validation rules.

### Example

[](#example)

```
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Kobylinski\Beetroot\WithValidate;

class AddUserCommand extends Command
{
  use WithValidate;

  protected $signature = "add-user {handle}";

  protected $description = "Add a new user with a unique handle";

  /**
   * Define validation rules for the command input.
   *
   * @return array
   */
  protected function rules(): array
  {
    return [
      "handle" => [
        "string", // Ensure it's a string
        "max:255", // Limit length to 255 characters
        "unique:users,handle", // Ensure it's unique in the 'users' table
      ],
    ];
  }

  /**
   * Execute the console command.
   *
   * @return int
   */
  public function handle(): int
  {
    $handle = $this->argument("handle");
    $this->info("User '{$handle}' added successfully!");

    return Command::SUCCESS;
  }
}
```

### Custom Validation Messages

[](#custom-validation-messages)

You can define custom error messages for specific validation rules by adding a messages method to your command.

```
/**
 * Define custom validation messages.
 *
 * @return array
 */
protected function messages(): array
{
  return [
    "handle.unique" => "A user with this handle already exists.",
  ];
}
```

Nested Subcommands
------------------

[](#nested-subcommands)

This helper allows you to define subcommands directly in the command's $signature, simplifying the creation of complex CLI tools with hierarchical structures.

### Defining Subcommands

[](#defining-subcommands)

The helper introduces the ability to:

- Define subcommands within the $signature.
- Nest subcommands with their own arguments, options, and descriptions.
- Group commands logically for better usability.

### Example Signature

[](#example-signature)

```
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Kobylinski\Beetroot\WithSubcommands;

class AddUserCommand extends Command
{
  use WithSubcommands;

  protected $signature = 'user
    {UserCommand
      (add
        {handle : The handle of the user}
        {name : The name of the token}
        {abilities?* : The abilities of the token})
      (*find
        {handle? : Part of the handle of the user})
      (suspend|restore
        {handle : The handle of the user})
      (remove
        {handle : The handle of the user}
        {name : The name of the token})
      (token
        {handle : The handle of the user}
        {TokenCommand
          (add
            {name : The name of the token}
            {abilities?* : The abilities of the token})
          (remove
            {name : The name of the token})
        })
    }
  ';
```

### How It Works

[](#how-it-works)

1. Top-Level Command: The main command (user in this example).
2. Subcommands: Nested command groups (e.g., add, find, suspend|restore).
3. Arguments and Options: Each subcommand can define its own arguments and options.
4. Multi-level Nesting: Subcommands can themselves have nested subcommands (e.g., token with its own subcommands).

### Handling Subcommands in handle

[](#handling-subcommands-in-handle)

Your handle method processes the input, determines the subcommand invoked, and executes the corresponding logic.

```
public function handle(): int
{
  return match ($this->argument("UserCommand")) {
    "add" => $this->addUser(),
    "find" => $this->findUser(),
    "suspend", "restore" => $this->toggleUserStatus(),
    "remove" => $this->removeUser(),
    "token" => $this->handleTokenSubcommand(),
    default => Command::INVALID,
  };
}
```

### Running the Command

[](#running-the-command)

```
# add user
php artisan user add johndoe read write

# find user
php artisan user find john

# suspend user
php artisan user suspend johndoe

# add new token
php artisan user token johndoe add monitoring read
```

### Benefits

[](#benefits)

- Readable Structure: Subcommands and their arguments are clearly defined in the signature.
- Extensible: Add new subcommands without restructuring your entire command.
- Logical Grouping: Keeps related functionality together.

WithNamedParameters Trait
-------------------------

[](#withnamedparameters-trait)

The `WithNamedParameters` trait adds the ability to define validation rules with named parameters in your Laravel application. This feature simplifies rule customization and parameter management in complex validation scenarios.

### Key Features

[](#key-features)

- **Named Parameters in Validation Rules**: Define parameters for custom validation rules directly in the validation string.
- **Automatic Parameter Mapping**: Maps the provided parameters to the rule attributes with default values.
- **Customizable Messages**: Provides a way to dynamically replace placeholders in error messages.
- **Registration of Custom Rules**: Automatically registers the custom rule with Laravel's validator.

### Example Usage

[](#example-usage)

#### Validation Rule Definition

[](#validation-rule-definition)

Define your validation rules with named parameters:

```
[
  "field" => "required|my_rule:value1,strict,true,1.2.3"
]
```

#### Parameter Configuration Overview

[](#parameter-configuration-overview)

In this example, the rule string `my_rule:value1,strict,true,1.2.3` maps directly to the following attributes:

- **`Value('category')`**: Maps to the `value1` parameter.
- **`Value('mode', dictionary: ['strict', 'lenient'])`**: Maps to the `strict` parameter, with validation restricted to the listed dictionary values.
- **`Flag('active')`**: Maps to the `true` parameter (interpreted as a boolean flag).
- **`Sequence('ids_to_exclude')`**: Maps to the `1.2.3` parameter (interpreted as a sequence of values).

These parameters are automatically accessible within the rule as class properties:

- `$this->category`
- `$this->mode`
- `$this->active`
- `$this->ids_to_exclude`

#### Abstract Example of a Custom Rule

[](#abstract-example-of-a-custom-rule)

Here’s a generalized implementation of a custom rule:

```
