Fr3nch13/CakePHP Utilities

Debugger
in package
uses InstanceConfigTrait

Provide custom logging and error handling.

Debugger extends PHP's default error handling and gives simpler to use more powerful interfaces.

Tags
link
https://book.cakephp.org/4/en/development/debugging.html#namespace-Cake\Error

Table of Contents

Properties

$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_data  : array<string|int, mixed>
Holds current output data when outputFormat is false.
$_defaultConfig  : array<string, mixed>
Default configuration
$_outputFormat  : string
The current output format.
$_templates  : array<string, array<string, mixed>>
Templates used when generating trace or error strings. Can be global or indexed by the format value used in $_outputFormat.
$editors  : array<string, string|callable>
A map of editors to their link templates.
$renderers  : array<string, class-string>
Mapping for error renderers.

Methods

__construct()  : mixed
Constructor.
addEditor()  : void
Add an editor link format
addFormat()  : array<string|int, mixed>
Add an output format or update a format in Debugger.
addRenderer()  : void
Add a renderer to the current instance.
checkSecurityKeys()  : void
Verifies that the application's salt and cipher seed value has been changed from the default value.
configInstance()  : mixed
Read or write configuration options for the Debugger instance.
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
dump()  : void
Recursively formats and outputs the contents of the supplied variable.
editorUrl()  : string
Get a formatted URL for the active editor.
excerpt()  : array<string|int, string>
Grabs an excerpt from a file and highlights a given line of code.
exportVar()  : string
Converts a variable to a string for debug output.
exportVarAsNodes()  : NodeInterface
Convert the variable to the internal node tree.
exportVarAsPlainText()  : string
Converts a variable to a plain text string.
formatHtmlMessage()  : string
Format an exception message to be HTML formatted.
formatTrace()  : array<string|int, mixed>|string
Formats a stack trace based on the supplied options.
getConfig()  : mixed
Returns the config.
getConfigOrFail()  : mixed
Returns the config for this specific key.
getExportFormatter()  : FormatterInterface
Get the configured export formatter or infer one based on the environment.
getInstance()  : static
Returns a reference to the Debugger singleton object instance.
getOutputFormat()  : string
Get the output format for Debugger error rendering.
getType()  : string
Get the type of the given variable. Will return the class name for objects.
log()  : void
Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
outputError()  : void
Takes a processed array of data from an error and displays it in the chosen format.
outputMask()  : array<string, string>
Reads the current output masking.
printVar()  : void
Prints out debug information about given variable.
setConfig()  : $this
Sets the config.
setEditor()  : void
Choose the editor link style you want to use.
setOutputFormat()  : void
Set the output format for Debugger error rendering.
setOutputMask()  : void
Sets configurable masking of debugger output by property name and array key names.
trace()  : array<string|int, mixed>|string
Outputs a stack trace based on the supplied options.
trimPath()  : string
Shortens file paths by replacing the application base path with 'APP', and the CakePHP core path with 'CORE'.
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
_highlight()  : string
Wraps the highlight_string function in case the server API does not implement the function as it is the case of the HipHop interpreter
export()  : NodeInterface
Protected export function used to keep track of indentation and recursion.
exportArray()  : ArrayNode
Export an array type object. Filters out keys used in datasource configuration.
exportObject()  : NodeInterface
Handles object to node conversion.

Properties

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_data

Holds current output data when outputFormat is false.

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

$_defaultConfig

Default configuration

protected array<string, mixed> $_defaultConfig = ['outputMask' => [], 'exportFormatter' => null, 'editor' => 'phpstorm']

$_outputFormat

The current output format.

protected string $_outputFormat = 'js'

$_templates

Templates used when generating trace or error strings. Can be global or indexed by the format value used in $_outputFormat.

protected array<string, array<string, mixed>> $_templates = ['log' => [ // These templates are not actually used, as Debugger::log() is called instead. 'trace' => '{:reference} - {:path}, line {:line}', 'error' => '{:error} ({:code}): {:description} in [{:file}, line {:line}]', ], 'js' => ['error' => '', 'info' => '', 'trace' => '<pre class="stack-trace">{:trace}</pre>', 'code' => '', 'context' => '', 'links' => [], 'escapeContext' => true], 'html' => ['trace' => '<pre class="cake-error trace"><b>Trace</b> <p>{:trace}</p></pre>', 'context' => '<pre class="cake-error context"><b>Context</b> <p>{:context}</p></pre>', 'escapeContext' => true], 'txt' => ['error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}", 'code' => '', 'info' => ''], 'base' => ['traceLine' => '{:reference} - {:path}, line {:line}', 'trace' => "Trace:\n{:trace}\n", 'context' => "Context:\n{:context}\n"]]

$editors

A map of editors to their link templates.

protected array<string, string|callable> $editors = ['atom' => 'atom://core/open/file?filename={file}&line={line}', 'emacs' => 'emacs://open?url=file://{file}&line={line}', 'macvim' => 'mvim://open/?url=file://{file}&line={line}', 'phpstorm' => 'phpstorm://open?file={file}&line={line}', 'sublime' => 'subl://open?url=file://{file}&line={line}', 'textmate' => 'txmt://open?url=file://{file}&line={line}', 'vscode' => 'vscode://file/{file}:{line}']

$renderers

Mapping for error renderers.

protected array<string, class-string> $renderers = [ 'txt' => \Cake\Error\Renderer\TextErrorRenderer::class, // The html alias currently uses no JS and will be deprecated. 'js' => \Cake\Error\Renderer\HtmlErrorRenderer::class, ]

Error renderers are replacing output formatting with an object based system. Having Debugger handle and render errors will be deprecated and the new ErrorTrap system should be used instead.

Methods

__construct()

Constructor.

public __construct() : mixed

addEditor()

Add an editor link format

public static addEditor(string $name, Closure|string $template) : void

Template strings can use the {file} and {line} placeholders. Closures templates must return a string, and accept two parameters: The file and line.

Parameters
$name : string

The name of the editor.

$template : Closure|string

The string template or closure

addFormat()

Add an output format or update a format in Debugger.

public static addFormat(string $format, array<string|int, mixed> $strings) : array<string|int, mixed>

Update your application so use ErrorTrap instead.

Debugger::addFormat('custom', $data);

Where $data is an array of strings that use Text::insert() variable replacement. The template vars should be in a {:id} style. An error formatter can have the following keys:

  • 'error' - Used for the container for the error message. Gets the following template variables: id, error, code, description, path, line, links, info
  • 'info' - A combination of code, context and trace. Will be set with the contents of the other template keys.
  • 'trace' - The container for a stack trace. Gets the following template variables: trace
  • 'context' - The container element for the context variables. Gets the following templates: id, context
  • 'links' - An array of HTML links that are used for creating links to other resources. Typically this is used to create javascript links to open other sections. Link keys, are: code, context, help. See the JS output format for an example.
  • 'traceLine' - Used for creating lines in the stacktrace. Gets the following template variables: reference, path, line

Alternatively if you want to use a custom callback to do all the formatting, you can use the callback key, and provide a callable:

Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']];

The callback can expect two parameters. The first is an array of all the error data. The second contains the formatted strings generated using the other template strings. Keys like info, links, code, context and trace will be present depending on the other templates in the format type.

Parameters
$format : string

Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for straight HTML output, or 'txt' for unformatted text.

$strings : array<string|int, mixed>

Template strings, or a callback to be used for the output format.

Return values
array<string|int, mixed>

The resulting format string set.

addRenderer()

Add a renderer to the current instance.

public static addRenderer(string $name, ErrorRendererInterface> $class) : void

Update your application so use ErrorTrap instead.

Parameters
$name : string

The alias for the the renderer.

$class : ErrorRendererInterface>

The classname of the renderer to use.

checkSecurityKeys()

Verifies that the application's salt and cipher seed value has been changed from the default value.

public static checkSecurityKeys() : void

configInstance()

Read or write configuration options for the Debugger instance.

public static configInstance([array<string, mixed>|string|null $key = null ][, mixed|null $value = null ][, bool $merge = true ]) : mixed
Parameters
$key : array<string, mixed>|string|null = null

The key to get/set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
mixed

Config value being read, or the object itself on write operations.

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

Return values
$this

editorUrl()

Get a formatted URL for the active editor.

public static editorUrl(string $file, int $line) : string
Parameters
$file : string

The file to create a link for.

$line : int

The line number to create a link for.

Return values
string

The formatted URL.

excerpt()

Grabs an excerpt from a file and highlights a given line of code.

public static excerpt(string $file, int $line[, int $context = 2 ]) : array<string|int, string>

Usage:

Debugger::excerpt('/path/to/file', 100, 4);

The above would return an array of 8 items. The 4th item would be the provided line, and would be wrapped in <span class="code-highlight"></span>. All the lines are processed with highlight_string() as well, so they have basic PHP syntax highlighting applied.

Parameters
$file : string

Absolute path to a PHP file.

$line : int

Line number to highlight.

$context : int = 2

Number of lines of context to extract above and below $line.

Tags
see
https://secure.php.net/highlight_string
link
https://book.cakephp.org/4/en/development/debugging.html#getting-an-excerpt-from-a-file
Return values
array<string|int, string>

Set of lines highlighted

exportVar()

Converts a variable to a string for debug output.

public static exportVar(mixed $var[, int $maxDepth = 3 ]) : string

Note: The following keys will have their contents replaced with *****:

  • password
  • login
  • host
  • database
  • port
  • prefix
  • schema

This is done to protect database credentials, which could be accidentally shown in an error message if CakePHP is deployed in development mode.

Parameters
$var : mixed

Variable to convert.

$maxDepth : int = 3

The depth to output to. Defaults to 3.

Return values
string

Variable as a formatted string

exportVarAsNodes()

Convert the variable to the internal node tree.

public static exportVarAsNodes(mixed $var[, int $maxDepth = 3 ]) : NodeInterface

The node tree can be manipulated and serialized more easily than many object graphs can.

Parameters
$var : mixed

Variable to convert.

$maxDepth : int = 3

The depth to generate nodes to. Defaults to 3.

Return values
NodeInterface

The root node of the tree.

exportVarAsPlainText()

Converts a variable to a plain text string.

public static exportVarAsPlainText(mixed $var[, int $maxDepth = 3 ]) : string
Parameters
$var : mixed

Variable to convert.

$maxDepth : int = 3

The depth to output to. Defaults to 3.

Return values
string

Variable as a string

formatHtmlMessage()

Format an exception message to be HTML formatted.

public static formatHtmlMessage(string $message) : string

Does the following formatting operations:

  • HTML escape the message.
  • Convert bool into <code>bool</code>
  • Convert newlines into <br />
Parameters
$message : string

The string message to format.

Return values
string

Formatted message.

formatTrace()

Formats a stack trace based on the supplied options.

public static formatTrace(Throwable|array<string|int, mixed> $backtrace[, array<string, mixed> $options = [] ]) : array<string|int, mixed>|string

Options

  • depth - The number of stack frames to return. Defaults to 999
  • format - The format you want the return. Defaults to the currently selected format. If format is 'array' or 'points' the return will be an array.
  • args - Should arguments for functions be shown? If true, the arguments for each method call will be displayed.
  • start - The stack frame to start generating a trace from. Defaults to 0
Parameters
$backtrace : Throwable|array<string|int, mixed>

Trace as array or an exception object.

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

Format for outputting stack trace.

Tags
link
https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
Return values
array<string|int, mixed>|string

Formatted stack trace.

getConfig()

Returns the config.

public getConfig([string|null $key = null ][, mixed $default = null ]) : mixed

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');
Parameters
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Return values
mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

getExportFormatter()

Get the configured export formatter or infer one based on the environment.

public getExportFormatter() : FormatterInterface
Tags
unstable

This method is not stable and may change in the future.

since
4.1.0
Return values
FormatterInterface

getInstance()

Returns a reference to the Debugger singleton object instance.

public static getInstance([string|null $class = null ]) : static
Parameters
$class : string|null = null

Class name.

Return values
static

getOutputFormat()

Get the output format for Debugger error rendering.

public static getOutputFormat() : string

Update your application so use ErrorTrap instead.

Return values
string

Returns the current format when getting.

getType()

Get the type of the given variable. Will return the class name for objects.

public static getType(mixed $var) : string
Parameters
$var : mixed

The variable to get the type of.

Return values
string

The type of variable.

log()

Creates an entry in the log file. The log entry will contain a stack trace from where it was called.

public static log(mixed $var[, string|int $level = 'debug' ][, int $maxDepth = 3 ]) : void

as well as export the variable using exportVar. By default, the log is written to the debug log.

Parameters
$var : mixed

Variable or content to log.

$level : string|int = 'debug'

Type of log to use. Defaults to 'debug'.

$maxDepth : int = 3

The depth to output to. Defaults to 3.

outputError()

Takes a processed array of data from an error and displays it in the chosen format.

public outputError(array<string|int, mixed> $data) : void

Update your application so use ErrorTrap instead.

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

Data to output.

outputMask()

Reads the current output masking.

public static outputMask() : array<string, string>
Return values
array<string, string>

printVar()

Prints out debug information about given variable.

public static printVar(mixed $var[, array<string|int, mixed> $location = [] ][, bool|null $showHtml = null ]) : void
Parameters
$var : mixed

Variable to show debug information for.

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

If contains keys "file" and "line" their values will be used to show location info.

$showHtml : bool|null = null

If set to true, the method prints the debug data encoded as HTML. If false, plain text formatting will be used. If null, the format will be chosen based on the configured exportFormatter, or environment conditions.

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

setEditor()

Choose the editor link style you want to use.

public static setEditor(string $name) : void
Parameters
$name : string

The editor name.

setOutputFormat()

Set the output format for Debugger error rendering.

public static setOutputFormat(string $format) : void

Update your application so use ErrorTrap instead.

Parameters
$format : string

The format you want errors to be output as.

Tags
throws
InvalidArgumentException

When choosing a format that doesn't exist.

setOutputMask()

Sets configurable masking of debugger output by property name and array key names.

public static setOutputMask(array<string, string> $value[, bool $merge = true ]) : void

Example

Debugger::setOutputMask(['password' => '[*************]');

Parameters
$value : array<string, string>

An array where keys are replaced by their values in output.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

trace()

Outputs a stack trace based on the supplied options.

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

Options

  • depth - The number of stack frames to return. Defaults to 999
  • format - The format you want the return. Defaults to the currently selected format. If format is 'array' or 'points' the return will be an array.
  • args - Should arguments for functions be shown? If true, the arguments for each method call will be displayed.
  • start - The stack frame to start generating a trace from. Defaults to 0
Parameters
$options : array<string, mixed> = []

Format for outputting stack trace.

Tags
link
https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
Return values
array<string|int, mixed>|string

Formatted stack trace.

trimPath()

Shortens file paths by replacing the application base path with 'APP', and the CakePHP core path with 'CORE'.

public static trimPath(string $path) : string
Parameters
$path : string

Path to shorten.

Return values
string

Normalized path

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Tags
throws
CakeException

if attempting to clobber existing config

_highlight()

Wraps the highlight_string function in case the server API does not implement the function as it is the case of the HipHop interpreter

protected static _highlight(string $str) : string
Parameters
$str : string

The string to convert.

Return values
string

export()

Protected export function used to keep track of indentation and recursion.

protected static export(mixed $var, DebugContext $context) : NodeInterface
Parameters
$var : mixed

The variable to dump.

$context : DebugContext

Dump context

Return values
NodeInterface

The dumped variable.

exportArray()

Export an array type object. Filters out keys used in datasource configuration.

protected static exportArray(array<string|int, mixed> $var, DebugContext $context) : ArrayNode

The following keys are replaced with ***'s

  • password
  • login
  • host
  • database
  • port
  • prefix
  • schema
Parameters
$var : array<string|int, mixed>

The array to export.

$context : DebugContext

The current dump context.

Return values
ArrayNode

Exported array.

exportObject()

Handles object to node conversion.

protected static exportObject(object $var, DebugContext $context) : NodeInterface
Parameters
$var : object

Object to convert.

$context : DebugContext

The dump context.

Tags
see
Debugger::exportVar()
Return values
NodeInterface

        
On this page

Search results