Image

Spawner

Spawn boilerplate code for any PHP application component

Development Boilerplate Generator PHP

Validators

Validators are set of rules defined on an Ask Input to validate user input.

name:
  input: ask
  message: What is name of the form ?
  default: DefaultForm
  validators:
    empty:
      message: Form name cannot be empty
    ends_with:
      message: Name should end with `Form`
      options: ['Form']

A validator has two key values

  • Message (Required) - A message that will be prompt when this validation rule has failed
  • Options (Optional) - Accepts an array of arguments. Depends on the validator if it accepts arguments

Default Validators

Spawner ships with some default validators which you can immediately use.

Empty

Ensures that the user input is not an empty string

validators:
  empty:
    message: Form name cannot be empty

Starts with

Ensures that the user input start with the specified string

validators:
  starts_with:
    message: Your input should begin with 'User'
    options: ['User']

Ends with

Ensures that the user input ends with the specified string

validators:
  ends_with:
    message: Name should end with `Form`
    options: ['Form']

Defining your own Validators

Let's define a validator with a key of custom. This validator will accept an option that determines if the input is valid if it does not match the specified string.

validators:
  custom:
    message: Your input is invalid
    options: ['name']

To define your own validators, create a custom class that extends a specific base class.

namespace App\Validators;

use Alexecus\Spawner\Validators\AbstractValidator;

class CustomValidator extends AbstractValidator
{
    /**
     * @{inheritdoc}
     */
    public function validate($value, $options = [])
    {
        $text = $options[0];

        return strtolower($value) !== $text;
    }
}

Implement a validate method, it should return a boolean. Options are supported too, the options correspond to an array of parameters passed from the YAML definition.

Register your validator on your console class afterwards, before running it.

$app = new Alexecus\Spawner\Application();

$app->addValidator('custom', App\Validators\MyValidator::class);