Fr3nch13/CakePHP Utilities

Shell
in package
uses LocatorAwareTrait, LogTrait, MergeVariablesTrait, ModelAwareTrait

Base class for command-line utilities for automating programmer chores.

ShellDispatcher and Shell will be removed in 5.0

Is the equivalent of Cake\Controller\Controller on the command line.

Attributes
#[AllowDynamicProperties]

Table of Contents

Constants

CODE_ERROR  = 1
Default error code
CODE_SUCCESS  = 0
Default success code
NORMAL  = \Cake\Console\ConsoleIo::NORMAL
Output constant for making normal shells.
QUIET  = \Cake\Console\ConsoleIo::QUIET
Output constants for making quiet shells.
VERBOSE  = \Cake\Console\ConsoleIo::VERBOSE
Output constant making verbose shells.

Properties

$args  : array<string|int, mixed>
Contains arguments parsed from the command line.
$command  : string|null
The command (method/task) that is being run.
$interactive  : bool
If true, the script will ask for permission to perform actions.
$name  : string
The name of the shell in camelized.
$OptionParser  : ConsoleOptionParser
An instance of ConsoleOptionParser that has been configured for this class.
$params  : array<string|int, mixed>
Contains command switches parsed from the command line.
$plugin  : string
The name of the plugin the shell belongs to.
$taskNames  : array<string|int, string>
Contains the loaded tasks
$tasks  : array<string|int, mixed>|bool
Contains tasks to load and instantiate
$Tasks  : TaskRegistry
Task Collection for the command, used to create Tasks.
$_io  : ConsoleIo
ConsoleIo instance.
$_modelFactories  : array<string|int, callable|LocatorInterface>
A list of overridden model factory functions.
$_modelType  : string
The model type to use.
$_tableLocator  : LocatorInterface|null
Table locator instance
$_taskMap  : array<string, array<string|int, mixed>>
Normalized map of tasks.
$defaultTable  : string|null
This object's default table alias.
$modelClass  : string|null
This object's primary model class name. Should be a plural form.
$rootName  : string
The root command name used when generating help output.

Methods

__construct()  : mixed
Constructs this Shell instance.
__debugInfo()  : array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
__get()  : Shell
Overload get for lazy building of tasks
abort()  : void
Displays a formatted error message and exits the application with an error code.
clear()  : void
Clear the console
createFile()  : bool
Creates a file at given path
dispatchShell()  : int
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
err()  : int
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
fetchTable()  : Table
Convenience method to get a table instance.
getIo()  : ConsoleIo
Get the io object for this shell.
getModelType()  : string
Get the model type to be used by this class
getOptionParser()  : ConsoleOptionParser
Gets the option parser instance and configures it.
getTableLocator()  : LocatorInterface
Gets the table locator.
hasMethod()  : bool
Check to see if this shell has a callable method by the given name.
hasTask()  : bool
Check to see if this shell has a task with the provided name.
helper()  : Helper
Render a Console Helper
hr()  : void
Outputs a series of minus characters to the standard output, acts as a visual separator.
in()  : string|null
Prompts the user for input, and returns it.
info()  : int|null
Convenience method for out() that wraps message between <info /> tag
initialize()  : void
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
loadModel()  : RepositoryInterface
Loads and constructs repository objects required by this object
loadTasks()  : true
Loads tasks defined in public $tasks
log()  : bool
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
main()  : int|bool|null|void
modelFactory()  : void
Override a existing callable to generate repositories of a given type.
nl()  : string
Returns a single or multiple linefeeds sequences.
out()  : int|null
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
param()  : string|bool|null
Safely access the values in $this->params.
parseDispatchArguments()  : array<string|int, mixed>
Parses the arguments for the dispatchShell() method.
quiet()  : int|null
Output at all levels.
runCommand()  : int|bool|null
Runs the Shell with the provided argv.
setIo()  : void
Set the io object for this shell.
setModelType()  : $this
Set the model type to be used by this class
setRootName()  : $this
Set the root command name for help output.
setTableLocator()  : $this
Sets the table locator.
shortPath()  : string
Makes absolute file path easier to read
startup()  : void
Starts up the Shell and displays the welcome message.
success()  : int|null
Convenience method for out() that wraps message between <success /> tag
verbose()  : int|null
Output at the verbose level.
warn()  : int
Convenience method for err() that wraps message between <warning /> tag
wrapText()  : string
Wrap a block of text.
_displayHelp()  : int|null
Display the help in the correct format
_mergeProperty()  : void
Merge a single property with the values declared in all parent classes.
_mergePropertyData()  : array<string|int, mixed>
Merge each of the keys in a property together.
_mergeVars()  : void
Merge the list of $properties with all parent classes of the current class.
_setModelClass()  : void
Set the modelClass property based on conventions.
_setOutputLevel()  : void
Set the output level based on the parameters.
_stop()  : void
Stop execution of the current script.
_validateTasks()  : void
Checks that the tasks in the task map are actually available
_welcome()  : void
Displays a header for the shell

Constants

CODE_ERROR

Default error code

public int CODE_ERROR = 1

CODE_SUCCESS

Default success code

public int CODE_SUCCESS = 0

NORMAL

Output constant for making normal shells.

public int NORMAL = \Cake\Console\ConsoleIo::NORMAL

QUIET

Output constants for making quiet shells.

public int QUIET = \Cake\Console\ConsoleIo::QUIET

VERBOSE

Output constant making verbose shells.

public int VERBOSE = \Cake\Console\ConsoleIo::VERBOSE

Properties

$args

Contains arguments parsed from the command line.

public array<string|int, mixed> $args = []

$command

The command (method/task) that is being run.

public string|null $command

$interactive

If true, the script will ask for permission to perform actions.

public bool $interactive = true

$name

The name of the shell in camelized.

public string $name

$OptionParser

An instance of ConsoleOptionParser that has been configured for this class.

public ConsoleOptionParser $OptionParser

$params

Contains command switches parsed from the command line.

public array<string|int, mixed> $params = []

$plugin

The name of the plugin the shell belongs to.

public string $plugin

Is automatically set by ShellDispatcher when a shell is constructed.

$taskNames

Contains the loaded tasks

public array<string|int, string> $taskNames = []

$Tasks

Task Collection for the command, used to create Tasks.

public TaskRegistry $Tasks

$_modelType

The model type to use.

protected string $_modelType = 'Table'

$_taskMap

Normalized map of tasks.

protected array<string, array<string|int, mixed>> $_taskMap = []

$defaultTable

This object's default table alias.

protected string|null $defaultTable = null

$modelClass

This object's primary model class name. Should be a plural form.

Use Cake\ORM\Locator\LocatorAwareTrait::$defaultTable instead.

protected string|null $modelClass

CakePHP will not inflect the name.

Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use Plugin.Comments style names to correctly load models from the correct plugin.

Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.

$rootName

The root command name used when generating help output.

protected string $rootName = 'cake'

Methods

__debugInfo()

Returns an array that can be used to describe the internal state of this object.

public __debugInfo() : array<string, mixed>
Return values
array<string, mixed>

__get()

Overload get for lazy building of tasks

public __get(string $name) : Shell
Parameters
$name : string

The task to get.

Return values
Shell

Object of Task

dispatchShell()

Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.

public dispatchShell() : int

Usage:

With a string command:

return $this->dispatchShell('schema create DbAcl');

Avoid using this form if you have string arguments, with spaces in them. The dispatched will be invoked incorrectly. Only use this form for simple command dispatching.

With an array command:

return $this->dispatchShell('schema', 'create', 'i18n', '--dry');

With an array having two key / value pairs:

  • command can accept either a string or an array. Represents the command to dispatch
  • extra can accept an array of extra parameters to pass on to the dispatcher. This parameters will be available in the param property of the called Shell

return $this->dispatchShell([ 'command' => 'schema create DbAcl', 'extra' => ['param' => 'value'] ]);

or

return $this->dispatchShell([ 'command' => ['schema', 'create', 'DbAcl'], 'extra' => ['param' => 'value'] ]);

Tags
link
https://book.cakephp.org/4/en/console-and-shells.html#invoking-other-shells-from-your-shell
Return values
int

The CLI command exit code. 0 is success.

err()

Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.

public err(array<string|int, string>|string $message[, int $newlines = 1 ]) : int
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

Return values
int

The number of bytes returned from writing to stderr.

fetchTable()

Convenience method to get a table instance.

public fetchTable([string|null $alias = null ][, array<string, mixed> $options = [] ]) : Table
Parameters
$alias : string|null = null

The alias name you want to get. Should be in CamelCase format. If null then the value of $defaultTable property is used.

$options : array<string, mixed> = []

The options you want to build the table with. If a table has already been loaded the registry options will be ignored.

Tags
throws
CakeException

If $alias argument and $defaultTable property both are null.

see
TableLocator::get()
since
4.3.0
Return values
Table

getIo()

Get the io object for this shell.

public getIo() : ConsoleIo
Return values
ConsoleIo

The current ConsoleIo object.

getModelType()

Get the model type to be used by this class

public getModelType() : string
Return values
string

helper()

Render a Console Helper

public helper(string $name[, array<string, mixed> $config = [] ]) : Helper

Create and render the output for a helper object. If the helper object has not already been loaded, it will be loaded and constructed.

Parameters
$name : string

The name of the helper to render

$config : array<string, mixed> = []

Configuration data for the helper.

Return values
Helper

The created helper instance.

in()

Prompts the user for input, and returns it.

public in(string $prompt[, array<string|int, string>|string|null $options = null ][, string|null $default = null ]) : string|null
Parameters
$prompt : string

Prompt text.

$options : array<string|int, string>|string|null = null

Array or string of options.

$default : string|null = null

Default input value.

Tags
link
https://book.cakephp.org/4/en/console-and-shells.html#Shell::in
Return values
string|null

Either the default value, or the user-provided input.

info()

Convenience method for out() that wraps message between <info /> tag

public info(array<string|int, string>|string $message[, int $newlines = 1 ][, int $level = Shell::NORMAL ]) : int|null
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

$level : int = Shell::NORMAL

The message's output level, see above.

Tags
see
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out
Return values
int|null

The number of bytes returned from writing to stdout.

loadModel()

Loads and constructs repository objects required by this object

public loadModel([string|null $modelClass = null ][, string|null $modelType = null ]) : RepositoryInterface

Use LocatorAwareTrait::fetchTable() instead.

Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.

If a repository provider does not return an object a MissingModelException will be thrown.

Parameters
$modelClass : string|null = null

Name of model class to load. Defaults to $this->modelClass. The name can be an alias like 'Post' or FQCN like App\Model\Table\PostsTable::class.

$modelType : string|null = null

The type of repository to load. Defaults to the getModelType() value.

Tags
throws
MissingModelException

If the model class cannot be found.

throws
UnexpectedValueException

If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty.

Return values
RepositoryInterface

The model instance created.

loadTasks()

Loads tasks defined in public $tasks

public loadTasks() : true
Return values
true

log()

Convenience method to write a message to Log. See Log::write() for more information on writing to logs.

public log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
$message : string

Log message.

$level : string|int = LogLevel::ERROR

Error level.

$context : array<string|int, mixed>|string = []

Additional log data relevant to this message.

Return values
bool

Success of log write.

main()

public main([mixed ...$args = ]) : int|bool|null|void

Main entry method for the shell.

Parameters
$args : mixed =
Return values
int|bool|null|void

modelFactory()

Override a existing callable to generate repositories of a given type.

public modelFactory(string $type, LocatorInterface|callable $factory) : void
Parameters
$type : string

The name of the repository type the factory function is for.

$factory : LocatorInterface|callable

The factory function used to create instances.

out()

Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.

public out(array<string|int, string>|string $message[, int $newlines = 1 ][, int $level = Shell::NORMAL ]) : int|null

Output levels

There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE. The verbose and quiet output levels, map to the verbose and quiet output switches present in most shells. Using Shell::QUIET for a message means it will always display. While using Shell::VERBOSE means it will only display when verbose output is toggled.

Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

$level : int = Shell::NORMAL

The message's output level, see above.

Tags
link
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out
Return values
int|null

The number of bytes returned from writing to stdout.

param()

Safely access the values in $this->params.

public param(string $name) : string|bool|null
Parameters
$name : string

The name of the parameter to get.

Return values
string|bool|null

Value. Will return null if it doesn't exist.

parseDispatchArguments()

Parses the arguments for the dispatchShell() method.

public parseDispatchArguments(array<string|int, mixed> $args) : array<string|int, mixed>
Parameters
$args : array<string|int, mixed>

Arguments fetch from the dispatchShell() method with func_get_args()

Return values
array<string|int, mixed>

First value has to be an array of the command arguments. Second value has to be an array of extra parameter to pass on to the dispatcher

quiet()

Output at all levels.

public quiet(array<string|int, string>|string $message[, int $newlines = 1 ]) : int|null
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

Return values
int|null

The number of bytes returned from writing to stdout.

runCommand()

Runs the Shell with the provided argv.

public runCommand(array<string|int, mixed> $argv[, bool $autoMethod = false ][, array<string|int, mixed> $extra = [] ]) : int|bool|null

Delegates calls to Tasks and resolves methods inside the class. Commands are looked up with the following order:

  • Method on the shell.
  • Matching task name.
  • main() method.

If a shell implements a main() method, all missing method calls will be sent to main() with the original method name in the argv.

For tasks to be invoked they must be exposed as subcommands. If you define any subcommands, you must define all the subcommands your shell needs, whether they be methods on this class or methods on tasks.

Parameters
$argv : array<string|int, mixed>

Array of arguments to run the shell with. This array should be missing the shell name.

$autoMethod : bool = false

Set to true to allow any public method to be called even if it was not defined as a subcommand. This is used by ShellDispatcher to make building simple shells easy.

$extra : array<string|int, mixed> = []

Extra parameters that you can manually pass to the Shell to be dispatched. Built-in extra parameter is :

  • requested : if used, will prevent the Shell welcome message to be displayed
Tags
link
https://book.cakephp.org/4/en/console-and-shells.html#the-cakephp-console
Return values
int|bool|null

setIo()

Set the io object for this shell.

public setIo(ConsoleIo $io) : void
Parameters
$io : ConsoleIo

The ConsoleIo object to use.

setModelType()

Set the model type to be used by this class

public setModelType(string $modelType) : $this
Parameters
$modelType : string

The model type

Return values
$this

setRootName()

Set the root command name for help output.

public setRootName(string $name) : $this
Parameters
$name : string

The name of the root command.

Return values
$this

success()

Convenience method for out() that wraps message between <success /> tag

public success(array<string|int, string>|string $message[, int $newlines = 1 ][, int $level = Shell::NORMAL ]) : int|null
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

$level : int = Shell::NORMAL

The message's output level, see above.

Tags
see
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out
Return values
int|null

The number of bytes returned from writing to stdout.

verbose()

Output at the verbose level.

public verbose(array<string|int, string>|string $message[, int $newlines = 1 ]) : int|null
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

Return values
int|null

The number of bytes returned from writing to stdout.

warn()

Convenience method for err() that wraps message between <warning /> tag

public warn(array<string|int, string>|string $message[, int $newlines = 1 ]) : int
Parameters
$message : array<string|int, string>|string

A string or an array of strings to output

$newlines : int = 1

Number of newlines to append

Tags
see
https://book.cakephp.org/4/en/console-and-shells.html#Shell::err
Return values
int

The number of bytes returned from writing to stderr.

wrapText()

Wrap a block of text.

public wrapText(string $text[, array<string, mixed>|int $options = [] ]) : string

Allows you to set the width, and indenting on a block of text.

Options

  • width The width to wrap to. Defaults to 72
  • wordWrap Only wrap on words breaks (spaces) Defaults to true.
  • indent Indent the text with the string provided. Defaults to null.
Parameters
$text : string

Text the text to format.

$options : array<string, mixed>|int = []

Array of options to use, or an integer to wrap the text to.

Tags
see
Text::wrap()
link
https://book.cakephp.org/4/en/console-and-shells.html#Shell::wrapText
Return values
string

Wrapped / indented text

_displayHelp()

Display the help in the correct format

protected _displayHelp([string|null $command = null ]) : int|null
Parameters
$command : string|null = null

The command to get help for.

Return values
int|null

The number of bytes returned from writing to stdout.

_mergeProperty()

Merge a single property with the values declared in all parent classes.

protected _mergeProperty(string $property, array<string|int, string> $parentClasses, array<string, mixed> $options) : void
Parameters
$property : string

The name of the property being merged.

$parentClasses : array<string|int, string>

An array of classes you want to merge with.

$options : array<string, mixed>

Options for merging the property, see _mergeVars()

_mergePropertyData()

Merge each of the keys in a property together.

protected _mergePropertyData(array<string|int, mixed> $current, array<string|int, mixed> $parent, bool $isAssoc) : array<string|int, mixed>
Parameters
$current : array<string|int, mixed>

The current merged value.

$parent : array<string|int, mixed>

The parent class' value.

$isAssoc : bool

Whether the merging should be done in associative mode.

Return values
array<string|int, mixed>

The updated value.

_mergeVars()

Merge the list of $properties with all parent classes of the current class.

protected _mergeVars(array<string|int, string> $properties[, array<string, mixed> $options = [] ]) : void

Options:

  • associative - A list of properties that should be treated as associative arrays. Properties in this list will be passed through Hash::normalize() before merging.
Parameters
$properties : array<string|int, string>

An array of properties and the merge strategy for them.

$options : array<string, mixed> = []

The options to use when merging properties.

_setModelClass()

Set the modelClass property based on conventions.

protected _setModelClass(string $name) : void

If the property is already set it will not be overwritten

Parameters
$name : string

Class name.

_setOutputLevel()

Set the output level based on the parameters.

protected _setOutputLevel() : void

This reconfigures both the output level for out() and the configured stdout/stderr logging

_stop()

Stop execution of the current script.

protected _stop([int $status = self::CODE_SUCCESS ]) : void

Raises a StopException to try and halt the execution.

Parameters
$status : int = self::CODE_SUCCESS

see https://secure.php.net/exit for values

Tags
throws
StopException

_validateTasks()

Checks that the tasks in the task map are actually available

protected _validateTasks() : void
Tags
throws
RuntimeException

_welcome()

Displays a header for the shell

protected _welcome() : void

        
On this page

Search results