HasValidators Trait

Table of contents

  1. Overview
  2. Instance Variables
  3. Support Functions
  4. Validator Callbacks

1. Overview Table of Contents

This trait is used by the Console and FrameworkQuestion class to validate input. You can use the chain the available functions or provide them as string input to the argOptionValidate and prompt functions of the Console class. Technically, you can chain them to the choice and confirm functions but it’s not advisable.


2. Instance Variables Table of Contents

protected array $errors

Contains a list of error messages.


protected string $fieldName

The name of the argument or option that is currently validated. Use this if you have multiple inputs for your command.


protected array $reservedKeywords

Supports ability to avoid input that may conflict with a reserved keyword.

The list of reserved keywords is as follows:

protected array $reservedKeywords = [
    // Reserved keywords
    'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch',
    'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do',
    'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach',
    'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final',
    'finally', 'fn', 'for', 'foreach', 'function', 'global', 'goto', 'if',
    'implements', 'include', 'include_once', 'instanceof', 'insteadof',
    'interface', 'isset', 'list', 'match', 'namespace', 'new', 'or', 'print',
    'private', 'protected', 'public', 'readonly', 'require', 'require_once',
    'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use',
    'var', 'while', 'xor', 'yield',

    // Predefined class names
    'self', 'parent', 'static',

    // Soft reserved / predefined constants
    'null', 'true', 'false',

    // Predefined classes worth avoiding
    'stdclass', 'exception', 'errorexception', 'closure', 'generator',
    'arithmetic error', 'typeerror', 'valueerror', 'stringable',

    // Enum related (PHP 8.1+)
    'enum',

    // Fiber related (PHP 8.1+)
    'fiber',
];


protected array $validators

A list of currently used validator callback functions.


3. Support Functions Table of Contents

public function addErrorMessage()

Adds a new error message to the $errors array.

Parameter:

  • string $message - The error message to be added to the $errors array.


public function displayErrorMessages()

Displays a list of all error messages.


public function fieldName()

Sets name of field to be validated.

Parameter:

  • string|array $fieldName - The name of the field to be validated.


public function setValidator()

Adds validator to array of validators to be used.

Parameter:

  • callable $validator - The anonymous function for a validator.


protected static function tokens()

Split on commas (tolerate spaces), normalize to lowercase, drop empties. Useful for cases where you have a comma separated string.

Parameter:

  • string $data - Comma separated strings of values to be converted into an array.

Returns:

  • array - An array containing values originally found in comma separated string.


protected function validate()

Calls validator callbacks. This function also ensures validators don’t bleed into next question if instance is reused.

Parameter:

  • mixed $response - The user answer.

Returns:

  • bool - True if validation passed. Otherwise, we return false.


4. Validator Callbacks Table of Contents

A. alpha()

Enforce rule where input must contain only alphabetic characters.


B. alphaNumeric()

Enforce rule where input must be alphanumeric characters.


C. between()

Ensures input is between within a certain range in length.

Parameter:

  • array $range - 2 element array where position 0 is min and position 1 is max.

Usage:

// FrameworkQuestion
$question->between([5, 10])->ask($message);

// Array parameter
['between:5:10']


D. classExists()

Checks if class exists within the specified namespace.

Parameter:

  • string|array $namespace - A string or an array containing one element with string for the namespace.

Usage:

// FrameworkQuestion
$question->classExists(self::SEEDER_NAMESPACE)->ask($message);

// Array parameter
$attributes = ['classExists:'.self::SEEDER_NAMESPACE];


E. colonNotation()

Ensures response is in colon notation format.


F. different()

Enforce rule where response and $match parameter needs to be different.

Parameter:

  • mixed - The value we want to compare.

Usage:

// FrameworkQuestion
$question = new FrameworkQuestion($this->input, $this->output);
$message = "Enter a value:";
$response1 = $question->ask($message);

$message = "Enter a different value";
$response2 = $question->different($response1)->ask($message);

// Array parameter
$response3 = Controller::prompt($message, $this->question(), ["different:$response1"]);


G. dotNotation()

Ensures response is in dot notation format.


H. email()

Ensures input is a valid E-mail address.


I. ip()

Enforce rule where input must be a valid IP address.


J. integer()

Enforce rule where input must be an integer.


K. isPortUsed()

Checks if a port on a particular host is in use. Assists in verifying if a port is available for a serve command. If the port is already in use an error message is presented to the user.

Parameter:

  • array $attributes - An array that assumes index 0 is the host and index 1 is timeout variable which is set to 3 if not provided.

Usage:

// FrameworkQuestion
$question->isPortUsed([$host, $timeout])->ask($message);

// Array parameter
["isPortUsed:$host:$timeout"]


L. list()

Ensure user inputs valid comma separated list of values. The user must provide the following in the $attributes parameter: 1) Class containing full namespaced path 2) Name of function that returns an array of strings or a comma separated array of strings. 3) A string value in this array as an alias (optional)

Parameter:

  • array $attributes - A : separate list in the following format: NamespaceToClass\Class:Method:Alias.

Usage:

// FrameworkQuestion
$question = new FrameworkQuestion($input, $output);
$message = "Enter comma separated list of channels.";
$response = $question->list([
    'Core\\Lib\\Notifications\\Notification', 'channelValues', 'all'
])->ask($message);

// Array parameter
$message = "Enter comma separated list of channels.";
$attributes = [
    'required', 
    'notReservedKeyword', 
    'list:Core\\Lib\\Notifications\\Notification:channelValues:all'
];
Notifications::argOptionValidate(
    $channels, 
    $message, 
    $this->question()
    $attributes, true
);


M. lower()

Enforces rule when input must contain at least one lower case character.


N. match()

Enforce rule where response and $match parameter needs to match.

Parameter:

  • mixed - The value we want to compare.

Usage:

// FrameworkQuestion
$question = new FrameworkQuestion($this->input, $this->output);
$message = "Enter a value:";
$response1 = $question->ask($message);

$message = "Confirm value entered";
$response2 = $question->match($response1)->ask($message);

// Array parameter
$response3 = Controller::prompt($message, $this->question(), ["match:$response1"]);


O. max()

Ensures input meets requirements for maximum allowable length.

Parameter:

  • int|array $maxRule - The maximum allowed size for input.

Usage:

// FrameworkQuestion
$response1 = $question->max(50)->ask($message);

// Array parameter
['max:50']


P. min()

Ensures input meets requirements for minimum allowable length.

Parameter:

  • int|array $minRule - The minimum allowed size for input.

Usage:

// FrameworkQuestion
$response1 = $question->min(5)->ask($message);

// Array parameter
['min:5']


Q. negative()

Enforces rule when input must be a negative number.


R. noSpecialChars()

Enforces rule when input must contain no special characters.


S. notReservedKeyword()

Enforce rule when reserved keywords should be avoided.


T. number()

Enforces rule when input must contain at least one numeric character.


U. numeric()

Enforce rule where input must contain only numeric characters.


V. required()

Ensures required input is entered.


W. positive()

Enforces rule when input must a positive number.


X. queue()

Validates if queue exists in database or redis.


Y. special()

Enforces rule when input must contain at least one special character.


Z. testFilterNotation()

Ensures response is in colon notation format.


A1. upper()

Enforces rule when input must contain at least one lower case character.


B1. url()

Enforce rule where input must be a valid URL.