class Notifications extends Console

Utilities that support console commands related to Notifications:

  • Resolving notifiables and channels from CLI options
  • Building per-send payloads/overrides
  • Scaffolding notification classes and the notifications migration
  • Performing dry-runs and actual sends via a notifiable

Traits

Supports ability to validate console input.

Constants

NOTIFICATION_NAMESPACE

NOTIFICATION_PATH

Properties

protected array $errors

An array of errors.

from  HasValidators
protected string $fieldName

The name of the field to be validated.

from  HasValidators
protected array $reservedKeywords

An array of reserved keywords.

from  HasValidators
protected array $validators

Array of validator callbacks.

from  HasValidators

Methods

void
addErrorMessage(string $message)

Adds a new error message to the $errors array.

alpha()

Enforce rule where input must contain only alphabetic characters.

alphaNumeric()

Enforce rule where input must be alphanumeric characters.

between(array $range)

Ensures input is between within a certain range in length.

classExists(string|array $namespace)

Checks if class exists within the specified namespace.

colonNotation()

Ensures response is in colon notation format.

different(mixed $data)

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

void
displayErrorMessages()

Displays a list of all error messages.

dotNotation()

Ensures response is in dot notation format.

email()

Ensures input is a valid E-mail address.

fieldName(string|array $fieldName)

Sets name of field to be validated.

ip()

Enforce rule where input must be a valid IP address.

integer()

Enforce rule where input must be an integer.

isPortUsed(array $attributes)

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.

list(array $attributes)

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.

lower()

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

match(mixed $match)

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

max(int|array $maxRule)

Ensures input meets requirements for maximum allowable length.

min(int|array $minRule)

Ensures input meets requirements for minimum allowable length.

negative()

Enforces rule when input must be a negative number.

noSpecialChars()

Enforces rule when input must contain no special characters.

notReservedKeyword()

Enforce rule when reserved keywords should be avoided.

number()

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

numeric()

Enforce rule where input must contain only numeric characters.

required()

Ensures required input is entered.

positive()

Enforces rule when input must a positive number.

queue()

Validates if queue exists in database or redis.

setValidator(callable $validator)

Adds validator to array of validators to be used.

special()

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

testFilterNotation()

Ensures response is in colon notation format.

static array
tokens(string $data)

Split on commas (tolerate spaces), normalize to lowercase, drop empties.

upper()

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

url()

Enforce rule where input must be a valid URL.

bool
validate(mixed $response)

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

__construct(string $fieldName = "")

Creates new instance of Console class.

from  Console
static void
argOptionValidate(string $field, string $message, FrameworkQuestion $question, array $validators = [], bool $defaultNone = false)

Validates argument and option input. If validation fails then the user is asked to enter a new value.

from  Console
static mixed
choice(string $message, array $choices, FrameworkQuestion $question, string|bool|int|float|null $default = null)

Ask user to confirm among several options based on question asked.

from  Console
static mixed
confirm(string $message, FrameworkQuestion $question, string|bool|int|float|null $default = true)

Asks a user to confirm based on question asked.

from  Console
static Console
getInstance(string $fieldName = "")

Returns instance of this or child helper class.

from  Console
static string
prompt(string $message, FrameworkQuestion $question, array $attributes = [], array $suggestions = [], string|bool|int|float|null $default = null, bool $defaultNone = false)

Asks user question about file to be created.

from  Console
static void
parseAttributes(object $object, array $validators)

Parse array containing additional validators or attributes for FrameworkQuestion as strings along with any additional parameters that maybe expected.

from  Console
static array
buildPayload(InputInterface $input, array $overrides)

Build the per-send payload for the test command.

static list<string>
channels(string $channels)

Resolve the --channels option into a normalized list of channels.

static bool
dryRun(object|string $notifiable, Notification $notification, array $payload, array|null $channels)

Perform a dry-run (no delivery). Prints the intended action and payload.

static Users
dummy()

Return a dummy notifiable. Creates a temporary record, retrieves its data and deletes it before returning.

static Users|null
findUser(mixed $user, FrameworkQuestion $question)

Find a user/notifiable record by numeric id, email, or username.

static Users
findUserById(int $user, FrameworkQuestion $question)

Find a user/notifiable record by id. If user is not found the a prompt is presented that asks for user id.

static Users
findUserByString(string $user, FrameworkQuestion $question)

Find a user/notifiable record by email, or username. If user is not found the a prompt is presented that asks for valid email or username.

static int
makeNotification(array|null $channels, string $notificationName)

Generate a new notification class file into {self::NOTIFICATION_PATH}.

static string
migrationTemplate(string $fileName)

Template for the notifications migration class file.

static string
notificationClass(string $notificationName)

Build a fully-qualified notification class name.

static int
notificationsMigration()

Create a new notifications migration file on disk.

static string
notificationTemplate(string $classFunctions, string $notificationName)

Generate the PHP contents for a notification class.

static int
prune(int $days)

Prune old notifications using the model layer.

static array|null
resolveChannelsOverride(InputInterface $input, FrameworkQuestion $question)

Resolve a channels override list from CLI input.

static object|string
resolveNotifiable(InputInterface $input, FrameworkQuestion $question)

Resolve a notifiable instance (or a sentinel string) from CLI input.

static array
resolveOverridesFromWith(InputInterface $input, FrameworkQuestion $question)

Parse overrides from the --with option (key:value,key2:value2).

static void
sendViaNotifiable(object|string $notifiable, Notification $notification, array $payload, array|null $channels)

Deliver a notification via a notifiable (or simulate if notifiable is not an object).

static string
setViaList(array|null $channels)

Format a list of channels into PHP code suitable for a generated via() method.

static string
toDatabaseTemplate()

Template for a toDatabase() method body within a scaffolded notification.

static string
toLogTemplate()

Template for a toLog() method body within a scaffolded notification.

static string
toMailTemplate()

Template for a toMail() method body within a scaffolded notification.

static array
userParams(string $user)

Returns parameters for finding user based on E-mail or username.

static string
viaTemplate(string $channelList)

Template for the via() method within a scaffolded notification.

Details

in HasValidators at line 79
void addErrorMessage(string $message)

Adds a new error message to the $errors array.

Parameters

string $message

The error message to be added to the $errors array.

Return Value

void

in HasValidators at line 89
HasValidators alpha()

Enforce rule where input must contain only alphabetic characters.

Return Value

HasValidators

in HasValidators at line 103
HasValidators alphaNumeric()

Enforce rule where input must be alphanumeric characters.

Return Value

HasValidators

in HasValidators at line 121
HasValidators between(array $range)

Ensures input is between within a certain range in length.

Parameters

array $range

2 element array where position 0 is min and position 1 is max.

Return Value

HasValidators

Exceptions

FrameworkRuntimeException

in HasValidators at line 146
HasValidators classExists(string|array $namespace)

Checks if class exists within the specified namespace.

Parameters

string|array $namespace

A string or an array containing one element with string for the namespace.

Return Value

HasValidators

in HasValidators at line 161
HasValidators colonNotation()

Ensures response is in colon notation format.

Return Value

HasValidators

in HasValidators at line 179
HasValidators different(mixed $data)

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

Parameters

mixed $data

The value we want to compare.

Return Value

HasValidators

in HasValidators at line 194
void displayErrorMessages()

Displays a list of all error messages.

Return Value

void

in HasValidators at line 210
HasValidators dotNotation()

Ensures response is in dot notation format.

Return Value

HasValidators

in HasValidators at line 227
HasValidators email()

Ensures input is a valid E-mail address.

Return Value

HasValidators

in HasValidators at line 242
HasValidators fieldName(string|array $fieldName)

Sets name of field to be validated.

Parameters

string|array $fieldName

The name of the field to be validated.

Return Value

HasValidators

in HasValidators at line 253
HasValidators ip()

Enforce rule where input must be a valid IP address.

Return Value

HasValidators

in HasValidators at line 267
HasValidators integer()

Enforce rule where input must be an integer.

Return Value

HasValidators

in HasValidators at line 285
HasValidators isPortUsed(array $attributes)

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.

Parameters

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.

Return Value

HasValidators

in HasValidators at line 314
HasValidators list(array $attributes)

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).

Parameters

array $attributes

A : separate list in the following format: NamespaceToClass\Class:Method:Alias.

Return Value

HasValidators

in HasValidators at line 352
HasValidators lower()

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

Return Value

HasValidators

in HasValidators at line 367
HasValidators match(mixed $match)

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

Parameters

mixed $match

The value we want to compare.

Return Value

HasValidators

in HasValidators at line 382
HasValidators max(int|array $maxRule)

Ensures input meets requirements for maximum allowable length.

Parameters

int|array $maxRule

The maximum allowed size for input.

Return Value

HasValidators

in HasValidators at line 398
HasValidators min(int|array $minRule)

Ensures input meets requirements for minimum allowable length.

Parameters

int|array $minRule

The minimum allowed size for input.

Return Value

HasValidators

in HasValidators at line 413
HasValidators negative()

Enforces rule when input must be a negative number.

Return Value

HasValidators

in HasValidators at line 427
HasValidators noSpecialChars()

Enforces rule when input must contain no special characters.

Return Value

HasValidators

in HasValidators at line 441
HasValidators notReservedKeyword()

Enforce rule when reserved keywords should be avoided.

Return Value

HasValidators

in HasValidators at line 455
HasValidators number()

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

Return Value

HasValidators

in HasValidators at line 469
HasValidators numeric()

Enforce rule where input must contain only numeric characters.

Return Value

HasValidators

in HasValidators at line 483
HasValidators required()

Ensures required input is entered.

Return Value

HasValidators

in HasValidators at line 496
HasValidators positive()

Enforces rule when input must a positive number.

Return Value

HasValidators

in HasValidators at line 510
HasValidators queue()

Validates if queue exists in database or redis.

Return Value

HasValidators

in HasValidators at line 534
HasValidators setValidator(callable $validator)

Adds validator to array of validators to be used.

Parameters

callable $validator

The anonymous function for a validator.

Return Value

HasValidators

in HasValidators at line 544
HasValidators special()

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

Return Value

HasValidators

in HasValidators at line 558
HasValidators testFilterNotation()

Ensures response is in colon notation format.

Return Value

HasValidators

in HasValidators at line 579
static protected array tokens(string $data)

Split on commas (tolerate spaces), normalize to lowercase, drop empties.

Useful for cases where you have a comma separated string.

Parameters

string $data

Comma separated strings of values to be converted into an array.

Return Value

array

An array containing values originally found in comma separated string.

in HasValidators at line 589
HasValidators upper()

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

Return Value

HasValidators

in HasValidators at line 603
HasValidators url()

Enforce rule where input must be a valid URL.

Return Value

HasValidators

in HasValidators at line 619
protected bool validate(mixed $response)

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

Parameters

mixed $response

The user answer.

Return Value

bool

True if validation passed. Otherwise, we return false.

in Console at line 20
__construct(string $fieldName = "")

Creates new instance of Console class.

Parameters

string $fieldName

The name of the field to be validated.

in Console at line 42
static void argOptionValidate(string $field, string $message, FrameworkQuestion $question, array $validators = [], bool $defaultNone = false)

Validates argument and option input. If validation fails then the user is asked to enter a new value.

Validates the following conditions: 1) required 2) noSpecialChars 3) alpha 4) notReservedKeyword

Parameters

string $field

The reference to the value to be validated.

string $message

The message to present to the user.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

array $validators
bool $defaultNone

When set to true user will have to specify all validators.

Return Value

void

in Console at line 75
static mixed choice(string $message, array $choices, FrameworkQuestion $question, string|bool|int|float|null $default = null)

Ask user to confirm among several options based on question asked.

Parameters

string $message

The message to present to the user.

array $choices

An array of choices.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

string|bool|int|float|null $default

The default value if the user does not provide an answer.

Return Value

mixed

The user answer.

in Console at line 93
static mixed confirm(string $message, FrameworkQuestion $question, string|bool|int|float|null $default = true)

Asks a user to confirm based on question asked.

Parameters

string $message

The message to present to the user.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

string|bool|int|float|null $default

The default value if the user does not provide an answer.

Return Value

mixed

The user answer.

in Console at line 107
static Console getInstance(string $fieldName = "")

Returns instance of this or child helper class.

Parameters

string $fieldName

The name of the field to be validated.

Return Value

Console

in Console at line 132
static string prompt(string $message, FrameworkQuestion $question, array $attributes = [], array $suggestions = [], string|bool|int|float|null $default = null, bool $defaultNone = false)

Asks user question about file to be created.

Validates the following conditions: 1) required 2) noSpecialChars 3) alpha 4) notReservedKeyword

Parameters

string $message

The message to present to the user.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

array $attributes

An array of additional validators.

array $suggestions

An array of suggestions for when $anticipate is set to true. An exception is thrown if this array is empty and $anticipate = true.

string|bool|int|float|null $default

The default value if the user does not provide an answer.

bool $defaultNone

When set to true user will have to specify all validators and attributes.

Return Value

string

The user response.

in Console at line 167
static protected void parseAttributes(object $object, array $validators)

Parse array containing additional validators or attributes for FrameworkQuestion as strings along with any additional parameters that maybe expected.

Parameters

object $object

The instance of a class using the HasValidators trait.

array $validators

An array of validators. Any additional parameters must be separated with a ":".

Return Value

void

Exceptions

FrameworkException

at line 44
static array buildPayload(InputInterface $input, array $overrides)

Build the per-send payload for the test command.

Default fields:

  • level: "info"
  • tags: ["cli","test"]
  • dry_run: boolean (from --dry-run)

Parameters

InputInterface $input

Console input (expects option "dry-run").

array $overrides

Arbitrary key/value overrides (takes precedence).

Return Value

array

Merged payload passed to channels.

at line 64
static list<string> channels(string $channels)

Resolve the --channels option into a normalized list of channels.

Behavior:

  • If the option is omitted or empty, returns ALL enum channel values (use {\Console\Helpers\resolveChannelsOverride()} if you prefer NULL to defer to via()).
  • Accepts a comma-separated list, whitespace tolerated.
  • Accepts the special token "all" to mean all channel enum values.

Parameters

string $channels

A comma separated list of channels.

Return Value

list<string>

Normalized channel names (e.g., ['database','log']).

at line 85
static bool dryRun(object|string $notifiable, Notification $notification, array $payload, array|null $channels)

Perform a dry-run (no delivery). Prints the intended action and payload.

Parameters

object|string $notifiable

Notifiable instance or a sentinel string (e.g., "dummy").

Notification $notification

The notification instance.

array $payload

Payload merged from defaults and overrides.

array|null $channels

Channels override (NULL → will use via()).

Return Value

bool

TRUE if dry-run occurred; FALSE otherwise.

at line 116
static Users dummy()

Return a dummy notifiable. Creates a temporary record, retrieves its data and deletes it before returning.

Return Value

Users

The dummy user to be notified.

at line 139
static private Users|null findUser(mixed $user, FrameworkQuestion $question)

Find a user/notifiable record by numeric id, email, or username.

Parameters

mixed $user

String token from CLI (id|email|username).

FrameworkQuestion $question

Return Value

Users|null

The matched user or NULL if not found.

at line 154
static private Users findUserById(int $user, FrameworkQuestion $question)

Find a user/notifiable record by id. If user is not found the a prompt is presented that asks for user id.

Parameters

int $user

Token from CLI (id).

FrameworkQuestion $question

Return Value

Users

The matched user.

at line 179
static private Users findUserByString(string $user, FrameworkQuestion $question)

Find a user/notifiable record by email, or username. If user is not found the a prompt is presented that asks for valid email or username.

Parameters

string $user

String token from CLI (email|username).

FrameworkQuestion $question

Return Value

Users

The matched user.

at line 208
static int makeNotification(array|null $channels, string $notificationName)

Generate a new notification class file into {self::NOTIFICATION_PATH}.

The generated class includes channel methods (toX) for the provided list, plus a via() that references those channels. If $channels is NULL or empty, all enum channel values are used.

Parameters

array|null $channels

Channel names to scaffold (e.g., ['database','log']).

string $notificationName

Class name (without namespace).

Return Value

int

A Tools::writeFile status code.

at line 232
static string migrationTemplate(string $fileName)

Template for the notifications migration class file.

Parameters

string $fileName

The base filename/classname to use.

Return Value

string

The complete PHP contents of the migration.

at line 282
static string notificationClass(string $notificationName)

Build a fully-qualified notification class name.

Parameters

string $notificationName

Short class name or FQCN (leading backslash allowed).

Return Value

string

FQCN of the notification.

at line 293
static int notificationsMigration()

Create a new notifications migration file on disk.

Return Value

int

A Tools::writeFile status code.

at line 309
static private string notificationTemplate(string $classFunctions, string $notificationName)

Generate the PHP contents for a notification class.

Parameters

string $classFunctions

Concatenated channel method bodies + via().

string $notificationName

Class name (no namespace).

Return Value

string

Full PHP file contents for the notification class.

at line 347
static int prune(int $days)

Prune old notifications using the model layer.

Parameters

int $days

Number of days to retain; older rows are deleted.

Return Value

int

Command::SUCCESS on completion.

at line 363
static array|null resolveChannelsOverride(InputInterface $input, FrameworkQuestion $question)

Resolve a channels override list from CLI input.

If the option is omitted/empty, returns NULL so callers can defer to via().

Parameters

InputInterface $input

The Symfony InputInterface object.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

Return Value

array|null

Normalized channels or NULL to defer.

at line 388
static object|string resolveNotifiable(InputInterface $input, FrameworkQuestion $question)

Resolve a notifiable instance (or a sentinel string) from CLI input.

Parameters

InputInterface $input

The Symfony InputInterface object.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

Return Value

object|string

A model instance or "dummy" if none found/provided.

at line 404
static array resolveOverridesFromWith(InputInterface $input, FrameworkQuestion $question)

Parse overrides from the --with option (key:value,key2:value2).

Parameters

InputInterface $input

The Symfony InputInterface object.

FrameworkQuestion $question

Instance of FrameworkQuestion class.

Return Value

array

Flattened k=>v overrides.

at line 442
static void sendViaNotifiable(object|string $notifiable, Notification $notification, array $payload, array|null $channels)

Deliver a notification via a notifiable (or simulate if notifiable is not an object).

Parameters

object|string $notifiable

Notifiable instance or a sentinel string.

Notification $notification

The notification instance.

array $payload

Per-send payload/overrides.

array|null $channels

Channel override (NULL → use via()).

Return Value

void

at line 472
static private string setViaList(array|null $channels)

Format a list of channels into PHP code suitable for a generated via() method.

If the provided list is empty or equals the full enum size, returns the literal string "Notification::channelValues()" to keep the generated class concise.

Parameters

array|null $channels

Channel names to embed.

Return Value

string

PHP expression to place inside via().

at line 494
static private string toDatabaseTemplate()

Template for a toDatabase() method body within a scaffolded notification.

Return Value

string

PHP code snippet for inclusion.

at line 518
static private string toLogTemplate()

Template for a toLog() method body within a scaffolded notification.

Return Value

string

PHP code snippet for inclusion.

at line 537
static private string toMailTemplate()

Template for a toMail() method body within a scaffolded notification.

Return Value

string

PHP code snippet for inclusion.

at line 557
static private array userParams(string $user)

Returns parameters for finding user based on E-mail or username.

Parameters

string $user

The username or E-mail.

Return Value

array

An array of parameters for finding a user.

at line 569
static private string viaTemplate(string $channelList)

Template for the via() method within a scaffolded notification.

Parameters

string $channelList

PHP expression representing the channel list.

Return Value

string

PHP code snippet for inclusion.