Skip to content

wtl-oss/os-commandline-validation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


Logo

Laravel Command Line Validation

This is a package to validate your custom Laravel artisan commands.

Table of Contents

  1. About The Project
  2. Getting Started
  3. UML Class Diagrams
  4. How To Validate
  5. Example Validation
  6. Generate Signatures Automatically
  7. Advices
  8. Contributing
  9. License
  10. Credits

About The Project

This is a package to validate your custom laravel commands. We tried to integrate the project as well as possible into the laravel ecosystem. So that you can use the same rule logic for your validation as with the normal validation forms.

In laravel you can easily validate user data in forms. But there wasn't a standard solution if you want to validate something in the command line without requests. We want to change that and want to offer a simple solution with this package for the command line validation process.

Built With

Should run with laravel 5.x and PHP 7.4 =<

Getting Started

To get a local copy up and running, follow these simple steps.

Installation

  1. Go to your project folder in your favorite command line interface

  2. Install the Composer package

    composer require wtl/command-line-validation

Artisan Console Class

This package is based on the Laravel Artisan Console. You can create this laravel class with the following command:

php artisan make:command YourArtisanCommand

and run it with this command

php artisan YourArtisanCommand

for more have a look at the documentation https://laravel.com/docs/8.x/artisan

UML Class Diagrams

Overview over the package:

This package provides 2 classes: AbstractConsoleValidator and GenerateSignatureTrait

You have to create 2 classes: YourArtisanCommand (explained above) and ConcreteConsoleValidator

More accurate class diagram:

How to validate

  1. Create a class ConcreteConsoleValidator that extends AbstractConsoleValidator
  2. Define the abstract method 'rules()' with your own rules and return an array (just like with form requests). https://laravel.com/docs/8.x/validation#creating-form-requests
  3. Inject the class 'ConcreteConsoleValidator' into your handle() method in the class YourArtisanCommand
     public function handle(ConcreteConsoleValidator $concreteConsoleValidator): int {}
  4. Use the ConcreteConsoleValidator's method 'executeValidation(bool, array): bool' in your handle() method to validate your data.
    1. Set the arguments

      Parameter Type Argument Description
      $throwException bool true The method returns the validated data in an array if the validation was correct and throws a ValidationException if it was incorrect.
        bool false The method returns the validated data in an array if the validation was correct and false if it was incorrect.
      $optionsCommandLineUserInput array $this->options() Define your command line input expectations in the signature attribute and call these formatted in an array for example with this method: https://laravel.com/docs/8.x/artisan#options
    2. If the validation fails, the validation error messages will get saved as string and can be returned with the ConcreteConsoleValidator's method 'getLastErrorMessages()'.

Example validation

class YourArtisanCommand:

protected $signature = 'command:name {--name=}{--email=}{--date_of_birth}';

public function handle(ConcreteValidator $concreteValidator): int
{    
    $validatedData = $concreteValidator->executeValidation($this->options(), false);
    if($validatedData==false){
        $this->error($concreteValidator->getLastErrorMessages());
    }
    else{
        $this->info('The validation was correct.');
    }
    return 0;
}

class ConcreteConsoleValidator: (extends AbstractConsoleValidator)

public function rules(): array
    {
        return [
            'name' => ['max:30'],
            'email' => ['required', 'unique:validations', 'email:rfc,dns'],
            'date_of_birth' => ['required', 'date_format:d-m-Y', 'before:-21 years']
        ];
    }

Generate signatures automatically

Usually you have to declare the input expectations manually in the signature attribute of your YourArtisanCommand class. With this package you can create the signature automatically with the help of the trait 'GenerateSignatureTrait'.

The trait generates the signature from the method 'rules()' of your class 'ConcreteConsoleValidator'. The trait method creates for each rule one input expectation in form of an option.

So you have to create a rule for every input expectation that you want to validate in order to use the trait.

How to generate your signature

  1. Use the trait in the class YourArtisanCommand

    class YourArtisanCommand extends Command {
     use GenerateSignatureTrait;
  2. Set the new signature in the constructor with the trait's method generateSignature(array, string, string).
    The method requires your rules and a command name as parameters.

    public function __construct(ConcreteConsoleValidator $concreteConsoleValidator)
     {
         $this->signature = $this->generateSignature($concreteConsoleValidator->rules(), 'commandName');
         parent::__construct();
     }

    The parent constructor needs the signature therefore you have to declare the signature beforehand.

  3. OPTIONAL: The third argument of the method is optional. You can use it if you want to set input expectations which should not be validated. Write your expectations in the string as if you were writing it in the signature attribute.
    https://laravel.com/docs/8.x/artisan#defining-input-expectations

    For example you could use it as boolean switch for the the ConcreteConsoleValidator's method 'executeValidation(bool, array): bool'

    $this->signature = $this->generateSignature($userRequestRules->rules(), $this->commandName, '{--x|reportException}');

    and in the handle method of your YourArtisanCommand class like this:

    $userInputArray = $this->options();
    $userRequestRules->executeValidation($userInputArray['reportException'], $this->options());

    With this switch you can now decide in the command line whether you want to throw an exception or not.

    php artisan commandName --email [email protected] --age 25 -x

Advices

  1. This command displays how you can use your command. It displays the command description and which input options are available.

    php artisan YourArtisanCommandName --help
  2. If you have already defined rules for your form request, you can synchronize both rules() methods (form request & concreteConsoleValidator) with another trait.

Contributing

Contributions make the open source community to such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Code an amazing feature with tests
  4. Commit your changes (git commit -m 'Add some AmazingFeature')
  5. Push to the branch (git push origin feature/AmazingFeature)
  6. Open a pull request

License

Distributed under the MIT License. See LICENSE for more information.

Credits

Big shout out to Webteam Leipzig that made the project possible.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages