This is a package to validate your custom Laravel artisan commands.
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.
Should run with laravel 5.x and PHP 7.4 =<
To get a local copy up and running, follow these simple steps.
-
Go to your project folder in your favorite command line interface
-
Install the Composer package
composer require wtl/command-line-validation
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
This package provides 2 classes: AbstractConsoleValidator and GenerateSignatureTrait
You have to create 2 classes: YourArtisanCommand (explained above) and ConcreteConsoleValidator
- Create a class ConcreteConsoleValidator that extends AbstractConsoleValidator
- 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
- Inject the class 'ConcreteConsoleValidator' into your handle() method in the class YourArtisanCommand
public function handle(ConcreteConsoleValidator $concreteConsoleValidator): int {}
- Use the ConcreteConsoleValidator's method 'executeValidation(bool, array): bool' in your handle() method to validate
your data.
-
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 -
If the validation fails, the validation error messages will get saved as string and can be returned with the ConcreteConsoleValidator's method 'getLastErrorMessages()'.
-
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']
];
}
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.
-
Use the trait in the class YourArtisanCommand
class YourArtisanCommand extends Command { use GenerateSignatureTrait;
-
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.
-
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
-
This command displays how you can use your command. It displays the command description and which input options are available.
php artisan YourArtisanCommandName --help
-
If you have already defined rules for your form request, you can synchronize both rules() methods (form request & concreteConsoleValidator) with another trait.
Contributions make the open source community to such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Code an amazing feature with tests
- Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a pull request
Distributed under the MIT License. See LICENSE
for more information.
Big shout out to Webteam Leipzig that made the project possible.