public function getXMLFromResult(ResultInterface $query, array $params = []): string
	{
		// Set our default values
		foreach (['root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t"] as $key => $val)
		{
			if (! isset($params[$key]))
			{
				$params[$key] = $val;
			}
		}

		// Create variables for convenience
		extract($params);

		// Load the xml helper
		helper('xml');
		// Generate the result
		$xml = '<' . $root . '>' . $newline;
		while ($row = $query->getUnbufferedRow())
		{
			$xml .= $tab . '<' . $element . '>' . $newline;
			foreach ($row as $key => $val)
			{
				$val = (!empty($val)) ? xml_convert($val) : '';
				$xml .= $tab . $tab . '<' . $key . '>' . $val . '</' . $key . '>' . $newline;
			}
			$xml .= $tab . '</' . $element . '>' . $newline;
		}

		return $xml . '</' . $root . '>' . $newline;
	}

public
function
getXMLFromResult
(
ResultInterface
$
query
,
array
$
params
=
[
]
)
:
string
{
// Set our default values
foreach
(
[
'root'
=>
'root'
,
'element'
=>
'element'
,
'newline'
=>
"\n"
,
'tab'
=>
"\t"
]
as
$
key
=>
$
val
)
{
if
(
!
isset
(
$
params
[
$
key
]
)
)
{
$
params
[
$
key
]
=
$
val
;
}
}
// Create variables for convenience
extract
(
$
params
)
;
// Load the xml helper
helper
(
'xml'
)
;
// Generate the result
$
xml
=
'<'
.
$
root
.
'>'
.
$
newline
;
while
(
$
row
=
$
query
->
getUnbufferedRow
(
)
)
{
$
xml
.=
$
tab
.
'<'
.
$
element
.
'>'
.
$
newline
;
foreach
(
$
row
as
$
key
=>
$
val
)
{
$
val
=
(
!
empty
(
$
val
)
)
xml_convert
(
$
val
)
:
''
;
$
xml
.=
$
tab
.
$
tab
.
'<'
.
$
key
.
'>'
.
$
val
.
'</'
.
$
key
.
'>'
.
$
newline
;
}
$
xml
.=
$
tab
.
'</'
.
$
element
.
'>'
.
$
newline
;
}
return
$
xml
.
'</'
.
$
root
.
'>'
.
$
newline
;
}

Generate XML data from a query result object

@param ResultInterface $query  Query result object
@param array           $params Any preferences

@return string


protected function call(string $command, array $params = [])
	{
		// The CommandRunner will grab the first element
		// for the command name.
		array_unshift($params, $command);

		return $this->commands->index($params);
	}

Can be used by a command to run other commands.

@param string $command
@param array  $params

@return mixed
@throws \ReflectionException

Can be used by a command to run other commands .


public function call(string $class)
	{
		if (empty($class))
		{
			throw new \InvalidArgumentException('No Seeder was specified.');
		}

		$path = str_replace('.php', '', $class) . '.php';

		// If we have namespaced class, simply try to load it.
		if (strpos($class, '\\') !== false)
		{
			$seeder = new $class($this->config);
		}
		// Otherwise, try to load the class manually.
		else
		{
			$path = $this->seedPath . $path;

			if (! is_file($path))
			{
				throw new \InvalidArgumentException('The specified Seeder is not a valid file: ' . $path);
			}

			// Assume the class has the correct namespace
			$class = APP_NAMESPACE . '\Database\Seeds\\' . $class;

			if (! class_exists($class, false))
			{
				require_once $path;
			}

			$seeder = new $class($this->config);
		}

		$seeder->run();

		unset($seeder);

		if (is_cli() && ! $this->silent)
		{
			CLI::write("Seeded: {$class}", 'green');
		}
	}

Loads the specified seeder and runs it.

@param string $class

@throws \InvalidArgumentException

Loads the specified seeder and runs it .


public function in_list(string $value = null, string $list, array $data): bool
	{
		$list = explode(',', $list);
		$list = array_map(function ($value) {
			return trim($value);
		}, $list);
		return in_array($value, $list, true);
	}

public function in_list ( string $ value = null , string $ list , array $ data ) : bool { $ list = explode ( ',' , $ list ) ; $ list = array_map ( function ( $ value ) { return trim ( $ value ) ; } , $ list ) ; return in_array ( $ value , $ list , true ) ; }

Value should be within an array of values

@param  string $value
@param  string $list
@param  array  $data
@return boolean


public function less_than_equal_to(string $str = null, string $max): bool
	{
		return is_numeric($str) ? ($str <= $max) : false;
	}

public function less_than_equal_to ( string $ str = null , string $ max ) : bool { return is_numeric ( $ str ) ? ( $ str <= $ max ) : false ; }

Equal to or Less than

@param string $str
@param string $max

@return boolean


public function required_with($str = null, string $fields, array $data): bool
	{
		$fields = explode(',', $fields);

		// If the field is present we can safely assume that
		// the field is here, no matter whether the corresponding
		// search field is present or not.
		$present = $this->required($str ?? '');

		if ($present)
		{
			return true;
		}

		// Still here? Then we fail this test if
		// any of the fields are present in $data
		// as $fields is the lis
		$requiredFields = [];

		foreach ($fields as $field)
		{
			if (array_key_exists($field, $data))
			{
				$requiredFields[] = $field;
			}
		}

		// Remove any keys with empty values since, that means they
		// weren't truly there, as far as this is concerned.
		$requiredFields = array_filter($requiredFields, function ($item) use ($data) {
			return ! empty($data[$item]);
		});

		return empty($requiredFields);
	}

The field is required when any of the other required fields are present
in the data.

Example (field is required when the password field is present):

required_with[password]

@param $str
@param string $fields List of fields that we should check if present
@param array  $data   Complete list of fields from the form

@return boolean

The field is required when any of the other required fields are present in the data .


public function required_without($str = null, string $fields, array $data): bool
	{
		$fields = explode(',', $fields);

		// If the field is present we can safely assume that
		// the field is here, no matter whether the corresponding
		// search field is present or not.
		$present = $this->required($str ?? '');

		if ($present)
		{
			return true;
		}

		// Still here? Then we fail this test if
		// any of the fields are not present in $data
		foreach ($fields as $field)
		{
			if (! array_key_exists($field, $data))
			{
				return false;
			}
		}

		return true;
	}

The field is required when all of the other fields are present
in the data but not required.

Example (field is required when the id or email field is missing):

required_without[id,email]

@param $str
@param string $fields
@param array  $data

@return boolean

The field is required when all of the other fields are present in the data but not required .


protected function validateRequest(array $segments): array
	{
		$segments = array_filter($segments);
		$segments = array_values($segments);

		$c                  = count($segments);
		$directory_override = isset($this->directory);

		// Loop through our segments and return as soon as a controller
		// is found or when such a directory doesn't exist
		while ($c -- > 0)
		{
			$test = $this->directory . ucfirst($this->translateURIDashes === true ? str_replace('-', '_', $segments[0]) : $segments[0]
			);

			if (! is_file(APPPATH . 'Controllers/' . $test . '.php') && $directory_override === false && is_dir(APPPATH . 'Controllers/' . $this->directory . ucfirst($segments[0])))
			{
				$this->setDirectory(array_shift($segments), true);
				continue;
			}

			return $segments;
		}

		// This means that all segments were actually directories
		return $segments;
	}

Attempts to validate the URI request and determine the controller path.

@param array $segments URI segments

@return array URI segments

Attempts to validate the URI request and determine the controller path .


protected function setDirectory(string $dir = null, bool $append = false)
	{
		$dir = ucfirst($dir);

		if ($append !== true || empty($this->directory))
		{
			$this->directory = str_replace('.', '', trim($dir, '/')) . '/';
		}
		else
		{
			$this->directory .= str_replace('.', '', trim($dir, '/')) . '/';
		}
	}

protected function setDirectory ( string $ dir = null , bool $ append = false ) { $ dir = ucfirst ( $ dir ) ; if ( $ append !== true || empty ( $ this -> directory ) ) { $ this -> directory = str_replace ( '.' , '' , trim ( $ dir , '/' ) ) . '/' ; } else { $ this -> directory .= str_replace ( '.' , '' , trim ( $ dir , '/' ) ) . '/' ; } }

Sets the sub-directory that the controller is in.

@param string|null   $dir
@param boolean|false $append

Sets the sub - directory that the controller is in .


protected function setRequest(array $segments = [])
	{
		// If we don't have any segments - try the default controller;
		if (empty($segments))
		{
			$this->setDefaultController();

			return;
		}

		list($controller, $method) = array_pad(explode('::', $segments[0]), 2, null);

		$this->controller = $controller;

		// $this->method already contains the default method name,
		// so don't overwrite it with emptiness.
		if (! empty($method))
		{
			$this->method = $method;
		}

		array_shift($segments);

		$this->params = $segments;
	}

Set request route

Takes an array of URI segments as input and sets the class/method
to be called.

@param array $segments URI segments


protected function setDefaultController()
	{
		if (empty($this->controller))
		{
			throw RouterException::forMissingDefaultRoute();
		}

		// Is the method being specified?
		if (sscanf($this->controller, '%[^/]/%s', $class, $this->method) !== 2)
		{
			$this->method = 'index';
		}

		if (! is_file(APPPATH . 'Controllers/' . $this->directory . ucfirst($class) . '.php'))
		{
			return;
		}

		$this->controller = ucfirst($class);

		log_message('info', 'Used the default controller.');
	}

protected
function
setDefaultController
(
)
{
if
(
empty
(
$
this
->
controller
)
)
{
throw
RouterException
::
forMissingDefaultRoute
(
)
;
}
// Is the method being specified?
if
(
sscanf
(
$
this
->
controller
,
'%[^/]/%s'
,
$
class
,
$
this
->
method
)
!==
2
)
{
$
this
->
method
=
'index'
;
}
if
(
!
is_file
(
APPPATH
.
'Controllers/'
.
$
this
->
directory
.
ucfirst
(
$
class
)
.
'.php'
)
)
{
return
;
}
$
this
->
controller
=
ucfirst
(
$
class
)
;
log_message
(
'info'
,
'Used the default controller.'
)
;
}

Sets the default controller based on the info set in the RouteCollection.

Sets the default controller based on the info set in the RouteCollection .


public function getSize(string $unit = 'b')
	{
		if (is_null($this->size))
		{
			$this->size = filesize($this->getPathname());
		}

		switch (strtolower($unit))
		{
			case 'kb':
				return number_format($this->size / 1024, 3);
			case 'mb':
				return number_format(($this->size / 1024) / 1024, 3);
		}

		return (int) $this->size;
	}

public function getSize ( string $ unit = 'b' ) { if ( is_null ( $ this -> size ) ) { $ this -> size = filesize ( $ this -> getPathname ( ) ) ; } switch ( strtolower ( $ unit ) ) { case 'kb' : return number_format ( $ this -> size / 1024 , 3 ) ; case 'mb' : return number_format ( ( $ this -> size / 1024 ) / 1024 , 3 ) ; } return ( int ) $ this -> size ; }

Retrieve the file size.

Implementations SHOULD return the value stored in the "size" key of
the file in the $_FILES array if available, as PHP calculates this based
on the actual size transmitted.

@param string $unit The unit to return:
- b   Bytes
- kb  Kilobytes
- mb  Megabytes

@return integer|null The file size in bytes or null if unknown.


public function move(string $targetPath, string $name = null, bool $overwrite = false)
	{
		$targetPath  = rtrim($targetPath, '/') . '/';
		$name        = $name ?? $this->getBaseName();
		$destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name);

		$oldName = empty($this->getRealPath()) ? $this->getPath() : $this->getRealPath();

		if (! @rename($oldName, $destination))
		{
			$error = error_get_last();
			throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message']));
		}

		@chmod($targetPath, 0777 & ~umask());

		return new File($destination);
	}

public function move ( string $ targetPath , string $ name = null , bool $ overwrite = false ) { $ targetPath = rtrim ( $ targetPath , '/' ) . '/' ; $ name = $ name ?? $ this -> getBaseName ( ) ; $ destination = $ overwrite ? $ targetPath . $ name : $ this -> getDestination ( $ targetPath . $ name ) ; $ oldName = empty ( $ this -> getRealPath ( ) ) ? $ this -> getPath ( ) : $ this -> getRealPath ( ) ; if ( ! @ rename ( $ oldName , $ destination ) ) { $ error = error_get_last ( ) ; throw FileException :: forUnableToMove ( $ this -> getBasename ( ) , $ targetPath , strip_tags ( $ error [ 'message' ] ) ) ; } @ chmod ( $ targetPath , 0777 & ~ umask ( ) ) ; return new File ( $ destination ) ; }

Moves a file to a new location.

@param string      $targetPath
@param string|null $name
@param boolean     $overwrite

@return \CodeIgniter\Files\File


public function getDestination(string $destination, string $delimiter = '_', int $i = 0): string
	{
		while (is_file($destination))
		{
			$info = pathinfo($destination);
			if (strpos($info['filename'], $delimiter) !== false)
			{
				$parts = explode($delimiter, $info['filename']);
				if (is_numeric(end($parts)))
				{
					$i = end($parts);
					array_pop($parts);
					array_push($parts, ++ $i);
					$destination = $info['dirname'] . '/' . implode($delimiter, $parts) . '.' . $info['extension'];
				}
				else
				{
					$destination = $info['dirname'] . '/' . $info['filename'] . $delimiter . ++ $i . '.' . $info['extension'];
				}
			}
			else
			{
				$destination = $info['dirname'] . '/' . $info['filename'] . $delimiter . ++ $i . '.' . $info['extension'];
			}
		}
		return $destination;
	}

public function getDestination ( string $ destination , string $ delimiter = '_' , int $ i = 0 ) : string { while ( is_file ( $ destination ) ) { $ info = pathinfo ( $ destination ) ; if ( strpos ( $ info [ 'filename' ] , $ delimiter ) !== false ) { $ parts = explode ( $ delimiter , $ info [ 'filename' ] ) ; if ( is_numeric ( end ( $ parts ) ) ) { $ i = end ( $ parts ) ; array_pop ( $ parts ) ; array_push ( $ parts , ++ $ i ) ; $ destination = $ info [ 'dirname' ] . '/' . implode ( $ delimiter , $ parts ) . '.' . $ info [ 'extension' ] ; } else { $ destination = $ info [ 'dirname' ] . '/' . $ info [ 'filename' ] . $ delimiter . ++ $ i . '.' . $ info [ 'extension' ] ; } } else { $ destination = $ info [ 'dirname' ] . '/' . $ info [ 'filename' ] . $ delimiter . ++ $ i . '.' . $ info [ 'extension' ] ; } } return $ destination ; }

Returns the destination path for the move operation where overwriting is not expected.

First, it checks whether the delimiter is present in the filename, if it is, then it checks whether the
last element is an integer as there may be cases that the delimiter may be present in the filename.
For the all other cases, it appends an integer starting from zero before the file's extension.

@param string  $destination
@param string  $delimiter
@param integer $i

@return string

Returns the destination path for the move operation where overwriting is not expected .


public static function collect(Query $query)
	{
		$config = config('Toolbar');

		// Provide default in case it's not set
		$max = $config->maxQueries ?: 100;

		if (count(static::$queries) < $max)
		{
			static::$queries[] = $query;
		}
	}

public
static
function
collect
(
Query
$
query
)
{
$
config
=
config
(
'Toolbar'
)
;
// Provide default in case it's not set
$
max
=
$
config
->
maxQueries
:
100
;
if
(
count
(
static
::
$
queries
)
<
$
max
)
{
static
::
$
queries
[
]
=
$
query
;
}
}

The static method used during Events to collect
data.

@param \CodeIgniter\Database\Query $query

@internal param $ array \CodeIgniter\Database\Query

The static method used during Events to collect data .


protected function formatTimelineData(): array
	{
		$data = [];

		foreach ($this->connections as $alias => $connection)
		{
			// Connection Time
			$data[] = [
				'name'      => 'Connecting to Database: "' . $alias . '"',
				'component' => 'Database',
				'start'     => $connection->getConnectStart(),
				'duration'  => $connection->getConnectDuration(),
			];
		}

		foreach (static::$queries as $query)
		{
			$data[] = [
				'name'      => 'Query',
				'component' => 'Database',
				'start'     => $query->getStartTime(true),
				'duration'  => $query->getDuration(),
			];
		}

		return $data;
	}

protected
function
formatTimelineData
(
)
:
array
{
$
data
=
[
]
;
foreach
(
$
this
->
connections
as
$
alias
=>
$
connection
)
{
// Connection Time
$
data
[
]
=
[
'name'
=>
'Connecting to Database: "'
.
$
alias
.
'"'
,
'component'
=>
'Database'
,
'start'
=>
$
connection
->
getConnectStart
(
)
,
'duration'
=>
$
connection
->
getConnectDuration
(
)
,
]
;
}
foreach
(
static
::
$
queries
as
$
query
)
{
$
data
[
]
=
[
'name'
=>
'Query'
,
'component'
=>
'Database'
,
'start'
=>
$
query
->
getStartTime
(
true
)
,
'duration'
=>
$
query
->
getDuration
(
)
,
]
;
}
return
$
data
;
}

Returns timeline data formatted for the toolbar.

@return array The formatted data or an empty array.

Returns timeline data formatted for the toolbar .


public function locateFile(string $file, string $folder = null, string $ext = 'php')
	{
		$file = $this->ensureExt($file, $ext);

		// Clears the folder name if it is at the beginning of the filename
		if (! empty($folder) && ($pos = strpos($file, $folder)) === 0)
		{
			$file = substr($file, strlen($folder . '/'));
		}

		// Is not namespaced? Try the application folder.
		if (strpos($file, '\\') === false)
		{
			return $this->legacyLocate($file, $folder);
		}

		// Standardize slashes to handle nested directories.
		$file = strtr($file, '/', '\\');

		$segments = explode('\\', $file);

		// The first segment will be empty if a slash started the filename.
		if (empty($segments[0]))
		{
			unset($segments[0]);
		}

		$path     = '';
		$prefix   = '';
		$filename = '';

		// Namespaces always comes with arrays of paths
		$namespaces = $this->autoloader->getNamespace();

		while (! empty($segments))
		{
			$prefix .= empty($prefix)
				? ucfirst(array_shift($segments))
				: '\\' . ucfirst(array_shift($segments));

			if (empty($namespaces[$prefix]))
			{
				continue;
			}
			$path = $this->getNamespaces($prefix);

			$filename = implode('/', $segments);
			break;
		}

		// IF we have a folder name, then the calling function
		// expects this file to be within that folder, like 'Views',
		// or 'libraries'.
		if (! empty($folder) && strpos($path . $filename, '/' . $folder . '/') === false)
		{
			$filename = $folder . '/' . $filename;
		}

		$path .= $filename;

		return is_file($path) ? $path : false;
	}

Attempts to locate a file by examining the name for a namespace
and looking through the PSR-4 namespaced files that we know about.

@param string $file   The namespaced file to locate
@param string $folder The folder within the namespace that we should look for the file.
@param string $ext    The file extension the file should have.

@return string|false The path to the file, or false if not found.

Attempts to locate a file by examining the name for a namespace and looking through the PSR - 4 namespaced files that we know about .


public function getClassname(string $file) : string
	{
		$php        = file_get_contents($file);
		$tokens     = token_get_all($php);
		$count      = count($tokens);
		$dlm        = false;
		$namespace  = '';
		$class_name = '';

		for ($i = 2; $i < $count; $i++)
		{
			if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $tokens[$i][0] === T_STRING))
			{
				if (! $dlm)
				{
					$namespace = 0;
				}
				if (isset($tokens[$i][1]))
				{
					$namespace = $namespace ? $namespace . '\\' . $tokens[$i][1] : $tokens[$i][1];
					$dlm       = true;
				}
			}
			elseif ($dlm && ($tokens[$i][0] !== T_NS_SEPARATOR) && ($tokens[$i][0] !== T_STRING))
			{
				$dlm = false;
			}
			if (($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass'))
				&& $tokens[$i - 1][0] === T_WHITESPACE
				&& $tokens[$i][0] === T_STRING)
			{
				$class_name = $tokens[$i][1];
				break;
			}
		}

		if (empty( $class_name ))
		{
			return '';
		}

		return $namespace . '\\' . $class_name;
	}

public function getClassname ( string $ file ) : string { $ php = file_get_contents ( $ file ) ; $ tokens = token_get_all ( $ php ) ; $ count = count ( $ tokens ) ; $ dlm = false ; $ namespace = '' ; $ class_name = '' ; for ( $ i = 2 ; $ i < $ count ; $ i ++ ) { if ( ( isset ( $ tokens [ $ i - 2 ] [ 1 ] ) && ( $ tokens [ $ i - 2 ] [ 1 ] === 'phpnamespace' || $ tokens [ $ i - 2 ] [ 1 ] === 'namespace' ) ) || ( $ dlm && $ tokens [ $ i - 1 ] [ 0 ] === T_NS_SEPARATOR && $ tokens [ $ i ] [ 0 ] === T_STRING ) ) { if ( ! $ dlm ) { $ namespace = 0 ; } if ( isset ( $ tokens [ $ i ] [ 1 ] ) ) { $ namespace = $ namespace ? $ namespace . '\\' . $ tokens [ $ i ] [ 1 ] : $ tokens [ $ i ] [ 1 ] ; $ dlm = true ; } } elseif ( $ dlm && ( $ tokens [ $ i ] [ 0 ] !== T_NS_SEPARATOR ) && ( $ tokens [ $ i ] [ 0 ] !== T_STRING ) ) { $ dlm = false ; } if ( ( $ tokens [ $ i - 2 ] [ 0 ] === T_CLASS || ( isset ( $ tokens [ $ i - 2 ] [ 1 ] ) && $ tokens [ $ i - 2 ] [ 1 ] === 'phpclass' ) ) && $ tokens [ $ i - 1 ] [ 0 ] === T_WHITESPACE && $ tokens [ $ i ] [ 0 ] === T_STRING ) { $ class_name = $ tokens [ $ i ] [ 1 ] ; break ; } } if ( empty ( $ class_name ) ) { return '' ; } return $ namespace . '\\' . $ class_name ; }

Examines a file and returns the fully qualified domain name.

@param string $file

@return string

Examines a file and returns the fully qualified domain name .


public function search(string $path, string $ext = 'php'): array
	{
		$path = $this->ensureExt($path, $ext);

		$foundPaths = [];

		foreach ($this->getNamespaces() as $namespace)
		{
			if (is_file($namespace['path'] . $path))
			{
				$foundPaths[] = $namespace['path'] . $path;
			}
		}

		// Remove any duplicates
		$foundPaths = array_unique($foundPaths);

		return $foundPaths;
	}

public
function
search
(
string
$
path
,
string
$
ext
=
'php'
)
:
array
{
$
path
=
$
this
->
ensureExt
(
$
path
,
$
ext
)
;
$
foundPaths
=
[
]
;
foreach
(
$
this
->
getNamespaces
(
)
as
$
namespace
)
{
if
(
is_file
(
$
namespace
[
'path'
]
.
$
path
)
)
{
$
foundPaths
[
]
=
$
namespace
[
'path'
]
.
$
path
;
}
}
// Remove any duplicates
$
foundPaths
=
array_unique
(
$
foundPaths
)
;
return
$
foundPaths
;
}

Searches through all of the defined namespaces looking for a file.
Returns an array of all found locations for the defined file.

Example:

$locator->search('Config/Routes.php');
// Assuming PSR4 namespaces include foo and bar, might return:
[
'app/Modules/foo/Config/Routes.php',
'app/Modules/bar/Config/Routes.php',
]

@param string $path
@param string $ext

@return array

Searches through all of the defined namespaces looking for a file . Returns an array of all found locations for the defined file .


protected function ensureExt(string $path, string $ext): string
	{
		if ($ext)
		{
			$ext = '.' . $ext;

			if (substr($path, -strlen($ext)) !== $ext)
			{
				$path .= $ext;
			}
		}

		return $path;
	}

protected function ensureExt ( string $ path , string $ ext ) : string { if ( $ ext ) { $ ext = '.' . $ ext ; if ( substr ( $ path , - strlen ( $ ext ) ) !== $ ext ) { $ path .= $ ext ; } } return $ path ; }

Ensures a extension is at the end of a filename

@param string $path
@param string $ext

@return string


public function findQualifiedNameFromPath(string $path)
	{
		$path = realpath($path);

		if (! $path)
		{
			return false;
		}

		foreach ($this->getNamespaces() as $namespace)
		{
			$namespace['path'] = realpath($namespace['path']);

			if (empty($namespace['path']))
			{
				continue;
			}

			if (mb_strpos($path, $namespace['path']) === 0)
			{
				$className = '\\' . $namespace['prefix'] . '\\' .
						ltrim(str_replace('/', '\\', mb_substr(
							$path, mb_strlen($namespace['path']))
						), '\\');
				// Remove the file extension (.php)
				$className = mb_substr($className, 0, -4);

				return $className;
			}
		}

		return false;
	}

public
function
findQualifiedNameFromPath
(
string
$
path
)
{
$
path
=
realpath
(
$
path
)
;
if
(
!
$
path
)
{
return
false
;
}
foreach
(
$
this
->
getNamespaces
(
)
as
$
namespace
)
{
$
namespace
[
'path'
]
=
realpath
(
$
namespace
[
'path'
]
)
;
if
(
empty
(
$
namespace
[
'path'
]
)
)
{
continue
;
}
if
(
mb_strpos
(
$
path
,
$
namespace
[
'path'
]
)
===
0
)
{
$
className
=
'\\'
.
$
namespace
[
'prefix'
]
.
'\\'
.
ltrim
(
str_replace
(
'/'
,
'\\'
,
mb_substr
(
$
path
,
mb_strlen
(
$
namespace
[
'path'
]
)
)
)
,
'\\'
)
;
// Remove the file extension (.php)
$
className
=
mb_substr
(
$
className
,
0
,
4
)
;
return
$
className
;
}
}
return
false
;
}

Find the qualified name of a file according to
the namespace of the first matched namespace path.

@param string $path

@return string|false The qualified name or false if the path is not found

Find the qualified name of a file according to the namespace of the first matched namespace path .


protected function legacyLocate(string $file, string $folder = null)
	{
		$paths = [
			APPPATH,
			SYSTEMPATH,
		];

		foreach ($paths as $path)
		{
			$path .= empty($folder) ? $file : $folder . '/' . $file;

			if (is_file($path))
			{
				return $path;
			}
		}

		return false;
	}

protected function legacyLocate ( string $ file , string $ folder = null ) { $ paths = [ APPPATH , SYSTEMPATH , ] ; foreach ( $ paths as $ path ) { $ path .= empty ( $ folder ) ? $ file : $ folder . '/' . $ file ; if ( is_file ( $ path ) ) { return $ path ; } } return false ; }

Checks the application folder to see if the file can be found.
Only for use with filenames that DO NOT include namespacing.

@param string      $file
@param string|null $folder

@return string|false The path to the file, or false if not found.

Checks the application folder to see if the file can be found . Only for use with filenames that DO NOT include namespacing .


public function renderString(string $view, array $options = null, bool $saveData = null): string
	{
		$start = microtime(true);
		if (is_null($saveData))
		{
			$saveData = $this->config->saveData;
		}

		extract($this->data);

		if (! $saveData)
		{
			$this->data = [];
		}

		ob_start();
		$incoming = '?>' . $view;
		eval($incoming);
		$output = ob_get_contents();
		@ob_end_clean();

		$this->logPerformance($start, microtime(true), $this->excerpt($view));

		return $output;
	}

public function renderString ( string $ view , array $ options = null , bool $ saveData = null ) : string { $ start = microtime ( true ) ; if ( is_null ( $ saveData ) ) { $ saveData = $ this -> config -> saveData ; } extract ( $ this -> data ) ; if ( ! $ saveData ) { $ this -> data = [ ] ; } ob_start ( ) ; $ incoming = '?>' . $ view ; eval ( $ incoming ) ; $ output = ob_get_contents ( ) ; @ ob_end_clean ( ) ; $ this -> logPerformance ( $ start , microtime ( true ) , $ this -> excerpt ( $ view ) ) ; return $ output ; }

Builds the output based upon a string and any
data that has already been set.
Cache does not apply, because there is no "key".

@param string  $view     The view contents
@param array   $options  Reserved for 3rd-party uses since
it might be needed to pass additional info
to other template engines.
@param boolean $saveData If true, will save data for use with any other calls,
if false, will clean the data after displaying the view,
if not specified, use the config setting.

@return string

Builds the output based upon a string and any data that has already been set . Cache does not apply because there is no key .


public function excerpt(string $string, int $length = 20): string
	{
		return (strlen($string) > $length) ? substr($string, 0, $length - 3) . '...' : $string;
	}

public function excerpt ( string $ string , int $ length = 20 ) : string { return ( strlen ( $ string ) > $ length ) ? substr ( $ string , 0 , $ length - 3 ) . '...' : $ string ; }

Extract first bit of a long string and add ellipsis

@param  string  $string
@param  integer $length
@return string


public function setData(array $data = [], string $context = null): RendererInterface
	{
		if (! empty($context))
		{
			$data = \esc($data, $context);
		}

		$this->data = array_merge($this->data, $data);

		return $this;
	}

public function setData ( array $ data = [ ] , string $ context = null ) : RendererInterface { if ( ! empty ( $ context ) ) { $ data = \ esc ( $ data , $ context ) ; } $ this -> data = array_merge ( $ this -> data , $ data ) ; return $ this ; }

Sets several pieces of view data at once.

@param array  $data
@param string $context The context to escape it for: html, css, js, url
If null, no escaping will happen

@return RendererInterface

Sets several pieces of view data at once .


public function setVar(string $name, $value = null, string $context = null): RendererInterface
	{
		if (! empty($context))
		{
			$value = \esc($value, $context);
		}

		$this->data[$name] = $value;

		return $this;
	}

public function setVar ( string $ name , $ value = null , string $ context = null ) : RendererInterface { if ( ! empty ( $ context ) ) { $ value = \ esc ( $ value , $ context ) ; } $ this -> data [ $ name ] = $ value ; return $ this ; }

Sets a single piece of view data.

@param string $name
@param mixed  $value
@param string $context The context to escape it for: html, css, js, url
If null, no escaping will happen

@return RendererInterface


public function renderSection(string $sectionName)
	{
		if (! isset($this->sections[$sectionName]))
		{
			echo '';

			return;
		}

		foreach ($this->sections[$sectionName] as $contents)
		{
			echo $contents;
		}
	}

public function renderSection ( string $ sectionName ) { if ( ! isset ( $ this -> sections [ $ sectionName ] ) ) { echo '' ; return ; } foreach ( $ this -> sections [ $ sectionName ] as $ contents ) { echo $ contents ; } }

Renders a section's contents.

@param string $sectionName


public function include(string $view, array $options = null, $saveData = null): string
	{
		return $this->render($view, $options, $saveData);
	}

public function include ( string $ view , array $ options = null , $ saveData = null ) : string { return $ this -> render ( $ view , $ options , $ saveData ) ; }

Used within layout views to include additional views.

@param string     $view
@param array|null $options
@param null       $saveData

@return string

Used within layout views to include additional views .


protected function logPerformance(float $start, float $end, string $view)
	{
		if (! $this->debug)
		{
			return;
		}

		$this->performanceData[] = [
			'start' => $start,
			'end'   => $end,
			'view'  => $view,
		];
	}

protected function logPerformance ( float $ start , float $ end , string $ view ) { if ( ! $ this -> debug ) { return ; } $ this -> performanceData [ ] = [ 'start' => $ start , 'end' => $ end , 'view' => $ view , ] ; }

Logs performance data for rendering a view.

@param float  $start
@param float  $end
@param string $view

Logs performance data for rendering a view .


public function withFile(string $path)
	{
		// Clear out the old resource so that
		// it doesn't try to use a previous image
		$this->resource = null;

		$this->image = new Image($path, true);

		$this->image->getProperties(false);
		$this->width  = $this->image->origWidth;
		$this->height = $this->image->origHeight;

		return $this;
	}

Sets another image for this handler to work on.
Keeps us from needing to continually instantiate the handler.

@param string $path

@return $this

Sets another image for this handler to work on . Keeps us from needing to continually instantiate the handler .


protected function ensureResource()
	{
		if ($this->resource === null)
		{
			$path = $this->image->getPathname();
			// if valid image type, make corresponding image resource
			switch ($this->image->imageType)
			{
				case IMAGETYPE_GIF:
					$this->resource = imagecreatefromgif($path);
					break;
				case IMAGETYPE_JPEG:
					$this->resource = imagecreatefromjpeg($path);
					break;
				case IMAGETYPE_PNG:
					$this->resource = imagecreatefrompng($path);
					break;
			}
		}
	}

Make the image resource object if needed


public function resize(int $width, int $height, bool $maintainRatio = false, string $masterDim = 'auto')
	{
		// If the target width/height match the source, then we have nothing to do here.
		if ($this->image->origWidth === $width && $this->image->origHeight === $height)
		{
			return $this;
		}

		$this->width  = $width;
		$this->height = $height;

		if ($maintainRatio)
		{
			$this->masterDim = $masterDim;
			$this->reproportion();
		}

		return $this->_resize($maintainRatio);
	}

Resize the image

@param integer $width
@param integer $height
@param boolean $maintainRatio If true, will get the closest match possible while keeping aspect ratio true.
@param string  $masterDim

@return BaseHandler


public function rotate(float $angle)
	{
		// Allowed rotation values
		$degs = [
			90,
			180,
			270,
		];

		if ($angle === '' || ! in_array($angle, $degs))
		{
			throw ImageException::forMissingAngle();
		}

		// cast angle as an int, for our use
		$angle = (int) $angle;

		// Reassign the width and height
		if ($angle === 90 || $angle === 270)
		{
			$temp         = $this->height;
			$this->width  = $this->height;
			$this->height = $temp;
		}

		// Call the Handler-specific version.
		$this->_rotate($angle);

		return $this;
	}

public
function
rotate
(
float
$
angle
)
{
// Allowed rotation values
$
degs
=
[
90
,
180
,
270
,
]
;
if
(
$
angle
===
''
||
!
in_array
(
$
angle
,
$
degs
)
)
{
throw
ImageException
::
forMissingAngle
(
)
;
}
// cast angle as an int, for our use
$
angle
=
(
int
)
$
angle
;
// Reassign the width and height
if
(
$
angle
===
90
||
$
angle
===
270
)
{
$
temp
=
$
this
->
height
;
$
this
->
width
=
$
this
->
height
;
$
this
->
height
=
$
temp
;
}
// Call the Handler-specific version.
$
this
->
_rotate
(
$
angle
)
;
return
$
this
;
}

Rotates the image on the current canvas.

@param float $angle

@return mixed

Rotates the image on the current canvas .


public function flip(string $dir = 'vertical')
	{
		$dir = strtolower($dir);

		if ($dir !== 'vertical' && $dir !== 'horizontal')
		{
			throw ImageException::forInvalidDirection($dir);
		}

		return $this->_flip($dir);
	}

public function flip ( string $ dir = 'vertical' ) { $ dir = strtolower ( $ dir ) ; if ( $ dir !== 'vertical' && $ dir !== 'horizontal' ) { throw ImageException :: forInvalidDirection ( $ dir ) ; } return $ this -> _flip ( $ dir ) ; }

Flips an image either horizontally or vertically.

@param string $dir Either 'vertical' or 'horizontal'

@return $this

Flips an image either horizontally or vertically .


public function text(string $text, array $options = [])
	{
		$options                = array_merge($this->textDefaults, $options);
		$options['color']       = trim($options['color'], '# ');
		$options['shadowColor'] = trim($options['shadowColor'], '# ');

		$this->_text($text, $options);

		return $this;
	}

public
function
text
(
string
$
text
,
array
$
options
=
[
]
)
{
$
options
=
array_merge
(
$
this
->
textDefaults
,
$
options
)
;
$
options
[
'color'
]
=
trim
(
$
options
[
'color'
]
,
'# '
)
;
$
options
[
'shadowColor'
]
=
trim
(
$
options
[
'shadowColor'
]
,
'# '
)
;
$
this
->
_text
(
$
text
,
$
options
)
;
return
$
this
;
}

Overlays a string of text over the image.

Valid options:

- color         Text Color (hex number)
- shadowColor   Color of the shadow (hex number)
- hAlign        Horizontal alignment: left, center, right
- vAlign        Vertical alignment: top, middle, bottom
- hOffset
- vOffset
- fontPath
- fontSize
- shadowOffset

@param string $text
@param array  $options

@return $this

Overlays a string of text over the image .


public function reorient(bool $silent = false)
	{
		$orientation = $this->getEXIF('Orientation', $silent);

		switch ($orientation)
		{
			case 2:
				return $this->flip('horizontal');
				break;
			case 3:
				return $this->rotate(180);
				break;
			case 4:
				return $this->rotate(180)
								->flip('horizontal');
				break;
			case 5:
				return $this->rotate(270)
								->flip('horizontal');
				break;
			case 6:
				return $this->rotate(270);
				break;
			case 7:
				return $this->rotate(90)
								->flip('horizontal');
				break;
			case 8:
				return $this->rotate(90);
				break;
			default:
				return $this;
		}
	}

public function reorient ( bool $ silent = false ) { $ orientation = $ this -> getEXIF ( 'Orientation' , $ silent ) ; switch ( $ orientation ) { case 2 : return $ this -> flip ( 'horizontal' ) ; break ; case 3 : return $ this -> rotate ( 180 ) ; break ; case 4 : return $ this -> rotate ( 180 ) -> flip ( 'horizontal' ) ; break ; case 5 : return $ this -> rotate ( 270 ) -> flip ( 'horizontal' ) ; break ; case 6 : return $ this -> rotate ( 270 ) ; break ; case 7 : return $ this -> rotate ( 90 ) -> flip ( 'horizontal' ) ; break ; case 8 : return $ this -> rotate ( 90 ) ; break ; default : return $ this ; } }

Reads the EXIF information from the image and modifies the orientation
so that displays correctly in the browser. This is especially an issue
with images taken by smartphones who always store the image up-right,
but set the orientation flag to display it correctly.

@param boolean $silent If true, will ignore exceptions when PHP doesn't support EXIF.

@return $this

Reads the EXIF information from the image and modifies the orientation so that displays correctly in the browser . This is especially an issue with images taken by smartphones who always store the image up - right but set the orientation flag to display it correctly .


public function getEXIF(string $key = null, bool $silent = false)
	{
		if (! function_exists('exif_read_data'))
		{
			if ($silent)
			{
				return null;
			}
		}

		$exif = exif_read_data($this->image->getPathname());
		if (! is_null($key) && is_array($exif))
		{
			$exif = $exif[$key] ?? false;
		}

		return $exif;
	}

public function getEXIF ( string $ key = null , bool $ silent = false ) { if ( ! function_exists ( 'exif_read_data' ) ) { if ( $ silent ) { return null ; } } $ exif = exif_read_data ( $ this -> image -> getPathname ( ) ) ; if ( ! is_null ( $ key ) && is_array ( $ exif ) ) { $ exif = $ exif [ $ key ] ?? false ; } return $ exif ; }

Retrieve the EXIF information from the image, if possible. Returns
an array of the information, or null if nothing can be found.

@param string|null $key    If specified, will only return this piece of EXIF data.

@param boolean     $silent If true, will not throw our own exceptions.

@return mixed

Retrieve the EXIF information from the image if possible . Returns an array of the information or null if nothing can be found .


public function fit(int $width, int $height = null, string $position = 'center')
	{
		$origWidth  = $this->image->origWidth;
		$origHeight = $this->image->origHeight;

		list($cropWidth, $cropHeight) = $this->calcAspectRatio($width, $height, $origWidth, $origHeight);

		if (is_null($height))
		{
			$height = ceil(($width / $cropWidth) * $cropHeight);
		}

		list($x, $y) = $this->calcCropCoords($width, $height, $origWidth, $origHeight, $position);

		return $this->crop($cropWidth, $cropHeight, $x, $y)
						->resize($width, $height);
	}

public function fit ( int $ width , int $ height = null , string $ position = 'center' ) { $ origWidth = $ this -> image -> origWidth ; $ origHeight = $ this -> image -> origHeight ; list ( $ cropWidth , $ cropHeight ) = $ this -> calcAspectRatio ( $ width , $ height , $ origWidth , $ origHeight ) ; if ( is_null ( $ height ) ) { $ height = ceil ( ( $ width / $ cropWidth ) * $ cropHeight ) ; } list ( $ x , $ y ) = $ this -> calcCropCoords ( $ width , $ height , $ origWidth , $ origHeight , $ position ) ; return $ this -> crop ( $ cropWidth , $ cropHeight , $ x , $ y ) -> resize ( $ width , $ height ) ; }

Combine cropping and resizing into a single command.

Supported positions:
- top-left
- top
- top-right
- left
- center
- right
- bottom-left
- bottom
- bottom-right

@param integer $width
@param integer $height
@param string  $position

@return boolean

Combine cropping and resizing into a single command .


public function run(array $params)
	{
		// Valid PHP Version?
		if (phpversion() < $this->minPHPVersion)
		{
			die('Your PHP version must be ' . $this->minPHPVersion .
				' or higher to run CodeIgniter. Current version: ' . phpversion());
		}

		// Collect any user-supplied options and apply them.
		$php  = CLI::getOption('php') ?? PHP_BINARY;
		$host = CLI::getOption('host') ?? 'localhost';
		$port = CLI::getOption('port') ?? '8080';

		// Get the party started.
		CLI::write('CodeIgniter development server started on http://' . $host . ':' . $port, 'green');
		CLI::write('Press Control-C to stop.');

		// Set the Front Controller path as Document Root.
		$docroot = escapeshellarg(FCPATH);

		// Mimic Apache's mod_rewrite functionality with user settings.
		$rewrite = escapeshellarg(__DIR__ . '/rewrite.php');

		// Call PHP's built-in webserver, making sure to set our
		// base path to the public folder, and to use the rewrite file
		// to ensure our environment is set and it simulates basic mod_rewrite.
		passthru($php . ' -S ' . $host . ':' . $port . ' -t ' . $docroot . ' ' . $rewrite);
	}

Run the server

@param array $params Parameters

@return void


public function renderString(string $template, array $options = null, bool $saveData = null): string
	{
		$start = microtime(true);
		if (is_null($saveData))
		{
			$saveData = $this->config->saveData;
		}

		$output = $this->parse($template, $this->data, $options);

		$this->logPerformance($start, microtime(true), $this->excerpt($template));

		if (! $saveData)
		{
			$this->data = [];
		}
		return $output;
	}

public function renderString ( string $ template , array $ options = null , bool $ saveData = null ) : string { $ start = microtime ( true ) ; if ( is_null ( $ saveData ) ) { $ saveData = $ this -> config -> saveData ; } $ output = $ this -> parse ( $ template , $ this -> data , $ options ) ; $ this -> logPerformance ( $ start , microtime ( true ) , $ this -> excerpt ( $ template ) ) ; if ( ! $ saveData ) { $ this -> data = [ ] ; } return $ output ; }

Parse a String

Parses pseudo-variables contained in the specified string,
replacing them with any data that has already been set.

@param string  $template
@param array   $options
@param boolean $saveData

@return string


protected function parsePair(string $variable, array $data, string $template): array
	{
		// Holds the replacement patterns and contents
		// that will be used within a preg_replace in parse()
		$replace = [];

		// Find all matches of space-flexible versions of {tag}{/tag} so we
		// have something to loop over.
		preg_match_all(
				'#' . $this->leftDelimiter . '\s*' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '(.+?)' .
				$this->leftDelimiter . '\s*' . '/' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '#s', $template, $matches, PREG_SET_ORDER
		);

		/*
		 * Each match looks like:
		 *
		 * $match[0] {tag}...{/tag}
		 * $match[1] Contents inside the tag
		 */
		foreach ($matches as $match)
		{
			// Loop over each piece of $data, replacing
			// it's contents so that we know what to replace in parse()
			$str = '';  // holds the new contents for this tag pair.
			foreach ($data as $row)
			{
				// Objects that have a `toArray()` method should be
				// converted with that method (i.e. Entities)
				if (is_object($row) && method_exists($row, 'toArray'))
				{
					$row = $row->toArray();
				}
				// Otherwise, cast as an array and it will grab public properties.
				else if (is_object($row))
				{
					$row = (array)$row;
				}

				$temp  = [];
				$pairs = [];
				$out   = $match[1];
				foreach ($row as $key => $val)
				{
					// For nested data, send us back through this method...
					if (is_array($val))
					{
						$pair = $this->parsePair($key, $val, $match[1]);

						if (! empty($pair))
						{
							$pairs[array_keys( $pair )[0]] = true;
							$temp                          = array_merge($temp, $pair);
						}

						continue;
					}
					else if (is_object($val))
					{
						$val = 'Class: ' . get_class($val);
					}
					else if (is_resource($val))
					{
						$val = 'Resource';
					}

					$temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|\w<>=\(\),:_\-\s\+]+)*\s*!?' . $this->rightDelimiter . '#s'] = $val;
				}

				// Now replace our placeholders with the new content.
				foreach ($temp as $pattern => $content)
				{
					$out = $this->replaceSingle($pattern, $content, $out, ! isset( $pairs[$pattern] ) );
				}

				$str .= $out;
			}

			$replace['#' . $match[0] . '#s'] = $str;
		}

		return $replace;
	}

Parse a tag pair

Parses tag pairs: {some_tag} string... {/some_tag}

@param  string $variable
@param  array  $data
@param  string $template
@return array


protected function extractNoparse(string $template): string
	{
		$pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ms';

		/*
		 * $matches[][0] is the raw match
		 * $matches[][1] is the contents
		 */
		if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER))
		{
			foreach ($matches as $match)
			{
				// Create a hash of the contents to insert in its place.
				$hash                       = md5($match[1]);
				$this->noparseBlocks[$hash] = $match[1];
				$template                   = str_replace($match[0], "noparse_{$hash}", $template);
			}
		}

		return $template;
	}

Extracts noparse blocks, inserting a hash in its place so that
those blocks of the page are not touched by parsing.

@param string $template

@return string

Extracts noparse blocks inserting a hash in its place so that those blocks of the page are not touched by parsing .


public function insertNoparse(string $template): string
	{
		foreach ($this->noparseBlocks as $hash => $replace)
		{
			$template = str_replace("noparse_{$hash}", $replace, $template);
			unset($this->noparseBlocks[$hash]);
		}

		return $template;
	}

public function insertNoparse ( string $ template ) : string { foreach ( $ this -> noparseBlocks as $ hash => $ replace ) { $ template = str_replace ( "noparse_{$hash}" , $ replace , $ template ) ; unset ( $ this -> noparseBlocks [ $ hash ] ) ; } return $ template ; }

Re-inserts the noparsed contents back into the template.

@param string $template

@return string

Re - inserts the noparsed contents back into the template .


protected function parseConditionals(string $template): string
	{
		$pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms';

		/**
		 * For each match:
		 * [0] = raw match `{if var}`
		 * [1] = conditional `if`
		 * [2] = condition `do === true`
		 * [3] = same as [2]
		 */
		preg_match_all($pattern, $template, $matches, PREG_SET_ORDER);

		foreach ($matches as $match)
		{
			// Build the string to replace the `if` statement with.
			$condition = $match[2];

			$statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>';
			$template  = str_replace($match[0], $statement, $template);
		}

		$template = preg_replace('/\{\s*else\s*\}/ms', '<?php else: ?>', $template);
		$template = preg_replace('/\{\s*endif\s*\}/ms', '<?php endif; ?>', $template);

		// Parse the PHP itself, or insert an error so they can debug
		ob_start();
		extract($this->data);
		try
		{
			eval('?>' . $template . '<?php ');
		}
		catch (\ParseError $e)
		{
			ob_end_clean();
			throw ViewException::forTagSyntaxError(str_replace(['?>', '<?php '], '', $template));
		}
		return ob_get_clean();
	}

Parses any conditionals in the code, removing blocks that don't
pass so we don't try to parse it later.

Valid conditionals:
- if
- elseif
- else

@param string $template

@return string

Parses any conditionals in the code removing blocks that don t pass so we don t try to parse it later .


public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface
	{
		$this->leftDelimiter  = $leftDelimiter;
		$this->rightDelimiter = $rightDelimiter;
		return $this;
	}

public function setDelimiters ( $ leftDelimiter = '{' , $ rightDelimiter = '}' ) : RendererInterface { $ this -> leftDelimiter = $ leftDelimiter ; $ this -> rightDelimiter = $ rightDelimiter ; return $ this ; }

Over-ride the substitution field delimiters.

@param  string $leftDelimiter
@param  string $rightDelimiter
@return RendererInterface

Over - ride the substitution field delimiters .


protected function replaceSingle($pattern, $content, $template, bool $escape = false): string
	{
		// Any dollar signs in the pattern will be mis-interpreted, so slash them
		$pattern = addcslashes($pattern, '$');

		// Replace the content in the template
		$template = preg_replace_callback($pattern, function ($matches) use ($content, $escape) {
			// Check for {! !} syntax to not-escape this one.
			if (strpos($matches[0], '{!') === 0 && substr($matches[0], -2) === '!}')
			{
				$escape = false;
			}

			return $this->prepareReplacement($matches, $content, $escape);
		}, $template);

		return $template;
	}

Handles replacing a pseudo-variable with the actual content. Will double-check
for escaping brackets.

@param $pattern
@param $content
@param $template
@param boolean  $escape

@return string

Handles replacing a pseudo - variable with the actual content . Will double - check for escaping brackets .


public function shouldAddEscaping(string $key)
	{
		$escape = false;

		$key = trim(str_replace(['{', '}'], '', $key));

		// If the key has a context stored (from setData)
		// we need to respect that.
		if (array_key_exists($key, $this->dataContexts))
		{
			if ($this->dataContexts[$key] !== 'raw')
			{
				return $this->dataContexts[$key];
			}
		}
		// No pipes, then we know we need to escape
		elseif (strpos($key, '|') === false)
		{
			$escape = 'html';
		}
		// If there's a `noescape` then we're definitely false.
		elseif (strpos($key, 'noescape') !== false)
		{
			$escape = false;
		}
		// If no `esc` filter is found, then we'll need to add one.
		elseif (! preg_match('/\s+esc/', $key))
		{
			$escape = 'html';
		}

		return $escape;
	}

Checks the placeholder the view provided to see if we need to provide any autoescaping.

@param string $key

@return false|string

Checks the placeholder the view provided to see if we need to provide any autoescaping .


public function addPlugin(string $alias, callable $callback, bool $isPair = false)
	{
		$this->plugins[$alias] = $isPair ? [$callback] : $callback;

		return $this;
	}

public function addPlugin ( string $ alias , callable $ callback , bool $ isPair = false ) { $ this -> plugins [ $ alias ] = $ isPair ? [ $ callback ] : $ callback ; return $ this ; }

Makes a new plugin available during the parsing of the template.

@param string   $alias
@param callable $callback

@param boolean  $isPair

@return $this

Makes a new plugin available during the parsing of the template .


protected function createImage(string $path = '', string $imageType = '')
	{
		if ($this->resource !== null)
		{
			return $this->resource;
		}

		if ($path === '')
		{
			$path = $this->image->getPathname();
		}

		if ($imageType === '')
		{
			$imageType = $this->image->imageType;
		}

		switch ($imageType)
		{
			case IMAGETYPE_GIF:
				if (! function_exists('imagecreatefromgif'))
				{
					throw ImageException::forInvalidImageCreate(lang('images.gifNotSupported'));
				}

				return imagecreatefromgif($path);
			case IMAGETYPE_JPEG:
				if (! function_exists('imagecreatefromjpeg'))
				{
					throw ImageException::forInvalidImageCreate(lang('images.jpgNotSupported'));
				}

				return imagecreatefromjpeg($path);
			case IMAGETYPE_PNG:
				if (! function_exists('imagecreatefrompng'))
				{
					throw ImageException::forInvalidImageCreate(lang('images.pngNotSupported'));
				}

				return imagecreatefrompng($path);
			default:
				throw ImageException::forInvalidImageCreate('Ima');
		}
	}

protected function createImage ( string $ path = '' , string $ imageType = '' ) { if ( $ this -> resource !== null ) { return $ this -> resource ; } if ( $ path === '' ) { $ path = $ this -> image -> getPathname ( ) ; } if ( $ imageType === '' ) { $ imageType = $ this -> image -> imageType ; } switch ( $ imageType ) { case IMAGETYPE_GIF : if ( ! function_exists ( 'imagecreatefromgif' ) ) { throw ImageException :: forInvalidImageCreate ( lang ( 'images.gifNotSupported' ) ) ; } return imagecreatefromgif ( $ path ) ; case IMAGETYPE_JPEG : if ( ! function_exists ( 'imagecreatefromjpeg' ) ) { throw ImageException :: forInvalidImageCreate ( lang ( 'images.jpgNotSupported' ) ) ; } return imagecreatefromjpeg ( $ path ) ; case IMAGETYPE_PNG : if ( ! function_exists ( 'imagecreatefrompng' ) ) { throw ImageException :: forInvalidImageCreate ( lang ( 'images.pngNotSupported' ) ) ; } return imagecreatefrompng ( $ path ) ; default : throw ImageException :: forInvalidImageCreate ( 'Ima' ) ; } }

Create Image Resource

This simply creates an image resource handle
based on the type of image being processed

@param string    $path
@param string    $imageType

@return resource|boolean


public function getHeader(string $name)
	{
		$orig_name = $this->getHeaderName($name);

		if (! isset($this->headers[$orig_name]))
		{
			return null;
		}

		return $this->headers[$orig_name];
	}

public function getHeader ( string $ name ) { $ orig_name = $ this -> getHeaderName ( $ name ) ; if ( ! isset ( $ this -> headers [ $ orig_name ] ) ) { return null ; } return $ this -> headers [ $ orig_name ] ; }

Returns a single header object. If multiple headers with the same
name exist, then will return an array of header objects.

@param string $name

@return array|\CodeIgniter\HTTP\Header

Returns a single header object . If multiple headers with the same name exist then will return an array of header objects .


public function hasHeader(string $name): bool
	{
		$orig_name = $this->getHeaderName($name);

		return isset($this->headers[$orig_name]);
	}

public function hasHeader ( string $ name ) : bool { $ orig_name = $ this -> getHeaderName ( $ name ) ; return isset ( $ this -> headers [ $ orig_name ] ) ; }

Determines whether a header exists.

@param string    $name

@return boolean


public function setHeader(string $name, $value)
	{
		if (! isset($this->headers[$name]))
		{
			$this->headers[$name] = new Header($name, $value);

			$this->headerMap[strtolower($name)] = $name;

			return $this;
		}

		if (! is_array($this->headers[$name]))
		{
			$this->headers[$name] = [$this->headers[$name]];
		}

		if (isset($this->headers[$name]))
		{
			$this->headers[$name] = new Header($name, $value);
		}

		return $this;
	}

public function setHeader ( string $ name , $ value ) { if ( ! isset ( $ this -> headers [ $ name ] ) ) { $ this -> headers [ $ name ] = new Header ( $ name , $ value ) ; $ this -> headerMap [ strtolower ( $ name ) ] = $ name ; return $ this ; } if ( ! is_array ( $ this -> headers [ $ name ] ) ) { $ this -> headers [ $ name ] = [ $ this -> headers [ $ name ] ] ; } if ( isset ( $ this -> headers [ $ name ] ) ) { $ this -> headers [ $ name ] = new Header ( $ name , $ value ) ; } return $ this ; }

Sets a header and it's value.

@param string            $name
@param array|null|string $value

@return Message|Response


public function removeHeader(string $name)
	{
		$orig_name = $this->getHeaderName($name);

		unset($this->headers[$orig_name]);
		unset($this->headerMap[strtolower($name)]);

		return $this;
	}

public function removeHeader ( string $ name ) { $ orig_name = $ this -> getHeaderName ( $ name ) ; unset ( $ this -> headers [ $ orig_name ] ) ; unset ( $ this -> headerMap [ strtolower ( $ name ) ] ) ; return $ this ; }

Removes a header from the list of headers we track.

@param string $name

@return Message

Removes a header from the list of headers we track .


public function setProtocolVersion(string $version)
	{
		if (! is_numeric($version))
		{
			$version = substr($version, strpos($version, '/') + 1);
		}

		if (! in_array($version, $this->validProtocolVersions))
		{
			throw HTTPException::forInvalidHTTPProtocol(implode(', ', $this->validProtocolVersions));
		}

		$this->protocolVersion = $version;

		return $this;
	}

public
function
setProtocolVersion
(
string
$
version
)
{
if
(
!
is_numeric
(
$
version
)
)
{
$
version
=
substr
(
$
version
,
strpos
(
$
version
,
'/'
)
+
1
)
;
}
if
(
!
in_array
(
$
version
,
$
this
->
validProtocolVersions
)
)
{
throw
HTTPException
::
forInvalidHTTPProtocol
(
implode
(
', '
,
$
this
->
validProtocolVersions
)
)
;
}
$
this
->
protocolVersion
=
$
version
;
return
$
this
;
}

Sets the HTTP protocol version.

@param string $version

@return Message


protected function getHeaderName(string $name): string
	{
		$lower_name = strtolower($name);

		return $this->headerMap[$lower_name] ?? $name;
	}

protected function getHeaderName ( string $ name ) : string { $ lower_name = strtolower ( $ name ) ; return $ this -> headerMap [ $ lower_name ] ?? $ name ; }

Takes a header name in any case, and returns the
normal-case version of the header.

@param string $name

@return string

Takes a header name in any case and returns the normal - case version of the header .


protected function configureSessionIDRegex()
	{
		$bitsPerCharacter = (int)ini_get('session.sid_bits_per_character');
		$SIDLength        = (int)ini_get('session.sid_length');

		if (($bits = $SIDLength * $bitsPerCharacter) < 160)
		{
			// Add as many more characters as necessary to reach at least 160 bits
			$SIDLength += (int)ceil((160 % $bits) / $bitsPerCharacter);
			ini_set('session.sid_length', $SIDLength);
		}

		// Yes, 4,5,6 are the only known possible values as of 2016-10-27
		switch ($bitsPerCharacter)
		{
			case 4:
				$this->sessionIDRegex = '[0-9a-f]';
				break;
			case 5:
				$this->sessionIDRegex = '[0-9a-v]';
				break;
			case 6:
				$this->sessionIDRegex = '[0-9a-zA-Z,-]';
				break;
		}

		$this->sessionIDRegex .= '{' . $SIDLength . '}';
	}


public function getReason(): string
	{
		if (empty($this->reason))
		{
			return ! empty($this->statusCode) ? static::$statusCodes[$this->statusCode] : '';
		}

		return $this->reason;
	}

public function getReason ( ) : string { if ( empty ( $ this -> reason ) ) { return ! empty ( $ this -> statusCode ) ? static :: $ statusCodes [ $ this -> statusCode ] : '' ; } return $ this -> reason ; }

Gets the response response phrase associated with the status code.

@see http://tools.ietf.org/html/rfc7231#section-6
@see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

@return string

Gets the response response phrase associated with the status code .


public function setLink(PagerInterface $pager)
	{
		$links = '';

		if ($previous = $pager->getPreviousPageURI())
		{
			$links .= '<' . $pager->getPageURI($pager->getFirstPage()) . '>; rel="first",';
			$links .= '<' . $previous . '>; rel="prev"';
		}

		if (($next = $pager->getNextPageURI()) && $previous)
		{
			$links .= ',';
		}

		if ($next)
		{
			$links .= '<' . $next . '>; rel="next",';
			$links .= '<' . $pager->getPageURI($pager->getLastPage()) . '>; rel="last"';
		}

		$this->setHeader('Link', $links);

		return $this;
	}

public
function
setLink
(
PagerInterface
$
pager
)
{
$
links
=
''
;
if
(
$
previous
=
$
pager
->
getPreviousPageURI
(
)
)
{
$
links
.=
'<'
.
$
pager
->
getPageURI
(
$
pager
->
getFirstPage
(
)
)
.
'>; rel="first",'
;
$
links
.=
'<'
.
$
previous
.
'>; rel="prev"'
;
}
if
(
(
$
next
=
$
pager
->
getNextPageURI
(
)
)
&&
$
previous
)
{
$
links
.=
','
;
}
if
(
$
next
)
{
$
links
.=
'<'
.
$
next
.
'>; rel="next",'
;
$
links
.=
'<'
.
$
pager
->
getPageURI
(
$
pager
->
getLastPage
(
)
)
.
'>; rel="last"'
;
}
$
this
->
setHeader
(
'Link'
,
$
links
)
;
return
$
this
;
}

Set the Link Header

@param \CodeIgniter\Pager\PagerInterface $pager

@see http://tools.ietf.org/html/rfc5988

@return Response


public function setContentType(string $mime, string $charset = 'UTF-8')
	{
		// add charset attribute if not already there and provided as parm
		if ((strpos($mime, 'charset=') < 1) && ! empty($charset))
		{
			$mime .= '; charset=' . $charset;
		}

		$this->removeHeader('Content-Type'); // replace existing content type
		$this->setHeader('Content-Type', $mime);

		return $this;
	}

Sets the Content Type header for this response with the mime type
and, optionally, the charset.

@param string $mime
@param string $charset

@return Response

Sets the Content Type header for this response with the mime type and optionally the charset .


public function getJSON()
	{
		$body = $this->body;

		if ($this->bodyFormat !== 'json')
		{
			/**
			 * @var Format $config
			 */
			$config    = config(Format::class);
			$formatter = $config->getFormatter('application/json');

			$body = $formatter->format($body);
		}

		return $body ?: null;
	}

Returns the current body, converted to JSON is it isn't already.

@return mixed|string

@throws \InvalidArgumentException If the body property is not array.

Returns the current body converted to JSON is it isn t already .


public function getXML()
	{
		$body = $this->body;

		if ($this->bodyFormat !== 'xml')
		{
			/**
			 * @var Format $config
			 */
			$config    = config(Format::class);
			$formatter = $config->getFormatter('application/xml');

			$body = $formatter->format($body);
		}

		return $body;
	}

Retrieves the current body into XML and returns it.

@return mixed|string
@throws \InvalidArgumentException If the body property is not array.

Retrieves the current body into XML and returns it .


protected function formatBody($body, string $format)
	{
		$mime = "application/{$format}";
		$this->setContentType($mime);
		$this->bodyFormat = $format;

		// Nothing much to do for a string...
		if (! is_string($body))
		{
			/**
			 * @var Format $config
			 */
			$config    = config(Format::class);
			$formatter = $config->getFormatter($mime);

			$body = $formatter->format($body);
		}

		return $body;
	}

Handles conversion of the of the data into the appropriate format,
and sets the correct Content-Type header for our response.

@param string|array $body
@param string       $format Valid: json, xml

@return mixed
@throws \InvalidArgumentException If the body property is not string or array.

Handles conversion of the of the data into the appropriate format and sets the correct Content - Type header for our response .


public function setCache(array $options = [])
	{
		if (empty($options))
		{
			return $this;
		}

		$this->removeHeader('Cache-Control');
		$this->removeHeader('ETag');

		// ETag
		if (isset($options['etag']))
		{
			$this->setHeader('ETag', $options['etag']);
			unset($options['etag']);
		}

		// Last Modified
		if (isset($options['last-modified']))
		{
			$this->setLastModified($options['last-modified']);

			unset($options['last-modified']);
		}

		$this->setHeader('Cache-control', $options);

		return $this;
	}

public
function
setCache
(
array
$
options
=
[
]
)
{
if
(
empty
(
$
options
)
)
{
return
$
this
;
}
$
this
->
removeHeader
(
'Cache-Control'
)
;
$
this
->
removeHeader
(
'ETag'
)
;
// ETag
if
(
isset
(
$
options
[
'etag'
]
)
)
{
$
this
->
setHeader
(
'ETag'
,
$
options
[
'etag'
]
)
;
unset
(
$
options
[
'etag'
]
)
;
}
// Last Modified
if
(
isset
(
$
options
[
'last-modified'
]
)
)
{
$
this
->
setLastModified
(
$
options
[
'last-modified'
]
)
;
unset
(
$
options
[
'last-modified'
]
)
;
}
$
this
->
setHeader
(
'Cache-control'
,
$
options
)
;
return
$
this
;
}

A shortcut method that allows the developer to set all of the
cache-control headers in one method call.

The options array is used to provide the cache-control directives
for the header. It might look something like:

$options = [
'max-age'  => 300,
's-maxage' => 900
'etag'     => 'abcde',
];

Typical options are:
- etag
- last-modified
- max-age
- s-maxage
- private
- public
- must-revalidate
- proxy-revalidate
- no-transform

@param array $options

@return Response

A shortcut method that allows the developer to set all of the cache - control headers in one method call .


public function send()
	{
		// If we're enforcing a Content Security Policy,
		// we need to give it a chance to build out it's headers.
		if ($this->CSPEnabled === true)
		{
			$this->CSP->finalize($this);
		}
		else
		{
			$this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body);
		}

		$this->sendHeaders();
		$this->sendBody();
		$this->sendCookies();

		return $this;
	}

Sends the output to the browser.

@return Response


public function sendHeaders()
	{
		// Have the headers already been sent?
		if ($this->pretend || headers_sent())
		{
			return $this;
		}

		// Per spec, MUST be sent with each request, if possible.
		// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
		if (! isset($this->headers['Date']))
		{
			$this->setDate(\DateTime::createFromFormat('U', time()));
		}

		// HTTP Status
		header(sprintf('HTTP/%s %s %s', $this->protocolVersion, $this->statusCode, $this->reason), true, $this->statusCode);

		// Send all of our headers
		foreach ($this->getHeaders() as $name => $values)
		{
			header($name . ': ' . $this->getHeaderLine($name), false, $this->statusCode);
		}

		return $this;
	}

Sends the headers of this HTTP request to the browser.

@return Response

Sends the headers of this HTTP request to the browser .


public function setCookie(
		$name,
		$value = '',
		$expire = '',
		$domain = '',
		$path = '/',
		$prefix = '',
		$secure = false,
		$httponly = false
	)
	{
		if (is_array($name))
		{
			// always leave 'name' in last place, as the loop will break otherwise, due to $$item
			foreach (['value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name'] as $item)
			{
				if (isset($name[$item]))
				{
					$$item = $name[$item];
				}
			}
		}

		if ($prefix === '' && $this->cookiePrefix !== '')
		{
			$prefix = $this->cookiePrefix;
		}

		if ($domain === '' && $this->cookieDomain !== '')
		{
			$domain = $this->cookieDomain;
		}

		if ($path === '/' && $this->cookiePath !== '/')
		{
			$path = $this->cookiePath;
		}

		if ($secure === false && $this->cookieSecure === true)
		{
			$secure = $this->cookieSecure;
		}

		if ($httponly === false && $this->cookieHTTPOnly !== false)
		{
			$httponly = $this->cookieHTTPOnly;
		}

		if (! is_numeric($expire))
		{
			$expire = time() - 86500;
		}
		else
		{
			$expire = ($expire > 0) ? time() + $expire : 0;
		}

		$this->cookies[] = [
			'name'     => $prefix . $name,
			'value'    => $value,
			'expires'  => $expire,
			'path'     => $path,
			'domain'   => $domain,
			'secure'   => $secure,
			'httponly' => $httponly,
		];

		return $this;
	}

Set a cookie

Accepts an arbitrary number of binds (up to 7) or an associative
array in the first parameter containing all the values.

@param string|array  $name     Cookie name or array containing binds
@param string        $value    Cookie value
@param string        $expire   Cookie expiration time in seconds
@param string        $domain   Cookie domain (e.g.: '.yourdomain.com')
@param string        $path     Cookie path (default: '/')
@param string        $prefix   Cookie name prefix
@param boolean|false $secure   Whether to only transfer cookies via SSL
@param boolean|false $httponly Whether only make the cookie accessible via HTTP (no javascript)

@return $this


public function hasCookie(string $name, string $value = null, string $prefix = ''): bool
	{
		if ($prefix === '' && $this->cookiePrefix !== '')
		{
			$prefix = $this->cookiePrefix;
		}

		$name = $prefix . $name;

		foreach ($this->cookies as $cookie)
		{
			if ($cookie['name'] !== $name)
			{
				continue;
			}

			if ($value === null)
			{
				return true;
			}

			return $cookie['value'] === $value;
		}

		return false;
	}

public function hasCookie ( string $ name , string $ value = null , string $ prefix = '' ) : bool { if ( $ prefix === '' && $ this -> cookiePrefix !== '' ) { $ prefix = $ this -> cookiePrefix ; } $ name = $ prefix . $ name ; foreach ( $ this -> cookies as $ cookie ) { if ( $ cookie [ 'name' ] !== $ name ) { continue ; } if ( $ value === null ) { return true ; } return $ cookie [ 'value' ] === $ value ; } return false ; }

Checks to see if the Response has a specified cookie or not.

@param string      $name
@param string|null $value
@param string      $prefix

@return boolean

Checks to see if the Response has a specified cookie or not .


public function getCookie(string $name = null, string $prefix = '')
	{
		// if no name given, return them all
		if (empty($name))
		{
			return $this->cookies;
		}

		if ($prefix === '' && $this->cookiePrefix !== '')
		{
			$prefix = $this->cookiePrefix;
		}

		$name = $prefix . $name;

		foreach ($this->cookies as $cookie)
		{
			if ($cookie['name'] === $name)
			{
				return $cookie;
			}
		}
		return null;
	}

public
function
getCookie
(
string
$
name
=
,
string
$
prefix
=
''
)
{
// if no name given, return them all
if
(
empty
(
$
name
)
)
{
return
$
this
->
cookies
;
}
if
(
$
prefix
===
''
&&
$
this
->
cookiePrefix
!==
''
)
{
$
prefix
=
$
this
->
cookiePrefix
;
}
$
name
=
$
prefix
.
$
name
;
foreach
(
$
this
->
cookies
as
$
cookie
)
{
if
(
$
cookie
[
'name'
]
===
$
name
)
{
return
$
cookie
;
}
}
return
;
}

Returns the cookie

@param string|null $name
@param string      $prefix

@return mixed


public function deleteCookie(string $name = '', string $domain = '', string $path = '/', string $prefix = '')
	{
		if (empty($name))
		{
			return $this;
		}

		if ($prefix === '' && $this->cookiePrefix !== '')
		{
			$prefix = $this->cookiePrefix;
		}

		$name = $prefix . $name;

		foreach ($this->cookies as &$cookie)
		{
			if ($cookie['name'] === $name)
			{
				if (! empty($domain) && $cookie['domain'] !== $domain)
				{
					continue;
				}
				if (! empty($path) && $cookie['path'] !== $path)
				{
					continue;
				}
				$cookie['value']   = '';
				$cookie['expires'] = '';

				break;
			}
		}

		return $this;
	}

public function deleteCookie ( string $ name = '' , string $ domain = '' , string $ path = '/' , string $ prefix = '' ) { if ( empty ( $ name ) ) { return $ this ; } if ( $ prefix === '' && $ this -> cookiePrefix !== '' ) { $ prefix = $ this -> cookiePrefix ; } $ name = $ prefix . $ name ; foreach ( $ this -> cookies as & $ cookie ) { if ( $ cookie [ 'name' ] === $ name ) { if ( ! empty ( $ domain ) && $ cookie [ 'domain' ] !== $ domain ) { continue ; } if ( ! empty ( $ path ) && $ cookie [ 'path' ] !== $ path ) { continue ; } $ cookie [ 'value' ] = '' ; $ cookie [ 'expires' ] = '' ; break ; } } return $ this ; }

Sets a cookie to be deleted when the response is sent.

@param string $name
@param string $domain
@param string $path
@param string $prefix

@return $this

Sets a cookie to be deleted when the response is sent .


protected function sendCookies()
	{
		if ($this->pretend)
		{
			return;
		}

		foreach ($this->cookies as $params)
		{
			// PHP cannot unpack array with string keys
			$params = array_values($params);

			setcookie(...$params);
		}
	}


public function download(string $filename = '', $data = '', bool $setMime = false)
	{
		if ($filename === '' || $data === '')
		{
			return null;
		}

		$filepath = '';
		if ($data === null)
		{
			$filepath = $filename;
			$filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));
			$filename = end($filename);
		}

		$response = new DownloadResponse($filename, $setMime);

		if ($filepath !== '')
		{
			$response->setFilePath($filepath);
		}
		elseif ($data !== null)
		{
			$response->setBinary($data);
		}

		return $response;
	}

public function download ( string $ filename = '' , $ data = '' , bool $ setMime = false ) { if ( $ filename === '' || $ data === '' ) { return null ; } $ filepath = '' ; if ( $ data === null ) { $ filepath = $ filename ; $ filename = explode ( '/' , str_replace ( DIRECTORY_SEPARATOR , '/' , $ filename ) ) ; $ filename = end ( $ filename ) ; } $ response = new DownloadResponse ( $ filename , $ setMime ) ; if ( $ filepath !== '' ) { $ response -> setFilePath ( $ filepath ) ; } elseif ( $ data !== null ) { $ response -> setBinary ( $ data ) ; } return $ response ; }

Force a download.

Generates the headers that force a download to happen. And
sends the file to the browser.

@param string        $filename The path to the file to send
@param string|null   $data     The data to be downloaded
@param boolean       $setMime  Whether to try and send the actual MIME type

@return \CodeIgniter\HTTP\DownloadResponse|null


public static function get(string $name, bool $getShared = true)
	{
		$class = $name;
		if (($pos = strrpos($name, '\\')) !== false)
		{
			$class = substr($name, $pos + 1);
		}

		if (! $getShared)
		{
			return self::createClass($name);
		}

		if (! isset( self::$instances[$class] ))
		{
			self::$instances[$class] = self::createClass($name);
		}
		return self::$instances[$class];
	}

public static function get ( string $ name , bool $ getShared = true ) { $ class = $ name ; if ( ( $ pos = strrpos ( $ name , '\\' ) ) !== false ) { $ class = substr ( $ name , $ pos + 1 ) ; } if ( ! $ getShared ) { return self :: createClass ( $ name ) ; } if ( ! isset ( self :: $ instances [ $ class ] ) ) { self :: $ instances [ $ class ] = self :: createClass ( $ name ) ; } return self :: $ instances [ $ class ] ; }

Create new configuration instances or return
a shared instance

@param string  $name      Configuration name
@param boolean $getShared Use shared instance

@return mixed|null


private static function createClass(string $name)
	{
		if (class_exists($name))
		{
			return new $name();
		}

		$locator = Services::locator();
		$file    = $locator->locateFile($name, 'Config');

		if (empty($file))
		{
			return null;
		}

		$name = $locator->getClassname($file);

		if (empty($name))
		{
			return null;
		}

		return new $name();
	}

private static function createClass ( string $ name ) { if ( class_exists ( $ name ) ) { return new $ name ( ) ; } $ locator = Services :: locator ( ) ; $ file = $ locator -> locateFile ( $ name , 'Config' ) ; if ( empty ( $ file ) ) { return null ; } $ name = $ locator -> getClassname ( $ file ) ; if ( empty ( $ name ) ) { return null ; } return new $ name ( ) ; }

Find configuration class and create instance

@param string $name Classname

@return mixed|null


protected static function getSharedInstance(string $key, ...$params)
	{
		// Returns mock if exists
		if (isset(static::$mocks[$key]))
		{
			return static::$mocks[$key];
		}

		if (! isset(static::$instances[$key]))
		{
			// Make sure $getShared is false
			array_push($params, false);

			static::$instances[$key] = static::$key(...$params);
		}

		return static::$instances[$key];
	}

protected
static
function
getSharedInstance
(
string
$
key
,
...
$
params
)
{
// Returns mock if exists
if
(
isset
(
static
::
$
mocks
[
$
key
]
)
)
{
return
static
::
$
mocks
[
$
key
]
;
}
if
(
!
isset
(
static
::
$
instances
[
$
key
]
)
)
{
// Make sure $getShared is false
array_push
(
$
params
,
false
)
;
static
::
$
instances
[
$
key
]
=
static
::
$
key
(
...
$
params
)
;
}
return
static
::
$
instances
[
$
key
]
;
}

Returns a shared instance of any of the class' services.

$key must be a name matching a service.

@param string $key
@param array  ...$params

@return mixed

Returns a shared instance of any of the class services .


public static function autoloader(bool $getShared = true)
	{
		if ($getShared)
		{
			if (empty(static::$instances['autoloader']))
			{
				static::$instances['autoloader'] = new Autoloader();
			}

			return static::$instances['autoloader'];
		}

		return new Autoloader();
	}

public static function autoloader ( bool $ getShared = true ) { if ( $ getShared ) { if ( empty ( static :: $ instances [ 'autoloader' ] ) ) { static :: $ instances [ 'autoloader' ] = new Autoloader ( ) ; } return static :: $ instances [ 'autoloader' ] ; } return new Autoloader ( ) ; }

The Autoloader class is the central class that handles our
spl_autoload_register method, and helper methods.

@param boolean $getShared

@return \CodeIgniter\Autoloader\Autoloader

The Autoloader class is the central class that handles our spl_autoload_register method and helper methods .


public static function locator(bool $getShared = true)
	{
		if ($getShared)
		{
			if (empty(static::$instances['locator']))
			{
				static::$instances['locator'] = new FileLocator(
					static::autoloader()
				);
			}

			return static::$instances['locator'];
		}

		return new FileLocator(static::autoloader());
	}

public static function locator ( bool $ getShared = true ) { if ( $ getShared ) { if ( empty ( static :: $ instances [ 'locator' ] ) ) { static :: $ instances [ 'locator' ] = new FileLocator ( static :: autoloader ( ) ) ; } return static :: $ instances [ 'locator' ] ; } return new FileLocator ( static :: autoloader ( ) ) ; }

The file locator provides utility methods for looking for non-classes
within namespaced folders, as well as convenience methods for
loading 'helpers', and 'libraries'.

@param boolean $getShared

@return \CodeIgniter\Autoloader\FileLocator

The file locator provides utility methods for looking for non - classes within namespaced folders as well as convenience methods for loading helpers and libraries .


public static function reset(bool $init_autoloader = false)
	{
		static::$mocks = [];

		static::$instances = [];

		if ($init_autoloader)
		{
			static::autoloader()->initialize(new Autoload(), new Modules());
		}
	}

public static function reset ( bool $ init_autoloader = false ) { static :: $ mocks = [ ] ; static :: $ instances = [ ] ; if ( $ init_autoloader ) { static :: autoloader ( ) -> initialize ( new Autoload ( ) , new Modules ( ) ) ; } }

Reset shared instances and mocks for testing.

@param boolean $init_autoloader Initializes autoloader instance

Reset shared instances and mocks for testing .


public static function injectMock(string $name, $mock)
	{
		$name                 = strtolower($name);
		static::$mocks[$name] = $mock;
	}

public static function injectMock ( string $ name , $ mock ) { $ name = strtolower ( $ name ) ; static :: $ mocks [ $ name ] = $ mock ; }

Inject mock object for testing.

@param string $name
@param $mock


protected static function discoverServices(string $name, array $arguments)
	{
		if (! static::$discovered)
		{
			$config = config('Modules');

			if ($config->shouldDiscover('services'))
			{
				$locator = static::locator();
				$files   = $locator->search('Config/Services');

				if (empty($files))
				{
					// no files at all found - this would be really, really bad
					return null;
				}

				// Get instances of all service classes and cache them locally.
				foreach ($files as $file)
				{
					$classname = $locator->getClassname($file);

					if (! in_array($classname, ['CodeIgniter\\Config\\Services']))
					{
						static::$services[] = new $classname();
					}
				}
			}

			static::$discovered = true;
		}

		if (! static::$services)
		{
			// we found stuff, but no services - this would be really bad
			return null;
		}

		// Try to find the desired service method
		foreach (static::$services as $class)
		{
			if (method_exists(get_class($class), $name))
			{
				return $class::$name(...$arguments);
			}
		}

		return null;
	}

Will scan all psr4 namespaces registered with system to look
for new Config\Services files. Caches a copy of each one, then
looks for the service method in each, returning an instance of
the service, if available.

@param string $name
@param array  $arguments

@return mixed

Will scan all psr4 namespaces registered with system to look for new Config \ Services files . Caches a copy of each one then looks for the service method in each returning an instance of the service if available .


public static function input(string $prefix = null): string
	{
		if (static::$readline_support)
		{
			return readline($prefix);
		}

		echo $prefix;

		return fgets(STDIN);
	}

public static function input ( string $ prefix = null ) : string { if ( static :: $ readline_support ) { return readline ( $ prefix ) ; } echo $ prefix ; return fgets ( STDIN ) ; }

Get input from the shell, using readline or the standard STDIN

Named options must be in the following formats:
php index.php user -v --v -name=John --name=John

@param  string $prefix
@return string

@codeCoverageIgnore

Get input from the shell using readline or the standard STDIN


public static function prompt(string $field, $options = null, string $validation = null): string
	{
		$extra_output = '';
		$default      = '';

		if (is_string($options))
		{
			$extra_output = ' [' . static::color($options, 'white') . ']';
			$default      = $options;
		}

		if (is_array($options) && $options)
		{
			$opts                 = $options;
			$extra_output_default = static::color($opts[0], 'white');

			unset($opts[0]);

			if (empty($opts))
			{
				$extra_output = $extra_output_default;
			}
			else
			{
				$extra_output = ' [' . $extra_output_default . ', ' . implode(', ', $opts) . ']';
				$validation  .= '|in_list[' . implode(',', $options) . ']';
				$validation   = trim($validation, '|');
			}

			$default = $options[0];
		}

		fwrite(STDOUT, $field . $extra_output . ': ');

		// Read the input from keyboard.
		$input = trim(static::input()) ?: $default;

		if (isset($validation))
		{
			while (! static::validate($field, $input, $validation))
			{
				$input = static::prompt($field, $options, $validation);
			}
		}

		return empty($input) ? '' : $input;
	}

public
static
function
prompt
(
string
$
field
,
$
options
=
,
string
$
validation
=
)
:
string
{
$
extra_output
=
''
;
$
default
=
''
;
if
(
is_string
(
$
options
)
)
{
$
extra_output
=
' ['
.
static
::
color
(
$
options
,
'white'
)
.
']'
;
$
default
=
$
options
;
}
if
(
is_array
(
$
options
)
&&
$
options
)
{
$
opts
=
$
options
;
$
extra_output_default
=
static
::
color
(
$
opts
[
0
]
,
'white'
)
;
unset
(
$
opts
[
0
]
)
;
if
(
empty
(
$
opts
)
)
{
$
extra_output
=
$
extra_output_default
;
}
else
{
$
extra_output
=
' ['
.
$
extra_output_default
.
', '
.
implode
(
', '
,
$
opts
)
.
']'
;
$
validation
.=
'|in_list['
.
implode
(
','
,
$
options
)
.
']'
;
$
validation
=
trim
(
$
validation
,
'|'
)
;
}
$
default
=
$
options
[
0
]
;
}
fwrite
(
STDOUT
,
$
field
.
$
extra_output
.
': '
)
;
// Read the input from keyboard.
$
input
=
trim
(
static
::
input
(
)
)
:
$
default
;
if
(
isset
(
$
validation
)
)
{
while
(
!
static
::
validate
(
$
field
,
$
input
,
$
validation
)
)
{
$
input
=
static
::
prompt
(
$
field
,
$
options
,
$
validation
)
;
}
}
return
empty
(
$
input
)
''
:
$
input
;
}

Asks the user for input.

Usage:

// Takes any input
$color = CLI::prompt('What is your favorite color?');

// Takes any input, but offers default
$color = CLI::prompt('What is your favourite color?', 'white');

// Will validate options with the in_list rule and accept only if one of the list
$color = CLI::prompt('What is your favourite color?', array('red','blue'));

// Do not provide options but requires a valid email
$email = CLI::prompt('What is your email?', null, 'required|valid_email');

@param string       $field      Output "field" question
@param string|array $options    String to a default value, array to a list of options (the first option will be the default value)
@param string       $validation Validation rules

@return             string                   The user input
@codeCoverageIgnore


protected static function validate(string $field, string $value, string $rules): bool
	{
		$validation = \Config\Services::validation(null, false);
		$validation->setRule($field, null, $rules);
		$validation->run([$field => $value]);

		if ($validation->hasError($field))
		{
			static::error($validation->getError($field));

			return false;
		}

		return true;
	}

protected static function validate ( string $ field , string $ value , string $ rules ) : bool { $ validation = \ Config \ Services :: validation ( null , false ) ; $ validation -> setRule ( $ field , null , $ rules ) ; $ validation -> run ( [ $ field => $ value ] ) ; if ( $ validation -> hasError ( $ field ) ) { static :: error ( $ validation -> getError ( $ field ) ) ; return false ; } return true ; }

Validate one prompt "field" at a time

@param string $field Prompt "field" output
@param string $value Input value
@param string $rules Validation rules

@return             boolean
@codeCoverageIgnore


public static function print(string $text = '', string $foreground = null, string $background = null)
	{
		if ($foreground || $background)
		{
			$text = static::color($text, $foreground, $background);
		}

		static::$lastWrite = null;

		fwrite(STDOUT, $text);
	}

public static function print ( string $ text = '' , string $ foreground = null , string $ background = null ) { if ( $ foreground || $ background ) { $ text = static :: color ( $ text , $ foreground , $ background ) ; } static :: $ lastWrite = null ; fwrite ( STDOUT , $ text ) ; }

Outputs a string to the CLI without any surrounding newlines.
Useful for showing repeating elements on a single line.

@param string      $text
@param string|null $foreground
@param string|null $background

Outputs a string to the CLI without any surrounding newlines . Useful for showing repeating elements on a single line .


public static function error(string $text, string $foreground = 'light_red', string $background = null)
	{
		if ($foreground || $background)
		{
			$text = static::color($text, $foreground, $background);
		}

		fwrite(STDERR, $text . PHP_EOL);
	}

public static function error ( string $ text , string $ foreground = 'light_red' , string $ background = null ) { if ( $ foreground || $ background ) { $ text = static :: color ( $ text , $ foreground , $ background ) ; } fwrite ( STDERR , $ text . PHP_EOL ) ; }

Outputs an error to the CLI using STDERR instead of STDOUT

@param string|array $text       The text to output, or array of errors
@param string       $foreground
@param string       $background


public static function wait(int $seconds, bool $countdown = false)
	{
		if ($countdown === true)
		{
			$time = $seconds;

			while ($time > 0)
			{
				fwrite(STDOUT, $time . '... ');
				sleep(1);
				$time --;
			}
			static::write();
		}
		else
		{
			if ($seconds > 0)
			{
				sleep($seconds);
			}
			else
			{
				// this chunk cannot be tested because of keyboard input
				// @codeCoverageIgnoreStart
				static::write(static::$wait_msg);
				static::input();
				// @codeCoverageIgnoreEnd
			}
		}
	}

Waits a certain number of seconds, optionally showing a wait message and
waiting for a key press.

@param integer $seconds   Number of seconds
@param boolean $countdown Show a countdown or not

Waits a certain number of seconds optionally showing a wait message and waiting for a key press .


public static function color(string $text, string $foreground, string $background = null, string $format = null): string
	{
		if (static::isWindows() && ! isset($_SERVER['ANSICON']))
		{
			// @codeCoverageIgnoreStart
			return $text;
			// @codeCoverageIgnoreEnd
		}

		if (! array_key_exists($foreground, static::$foreground_colors))
		{
			throw CLIException::forInvalidColor('foreground', $foreground);
		}

		if ($background !== null && ! array_key_exists($background, static::$background_colors))
		{
			throw CLIException::forInvalidColor('background', $background);
		}

		$string = "\033[" . static::$foreground_colors[$foreground] . 'm';

		if ($background !== null)
		{
			$string .= "\033[" . static::$background_colors[$background] . 'm';
		}

		if ($format === 'underline')
		{
			$string .= "\033[4m";
		}

		$string .= $text . "\033[0m";

		return $string;
	}

public
static
function
color
(
string
$
text
,
string
$
foreground
,
string
$
background
=
,
string
$
format
=
)
:
string
{
if
(
static
::
isWindows
(
)
&&
!
isset
(
$
_SERVER
[
'ANSICON'
]
)
)
{
// @codeCoverageIgnoreStart
return
$
text
;
// @codeCoverageIgnoreEnd
}
if
(
!
array_key_exists
(
$
foreground
,
static
::
$
foreground_colors
)
)
{
throw
CLIException
::
forInvalidColor
(
'foreground'
,
$
foreground
)
;
}
if
(
$
background
!==
&&
!
array_key_exists
(
$
background
,
static
::
$
background_colors
)
)
{
throw
CLIException
::
forInvalidColor
(
'background'
,
$
background
)
;
}
$
string
=
"\033["
.
static
::
$
foreground_colors
[
$
foreground
]
.
'm'
;
if
(
$
background
!==
)
{
$
string
.=
"\033["
.
static
::
$
background_colors
[
$
background
]
.
'm'
;
}
if
(
$
format
===
'underline'
)
{
$
string
.=
"\033[4m"
;
}
$
string
.=
$
text
.
"\033[0m"
;
return
$
string
;
}

Returns the given text with the correct color codes for a foreground and
optionally a background color.

@param string $text       The text to color
@param string $foreground The foreground color
@param string $background The background color
@param string $format     Other formatting to apply. Currently only 'underline' is understood

@return string    The color coded string

Returns the given text with the correct color codes for a foreground and optionally a background color .


public static function wrap(string $string = null, int $max = 0, int $pad_left = 0): string
	{
		if (empty($string))
		{
			return '';
		}

		if ($max === 0)
		{
			$max = CLI::getWidth();
		}

		if (CLI::getWidth() < $max)
		{
			$max = CLI::getWidth();
		}

		$max = $max - $pad_left;

		$lines = wordwrap($string, $max);

		if ($pad_left > 0)
		{
			$lines = explode(PHP_EOL, $lines);

			$first = true;

			array_walk($lines, function (&$line, $index) use ($pad_left, &$first) {
				if (! $first)
				{
					$line = str_repeat(' ', $pad_left) . $line;
				}
				else
				{
					$first = false;
				}
			});

			$lines = implode(PHP_EOL, $lines);
		}

		return $lines;
	}

public
static
function
wrap
(
string
$
string
=
,
int
$
max
=
0
,
int
$
pad_left
=
0
)
:
string
{
if
(
empty
(
$
string
)
)
{
return
''
;
}
if
(
$
max
===
0
)
{
$
max
=
CLI
::
getWidth
(
)
;
}
if
(
CLI
::
getWidth
(
)
<
$
max
)
{
$
max
=
CLI
::
getWidth
(
)
;
}
$
max
=
$
max
$
pad_left
;
$
lines
=
wordwrap
(
$
string
,
$
max
)
;
if
(
$
pad_left
>
0
)
{
$
lines
=
explode
(
PHP_EOL
,
$
lines
)
;
$
first
=
true
;
array_walk
(
$
lines
,
function
(
&
$
line
,
$
index
)
use
(
$
pad_left
,
&
$
first
)
{
if
(
!
$
first
)
{
$
line
=
str_repeat
(
' '
,
$
pad_left
)
.
$
line
;
}
else
{
$
first
=
false
;
}
}
)
;
$
lines
=
implode
(
PHP_EOL
,
$
lines
)
;
}
return
$
lines
;
}

Takes a string and writes it to the command line, wrapping to a maximum
width. If no maximum width is specified, will wrap to the window's max
width.

If an int is passed into $pad_left, then all strings after the first
will padded with that many spaces to the left. Useful when printing
short descriptions that need to start on an existing line.

@param string  $string
@param integer $max
@param integer $pad_left

@return string

Takes a string and writes it to the command line wrapping to a maximum width . If no maximum width is specified will wrap to the window s max width .


public static function getOption(string $name)
	{
		if (! array_key_exists($name, static::$options))
		{
			return null;
		}

		// If the option didn't have a value, simply return TRUE
		// so they know it was set, otherwise return the actual value.
		$val = static::$options[$name] === null ? true : static::$options[$name];

		return $val;
	}

Gets a single command-line option. Returns TRUE if the option
exists, but doesn't have a value, and is simply acting as a flag.

@param string $name

@return boolean|mixed|null

Gets a single command - line option . Returns TRUE if the option exists but doesn t have a value and is simply acting as a flag .


public static function table(array $tbody, array $thead = [])
	{
		// All the rows in the table will be here until the end
		$table_rows = [];

		// We need only indexes and not keys
		if (! empty($thead))
		{
			$table_rows[] = array_values($thead);
		}

		foreach ($tbody as $tr)
		{
			$table_rows[] = array_values($tr);
		}

		// Yes, it really is necessary to know this count
		$total_rows = count($table_rows);

		// Store all columns lengths
		// $all_cols_lengths[row][column] = length
		$all_cols_lengths = [];

		// Store maximum lengths by column
		// $max_cols_lengths[column] = length
		$max_cols_lengths = [];

		// Read row by row and define the longest columns
		for ($row = 0; $row < $total_rows; $row ++)
		{
			$column = 0; // Current column index
			foreach ($table_rows[$row] as $col)
			{
				// Sets the size of this column in the current row
				$all_cols_lengths[$row][$column] = static::strlen($col);

				// If the current column does not have a value among the larger ones
				// or the value of this is greater than the existing one
				// then, now, this assumes the maximum length
				if (! isset($max_cols_lengths[$column]) || $all_cols_lengths[$row][$column] > $max_cols_lengths[$column])
				{
					$max_cols_lengths[$column] = $all_cols_lengths[$row][$column];
				}

				// We can go check the size of the next column...
				$column ++;
			}
		}

		// Read row by row and add spaces at the end of the columns
		// to match the exact column length
		for ($row = 0; $row < $total_rows; $row ++)
		{
			$column = 0;
			foreach ($table_rows[$row] as $col)
			{
				$diff = $max_cols_lengths[$column] - static::strlen($col);
				if ($diff)
				{
					$table_rows[$row][$column] = $table_rows[$row][$column] . str_repeat(' ', $diff);
				}
				$column ++;
			}
		}

		$table = '';

		// Joins columns and append the well formatted rows to the table
		for ($row = 0; $row < $total_rows; $row ++)
		{
			// Set the table border-top
			if ($row === 0)
			{
				$cols = '+';
				foreach ($table_rows[$row] as $col)
				{
					$cols .= str_repeat('-', static::strlen($col) + 2) . '+';
				}
				$table .= $cols . PHP_EOL;
			}

			// Set the columns borders
			$table .= '| ' . implode(' | ', $table_rows[$row]) . ' |' . PHP_EOL;

			// Set the thead and table borders-bottom
			if ($row === 0 && ! empty($thead) || $row + 1 === $total_rows)
			{
				$table .= $cols . PHP_EOL;
			}
		}

		fwrite(STDOUT, $table);
	}

Returns a well formatted table

@param array $tbody List of rows
@param array $thead List of columns

@return void


public function respond($data = null, int $status = null, string $message = '')
	{
		// If data is null and status code not provided, exit and bail
		if ($data === null && $status === null)
		{
			$status = 404;

			// Create the output var here in case of $this->response([]);
			$output = null;
		} // If data is null but status provided, keep the output empty.
		elseif ($data === null && is_numeric($status))
		{
			$output = null;
		}
		else
		{
			$status = empty($status) ? 200 : $status;
			$output = $this->format($data);
		}

		return $this->response->setBody($output)
						->setStatusCode($status, $message);
	}

Provides a single, simple method to return an API response, formatted
to match the requested format, with proper content-type and status code.

@param array|string|null $data
@param integer           $status
@param string            $message

@return mixed

Provides a single simple method to return an API response formatted to match the requested format with proper content - type and status code .


public function fail($messages, int $status = 400, string $code = null, string $customMessage = '')
	{
		if (! is_array($messages))
		{
			$messages = ['error' => $messages];
		}

		$response = [
			'status'   => $status,
			'error'    => $code === null ? $status : $code,
			'messages' => $messages,
		];

		return $this->respond($response, $status, $customMessage);
	}

public function fail ( $ messages , int $ status = 400 , string $ code = null , string $ customMessage = '' ) { if ( ! is_array ( $ messages ) ) { $ messages = [ 'error' => $ messages ] ; } $ response = [ 'status' => $ status , 'error' => $ code === null ? $ status : $ code , 'messages' => $ messages , ] ; return $ this -> respond ( $ response , $ status , $ customMessage ) ; }

Used for generic failures that no custom methods exist for.

@param string|array $messages
@param integer|null $status        HTTP status code
@param string|null  $code          Custom, API-specific, error code
@param string       $customMessage

@return mixed

Used for generic failures that no custom methods exist for .


public function respondCreated($data = null, string $message = '')
	{
		return $this->respond($data, $this->codes['created'], $message);
	}

public function respondCreated ( $ data = null , string $ message = '' ) { return $ this -> respond ( $ data , $ this -> codes [ 'created' ] , $ message ) ; }

Used after successfully creating a new resource.

@param mixed  $data    Data.
@param string $message Message.

@return mixed

Used after successfully creating a new resource .


public function respondDeleted($data = null, string $message = '')
	{
		return $this->respond($data, $this->codes['deleted'], $message);
	}

public function respondDeleted ( $ data = null , string $ message = '' ) { return $ this -> respond ( $ data , $ this -> codes [ 'deleted' ] , $ message ) ; }

Used after a resource has been successfully deleted.

@param mixed  $data    Data.
@param string $message Message.

@return mixed

Used after a resource has been successfully deleted .


public function failUnauthorized(string $description = 'Unauthorized', string $code = null, string $message = '')
	{
		return $this->fail($description, $this->codes['unauthorized'], $code, $message);
	}

public function failUnauthorized ( string $ description = 'Unauthorized' , string $ code = null , string $ message = '' ) { return $ this -> fail ( $ description , $ this -> codes [ 'unauthorized' ] , $ code , $ message ) ; }

Used when the client is either didn't send authorization information,
or had bad authorization credentials. User is encouraged to try again
with the proper information.

@param string $description
@param string $code
@param string $message

@return mixed

Used when the client is either didn t send authorization information or had bad authorization credentials . User is encouraged to try again with the proper information .


public function failServerError(string $description = 'Internal Server Error', string $code = null, string $message = ''): Response
	{
		return $this->fail($description, $this->codes['server_error'], $code, $message);
	}

public
function
failServerError
(
string
$
description
=
'Internal Server Error'
,
string
$
code
=
,
string
$
message
=
''
)
:
Response
{
return
$
this
->
fail
(
$
description
,
$
this
->
codes
[
'server_error'
]
,
$
code
,
$
message
)
;
}

Used when there is a server error.

@param string      $description The error message to show the user.
@param string|null $code        A custom, API-specific, error code.
@param string      $message     A custom "reason" message to return.

@return Response The value of the Response's send() method.