CI3 => CI4

This commit is contained in:
2022-11-27 14:44:55 +08:00
parent 5ae91cce8b
commit 76ba89b3b2
2075 changed files with 230044 additions and 69688 deletions
+1 -1
View File
@@ -3,4 +3,4 @@
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
</IfModule>
+362
View File
@@ -0,0 +1,362 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\API;
use CodeIgniter\Format\FormatterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;
use Config\Services;
/**
* Provides common, more readable, methods to provide
* consistent HTTP responses under a variety of common
* situations when working as an API.
*
* @property IncomingRequest $request
* @property Response $response
*/
trait ResponseTrait
{
/**
* Allows child classes to override the
* status code that is used in their API.
*
* @var array<string, int>
*/
protected $codes = [
'created' => 201,
'deleted' => 200,
'updated' => 200,
'no_content' => 204,
'invalid_request' => 400,
'unsupported_response_type' => 400,
'invalid_scope' => 400,
'temporarily_unavailable' => 400,
'invalid_grant' => 400,
'invalid_credentials' => 400,
'invalid_refresh' => 400,
'no_data' => 400,
'invalid_data' => 400,
'access_denied' => 401,
'unauthorized' => 401,
'invalid_client' => 401,
'forbidden' => 403,
'resource_not_found' => 404,
'not_acceptable' => 406,
'resource_exists' => 409,
'conflict' => 409,
'resource_gone' => 410,
'payload_too_large' => 413,
'unsupported_media_type' => 415,
'too_many_requests' => 429,
'server_error' => 500,
'unsupported_grant_type' => 501,
'not_implemented' => 501,
];
/**
* How to format the response data.
* Either 'json' or 'xml'. If blank will be
* determine through content negotiation.
*
* @var string
*/
protected $format = 'json';
/**
* Current Formatter instance. This is usually set by ResponseTrait::format
*
* @var FormatterInterface|null
*/
protected $formatter;
/**
* 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
*
* @return Response
*/
protected function respond($data = null, ?int $status = null, string $message = '')
{
if ($data === null && $status === null) {
$status = 404;
$output = null;
} elseif ($data === null && is_numeric($status)) {
$output = null;
} else {
$status = empty($status) ? 200 : $status;
$output = $this->format($data);
}
if ($output !== null) {
if ($this->format === 'json') {
return $this->response->setJSON($output)->setStatusCode($status, $message);
}
if ($this->format === 'xml') {
return $this->response->setXML($output)->setStatusCode($status, $message);
}
}
return $this->response->setBody($output)->setStatusCode($status, $message);
}
/**
* Used for generic failures that no custom methods exist for.
*
* @param array|string $messages
* @param int $status HTTP status code
* @param string|null $code Custom, API-specific, error code
*
* @return Response
*/
protected function fail($messages, int $status = 400, ?string $code = null, string $customMessage = '')
{
if (! is_array($messages)) {
$messages = ['error' => $messages];
}
$response = [
'status' => $status,
'error' => $code ?? $status,
'messages' => $messages,
];
return $this->respond($response, $status, $customMessage);
}
// --------------------------------------------------------------------
// Response Helpers
// --------------------------------------------------------------------
/**
* Used after successfully creating a new resource.
*
* @param array|string|null $data
*
* @return Response
*/
protected function respondCreated($data = null, string $message = '')
{
return $this->respond($data, $this->codes['created'], $message);
}
/**
* Used after a resource has been successfully deleted.
*
* @param array|string|null $data
*
* @return Response
*/
protected function respondDeleted($data = null, string $message = '')
{
return $this->respond($data, $this->codes['deleted'], $message);
}
/**
* Used after a resource has been successfully updated.
*
* @param array|string|null $data
*
* @return Response
*/
protected function respondUpdated($data = null, string $message = '')
{
return $this->respond($data, $this->codes['updated'], $message);
}
/**
* Used after a command has been successfully executed but there is no
* meaningful reply to send back to the client.
*
* @return Response
*/
protected function respondNoContent(string $message = 'No Content')
{
return $this->respond(null, $this->codes['no_content'], $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.
*
* @return Response
*/
protected function failUnauthorized(string $description = 'Unauthorized', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['unauthorized'], $code, $message);
}
/**
* Used when access is always denied to this resource and no amount
* of trying again will help.
*
* @return Response
*/
protected function failForbidden(string $description = 'Forbidden', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['forbidden'], $code, $message);
}
/**
* Used when a specified resource cannot be found.
*
* @return Response
*/
protected function failNotFound(string $description = 'Not Found', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_not_found'], $code, $message);
}
/**
* Used when the data provided by the client cannot be validated.
*
* @return Response
*
* @deprecated Use failValidationErrors instead
*/
protected function failValidationError(string $description = 'Bad Request', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['invalid_data'], $code, $message);
}
/**
* Used when the data provided by the client cannot be validated on one or more fields.
*
* @param string|string[] $errors
*
* @return Response
*/
protected function failValidationErrors($errors, ?string $code = null, string $message = '')
{
return $this->fail($errors, $this->codes['invalid_data'], $code, $message);
}
/**
* Use when trying to create a new resource and it already exists.
*
* @return Response
*/
protected function failResourceExists(string $description = 'Conflict', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_exists'], $code, $message);
}
/**
* Use when a resource was previously deleted. This is different than
* Not Found, because here we know the data previously existed, but is now gone,
* where Not Found means we simply cannot find any information about it.
*
* @return Response
*/
protected function failResourceGone(string $description = 'Gone', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_gone'], $code, $message);
}
/**
* Used when the user has made too many requests for the resource recently.
*
* @return Response
*/
protected function failTooManyRequests(string $description = 'Too Many Requests', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['too_many_requests'], $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.
*/
protected function failServerError(string $description = 'Internal Server Error', ?string $code = null, string $message = ''): Response
{
return $this->fail($description, $this->codes['server_error'], $code, $message);
}
// --------------------------------------------------------------------
// Utility Methods
// --------------------------------------------------------------------
/**
* Handles formatting a response. Currently makes some heavy assumptions
* and needs updating! :)
*
* @param array|string|null $data
*
* @return string|null
*/
protected function format($data = null)
{
// If the data is a string, there's not much we can do to it...
if (is_string($data)) {
// The content type should be text/... and not application/...
$contentType = $this->response->getHeaderLine('Content-Type');
$contentType = str_replace('application/json', 'text/html', $contentType);
$contentType = str_replace('application/', 'text/', $contentType);
$this->response->setContentType($contentType);
$this->format = 'html';
return $data;
}
$format = Services::format();
$mime = "application/{$this->format}";
// Determine correct response type through content negotiation if not explicitly declared
if (
(empty($this->format) || ! in_array($this->format, ['json', 'xml'], true))
&& $this->request instanceof IncomingRequest
) {
$mime = $this->request->negotiate(
'media',
$format->getConfig()->supportedResponseFormats,
false
);
}
$this->response->setContentType($mime);
// if we don't have a formatter, make one
if (! isset($this->formatter)) {
// if no formatter, use the default
$this->formatter = $format->getFormatter($mime);
}
if ($mime !== 'application/json') {
// Recursively convert objects into associative arrays
// Conversion not required for JSONFormatter
$data = json_decode(json_encode($data), true);
}
return $this->formatter->format($data);
}
/**
* Sets the format the response should be in.
*
* @return $this
*/
protected function setResponseFormat(?string $format = null)
{
$this->format = strtolower($format);
return $this;
}
}
+374
View File
@@ -0,0 +1,374 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
use Composer\Autoload\ClassLoader;
use Config\Autoload;
use Config\Modules;
use InvalidArgumentException;
/**
* An autoloader that uses both PSR4 autoloading, and traditional classmaps.
*
* Given a foo-bar package of classes in the file system at the following paths:
* ```
* /path/to/packages/foo-bar/
* /src
* Baz.php # Foo\Bar\Baz
* Qux/
* Quux.php # Foo\Bar\Qux\Quux
* ```
* you can add the path to the configuration array that is passed in the constructor.
* The Config array consists of 2 primary keys, both of which are associative arrays:
* 'psr4', and 'classmap'.
* ```
* $Config = [
* 'psr4' => [
* 'Foo\Bar' => '/path/to/packages/foo-bar'
* ],
* 'classmap' => [
* 'MyClass' => '/path/to/class/file.php'
* ]
* ];
* ```
* Example:
* ```
* <?php
* // our configuration array
* $Config = [ ... ];
* $loader = new \CodeIgniter\Autoloader\Autoloader($Config);
*
* // register the autoloader
* $loader->register();
* ```
*/
class Autoloader
{
/**
* Stores namespaces as key, and path as values.
*
* @var array<string, array<string>>
*/
protected $prefixes = [];
/**
* Stores class name as key, and path as values.
*
* @var array<string, string>
*/
protected $classmap = [];
/**
* Stores files as a list.
*
* @var array<int, string>
*/
protected $files = [];
/**
* Reads in the configuration array (described above) and stores
* the valid parts that we'll need.
*
* @return $this
*/
public function initialize(Autoload $config, Modules $modules)
{
$this->prefixes = [];
$this->classmap = [];
$this->files = [];
// We have to have one or the other, though we don't enforce the need
// to have both present in order to work.
if (empty($config->psr4) && empty($config->classmap)) {
throw new InvalidArgumentException('Config array must contain either the \'psr4\' key or the \'classmap\' key.');
}
if (isset($config->psr4)) {
$this->addNamespace($config->psr4);
}
if (isset($config->classmap)) {
$this->classmap = $config->classmap;
}
if (isset($config->files)) {
$this->files = $config->files;
}
if (is_file(COMPOSER_PATH)) {
$this->loadComposerInfo($modules);
}
return $this;
}
private function loadComposerInfo(Modules $modules): void
{
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$this->loadComposerClassmap($composer);
// Should we load through Composer's namespaces, also?
if ($modules->discoverInComposer) {
$this->loadComposerNamespaces($composer);
}
unset($composer);
}
/**
* Register the loader with the SPL autoloader stack.
*/
public function register()
{
// Prepend the PSR4 autoloader for maximum performance.
spl_autoload_register([$this, 'loadClass'], true, true);
// Now prepend another loader for the files in our class map.
spl_autoload_register([$this, 'loadClassmap'], true, true);
// Load our non-class files
foreach ($this->files as $file) {
$this->includeFile($file);
}
}
/**
* Registers namespaces with the autoloader.
*
* @param array|string $namespace
*
* @return $this
*/
public function addNamespace($namespace, ?string $path = null)
{
if (is_array($namespace)) {
foreach ($namespace as $prefix => $namespacedPath) {
$prefix = trim($prefix, '\\');
if (is_array($namespacedPath)) {
foreach ($namespacedPath as $dir) {
$this->prefixes[$prefix][] = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR;
}
continue;
}
$this->prefixes[$prefix][] = rtrim($namespacedPath, '\\/') . DIRECTORY_SEPARATOR;
}
} else {
$this->prefixes[trim($namespace, '\\')][] = rtrim($path, '\\/') . DIRECTORY_SEPARATOR;
}
return $this;
}
/**
* Get namespaces with prefixes as keys and paths as values.
*
* If a prefix param is set, returns only paths to the given prefix.
*
* @return array
*/
public function getNamespace(?string $prefix = null)
{
if ($prefix === null) {
return $this->prefixes;
}
return $this->prefixes[trim($prefix, '\\')] ?? [];
}
/**
* Removes a single namespace from the psr4 settings.
*
* @return $this
*/
public function removeNamespace(string $namespace)
{
if (isset($this->prefixes[trim($namespace, '\\')])) {
unset($this->prefixes[trim($namespace, '\\')]);
}
return $this;
}
/**
* Load a class using available class mapping.
*
* @return false|string
*/
public function loadClassmap(string $class)
{
$file = $this->classmap[$class] ?? '';
if (is_string($file) && $file !== '') {
return $this->includeFile($file);
}
return false;
}
/**
* Loads the class file for a given class name.
*
* @param string $class The fully qualified class name.
*
* @return false|string The mapped file on success, or boolean false
* on failure.
*/
public function loadClass(string $class)
{
$class = trim($class, '\\');
$class = str_ireplace('.php', '', $class);
return $this->loadInNamespace($class);
}
/**
* Loads the class file for a given class name.
*
* @param string $class The fully-qualified class name
*
* @return false|string The mapped file name on success, or boolean false on fail
*/
protected function loadInNamespace(string $class)
{
if (strpos($class, '\\') === false) {
return false;
}
foreach ($this->prefixes as $namespace => $directories) {
foreach ($directories as $directory) {
$directory = rtrim($directory, '\\/');
if (strpos($class, $namespace) === 0) {
$filePath = $directory . str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($namespace))) . '.php';
$filename = $this->includeFile($filePath);
if ($filename) {
return $filename;
}
}
}
}
// never found a mapped file
return false;
}
/**
* A central way to include a file. Split out primarily for testing purposes.
*
* @return false|string The filename on success, false if the file is not loaded
*/
protected function includeFile(string $file)
{
$file = $this->sanitizeFilename($file);
if (is_file($file)) {
include_once $file;
return $file;
}
return false;
}
/**
* Sanitizes a filename, replacing spaces with dashes.
*
* Removes special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trim period, dash and underscore from beginning
* and end of filename.
*
* @return string The sanitized filename
*/
public function sanitizeFilename(string $filename): string
{
// Only allow characters deemed safe for POSIX portable filenames.
// Plus the forward slash for directory separators since this might be a path.
// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_278
// Modified to allow backslash and colons for on Windows machines.
$filename = preg_replace('/[^0-9\p{L}\s\/\-\_\.\:\\\\]/u', '', $filename);
// Clean up our filename edges.
return trim($filename, '.-_');
}
private function loadComposerNamespaces(ClassLoader $composer): void
{
$paths = $composer->getPrefixesPsr4();
// Get rid of CodeIgniter so we don't have duplicates
if (isset($paths['CodeIgniter\\'])) {
unset($paths['CodeIgniter\\']);
}
$newPaths = [];
foreach ($paths as $key => $value) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($key, '\\ ')] = $value;
}
$this->addNamespace($newPaths);
}
private function loadComposerClassmap(ClassLoader $composer): void
{
$classes = $composer->getClassMap();
$this->classmap = array_merge($this->classmap, $classes);
}
/**
* Locates autoload information from Composer, if available.
*
* @deprecated No longer used.
*/
protected function discoverComposerNamespaces()
{
if (! is_file(COMPOSER_PATH)) {
return;
}
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$paths = $composer->getPrefixesPsr4();
$classes = $composer->getClassMap();
unset($composer);
// Get rid of CodeIgniter so we don't have duplicates
if (isset($paths['CodeIgniter\\'])) {
unset($paths['CodeIgniter\\']);
}
$newPaths = [];
foreach ($paths as $key => $value) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($key, '\\ ')] = $value;
}
$this->prefixes = array_merge($this->prefixes, $newPaths);
$this->classmap = array_merge($this->classmap, $classes);
}
}
+373
View File
@@ -0,0 +1,373 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
/**
* Allows loading non-class files in a namespaced manner.
* Works with Helpers, Views, etc.
*/
class FileLocator
{
/**
* The Autoloader to use.
*
* @var Autoloader
*/
protected $autoloader;
public function __construct(Autoloader $autoloader)
{
$this->autoloader = $autoloader;
}
/**
* 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|null $folder The folder within the namespace that we should look for the file.
* @param string $ext The file extension the file should have.
*
* @return false|string The path to the file, or false if not found.
*/
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) && 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, '/', '\\');
$file = ltrim($file, '\\');
$segments = explode('\\', $file);
// The first segment will be empty if a slash started the filename.
if (empty($segments[0])) {
unset($segments[0]);
}
$paths = [];
$filename = '';
// Namespaces always comes with arrays of paths
$namespaces = $this->autoloader->getNamespace();
foreach (array_keys($namespaces) as $namespace) {
if (substr($file, 0, strlen($namespace)) === $namespace) {
// There may be sub-namespaces of the same vendor,
// so overwrite them with namespaces found later.
$paths = $namespaces[$namespace];
$fileWithoutNamespace = substr($file, strlen($namespace));
$filename = ltrim(str_replace('\\', '/', $fileWithoutNamespace), '/');
}
}
// if no namespaces matched then quit
if (empty($paths)) {
return false;
}
// Check each path in the namespace
foreach ($paths as $path) {
// Ensure trailing slash
$path = rtrim($path, '/') . '/';
// 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) {
$path .= trim($folder, '/') . '/';
}
$path .= $filename;
if (is_file($path)) {
return $path;
}
}
return false;
}
/**
* Examines a file and returns the fully qualified class name.
*/
public function getClassname(string $file): string
{
$php = file_get_contents($file);
$tokens = token_get_all($php);
$dlm = false;
$namespace = '';
$className = '';
foreach ($tokens as $i => $token) {
if ($i < 2) {
continue;
}
if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $token[0] === T_STRING)) {
if (! $dlm) {
$namespace = 0;
}
if (isset($token[1])) {
$namespace = $namespace ? $namespace . '\\' . $token[1] : $token[1];
$dlm = true;
}
} elseif ($dlm && ($token[0] !== T_NS_SEPARATOR) && ($token[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
&& $token[0] === T_STRING) {
$className = $token[1];
break;
}
}
if (empty($className)) {
return '';
}
return $namespace . '\\' . $className;
}
/**
* 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',
* ]
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
$path = $this->ensureExt($path, $ext);
$foundPaths = [];
$appPaths = [];
foreach ($this->getNamespaces() as $namespace) {
if (isset($namespace['path']) && is_file($namespace['path'] . $path)) {
$fullPath = $namespace['path'] . $path;
$fullPath = realpath($fullPath) ?: $fullPath;
if ($prioritizeApp) {
$foundPaths[] = $fullPath;
} elseif (strpos($fullPath, APPPATH) === 0) {
$appPaths[] = $fullPath;
} else {
$foundPaths[] = $fullPath;
}
}
}
if (! $prioritizeApp && ! empty($appPaths)) {
$foundPaths = [...$foundPaths, ...$appPaths];
}
// Remove any duplicates
return array_unique($foundPaths);
}
/**
* Ensures a extension is at the end of a filename
*/
protected function ensureExt(string $path, string $ext): string
{
if ($ext) {
$ext = '.' . $ext;
if (substr($path, -strlen($ext)) !== $ext) {
$path .= $ext;
}
}
return $path;
}
/**
* Return the namespace mappings we know about.
*
* @return array<int, array<string, string>>
*/
protected function getNamespaces()
{
$namespaces = [];
// Save system for last
$system = [];
foreach ($this->autoloader->getNamespace() as $prefix => $paths) {
foreach ($paths as $path) {
if ($prefix === 'CodeIgniter') {
$system = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
continue;
}
$namespaces[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
}
}
$namespaces[] = $system;
return $namespaces;
}
/**
* Find the qualified name of a file according to
* the namespace of the first matched namespace path.
*
* @return false|string The qualified name or false if the path is not found
*/
public function findQualifiedNameFromPath(string $path)
{
$path = realpath($path) ?: $path;
if (! is_file($path)) {
return false;
}
foreach ($this->getNamespaces() as $namespace) {
$namespace['path'] = realpath($namespace['path']) ?: $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);
// Check if this exists
if (class_exists($className)) {
return $className;
}
}
}
return false;
}
/**
* Scans the defined namespaces, returning a list of all files
* that are contained within the subpath specified by $path.
*
* @return string[] List of file paths
*/
public function listFiles(string $path): array
{
if (empty($path)) {
return [];
}
$files = [];
helper('filesystem');
foreach ($this->getNamespaces() as $namespace) {
$fullPath = $namespace['path'] . $path;
$fullPath = realpath($fullPath) ?: $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if (! empty($tempFiles)) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Scans the provided namespace, returning a list of all files
* that are contained within the sub path specified by $path.
*
* @return string[] List of file paths
*/
public function listNamespaceFiles(string $prefix, string $path): array
{
if (empty($path) || empty($prefix)) {
return [];
}
$files = [];
helper('filesystem');
// autoloader->getNamespace($prefix) returns an array of paths for that namespace
foreach ($this->autoloader->getNamespace($prefix) as $namespacePath) {
$fullPath = rtrim($namespacePath, '/') . '/' . $path;
$fullPath = realpath($fullPath) ?: $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if (! empty($tempFiles)) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Checks the app folder to see if the file can be found.
* Only for use with filenames that DO NOT include namespacing.
*
* @return false|string The path to the file, or false if not found.
*/
protected function legacyLocate(string $file, ?string $folder = null)
{
$path = APPPATH . (empty($folder) ? $file : $folder . '/' . $file);
$path = realpath($path) ?: $path;
if (is_file($path)) {
return $path;
}
return false;
}
}
File diff suppressed because it is too large Load Diff
+220
View File
@@ -0,0 +1,220 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use Psr\Log\LoggerInterface;
use ReflectionException;
use Throwable;
/**
* BaseCommand is the base class used in creating CLI commands.
*
* @property array $arguments
* @property Commands $commands
* @property string $description
* @property string $group
* @property LoggerInterface $logger
* @property string $name
* @property array $options
* @property string $usage
*/
abstract class BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group;
/**
* The Command's name
*
* @var string
*/
protected $name;
/**
* the Command's usage description
*
* @var string
*/
protected $usage;
/**
* the Command's short description
*
* @var string
*/
protected $description;
/**
* the Command's options description
*
* @var array
*/
protected $options = [];
/**
* the Command's Arguments description
*
* @var array
*/
protected $arguments = [];
/**
* The Logger to use for a command
*
* @var LoggerInterface
*/
protected $logger;
/**
* Instance of Commands so
* commands can call other commands.
*
* @var Commands
*/
protected $commands;
public function __construct(LoggerInterface $logger, Commands $commands)
{
$this->logger = $logger;
$this->commands = $commands;
}
/**
* Actually execute a command.
*
* @param array<int|string, string|null> $params
*/
abstract public function run(array $params);
/**
* Can be used by a command to run other commands.
*
* @return mixed
*
* @throws ReflectionException
*/
protected function call(string $command, array $params = [])
{
return $this->commands->run($command, $params);
}
/**
* A simple method to display an error with line/file, in child commands.
*/
protected function showError(Throwable $e)
{
$exception = $e;
$message = $e->getMessage();
$config = config('Exceptions');
require $config->errorViewPath . '/cli/error_exception.php';
}
/**
* Show Help includes (Usage, Arguments, Description, Options).
*/
public function showHelp()
{
CLI::write(lang('CLI.helpUsage'), 'yellow');
if (! empty($this->usage)) {
$usage = $this->usage;
} else {
$usage = $this->name;
if (! empty($this->arguments)) {
$usage .= ' [arguments]';
}
}
CLI::write($this->setPad($usage, 0, 0, 2));
if (! empty($this->description)) {
CLI::newLine();
CLI::write(lang('CLI.helpDescription'), 'yellow');
CLI::write($this->setPad($this->description, 0, 0, 2));
}
if (! empty($this->arguments)) {
CLI::newLine();
CLI::write(lang('CLI.helpArguments'), 'yellow');
$length = max(array_map('strlen', array_keys($this->arguments)));
foreach ($this->arguments as $argument => $description) {
CLI::write(CLI::color($this->setPad($argument, $length, 2, 2), 'green') . $description);
}
}
if (! empty($this->options)) {
CLI::newLine();
CLI::write(lang('CLI.helpOptions'), 'yellow');
$length = max(array_map('strlen', array_keys($this->options)));
foreach ($this->options as $option => $description) {
CLI::write(CLI::color($this->setPad($option, $length, 2, 2), 'green') . $description);
}
}
}
/**
* Pads our string out so that all titles are the same length to nicely line up descriptions.
*
* @param int $extra How many extra spaces to add at the end
*/
public function setPad(string $item, int $max, int $extra = 2, int $indent = 0): string
{
$max += $extra + $indent;
return str_pad(str_repeat(' ', $indent) . $item, $max);
}
/**
* Get pad for $key => $value array output
*
* @deprecated Use setPad() instead.
*
* @codeCoverageIgnore
*/
public function getPad(array $array, int $pad): int
{
$max = 0;
foreach (array_keys($array) as $key) {
$max = max($max, strlen($key));
}
return $max + $pad;
}
/**
* Makes it simple to access our protected properties.
*
* @return mixed
*/
public function __get(string $key)
{
return $this->{$key} ?? null;
}
/**
* Makes it simple to check our protected properties.
*/
public function __isset(string $key): bool
{
return isset($this->{$key});
}
}
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\Controller;
use Config\Services;
use ReflectionException;
/**
* Command runner
*/
class CommandRunner extends Controller
{
/**
* Instance of class managing the collection of commands
*
* @var Commands
*/
protected $commands;
/**
* Constructor
*/
public function __construct()
{
$this->commands = Services::commands();
}
/**
* We map all un-routed CLI methods through this function
* so we have the chance to look for a Command first.
*
* @param string $method
* @param array $params
*
* @return mixed
*
* @throws ReflectionException
*/
public function _remap($method, $params)
{
return $this->index($params);
}
/**
* Default command.
*
* @return mixed
*
* @throws ReflectionException
*/
public function index(array $params)
{
$command = array_shift($params) ?? 'list';
return $this->commands->run($command, $params);
}
/**
* Allows access to the current commands that have been found.
*/
public function getCommands(): array
{
return $this->commands->getCommands();
}
}
+181
View File
@@ -0,0 +1,181 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\Autoloader\FileLocator;
use CodeIgniter\Log\Logger;
use ReflectionClass;
use ReflectionException;
/**
* Core functionality for running, listing, etc commands.
*/
class Commands
{
/**
* The found commands.
*
* @var array
*/
protected $commands = [];
/**
* Logger instance.
*
* @var Logger
*/
protected $logger;
/**
* Constructor
*
* @param Logger|null $logger
*/
public function __construct($logger = null)
{
$this->logger = $logger ?? service('logger');
$this->discoverCommands();
}
/**
* Runs a command given
*/
public function run(string $command, array $params)
{
if (! $this->verifyCommand($command, $this->commands)) {
return;
}
// The file would have already been loaded during the
// createCommandList function...
$className = $this->commands[$command]['class'];
$class = new $className($this->logger, $this);
return $class->run($params);
}
/**
* Provide access to the list of commands.
*
* @return array
*/
public function getCommands()
{
return $this->commands;
}
/**
* Discovers all commands in the framework and within user code,
* and collects instances of them to work with.
*/
public function discoverCommands()
{
if ($this->commands !== []) {
return;
}
/** @var FileLocator $locator */
$locator = service('locator');
$files = $locator->listFiles('Commands/');
// If no matching command files were found, bail
// This should never happen in unit testing.
if ($files === []) {
return; // @codeCoverageIgnore
}
// Loop over each file checking to see if a command with that
// alias exists in the class.
foreach ($files as $file) {
$className = $locator->getClassname($file);
if ($className === '' || ! class_exists($className)) {
continue;
}
try {
$class = new ReflectionClass($className);
if (! $class->isInstantiable() || ! $class->isSubclassOf(BaseCommand::class)) {
continue;
}
/** @var BaseCommand $class */
$class = new $className($this->logger, $this);
if (isset($class->group)) {
$this->commands[$class->name] = [
'class' => $className,
'file' => $file,
'group' => $class->group,
'description' => $class->description,
];
}
unset($class);
} catch (ReflectionException $e) {
$this->logger->error($e->getMessage());
}
}
asort($this->commands);
}
/**
* Verifies if the command being sought is found
* in the commands list.
*/
public function verifyCommand(string $command, array $commands): bool
{
if (isset($commands[$command])) {
return true;
}
$message = lang('CLI.commandNotFound', [$command]);
if ($alternatives = $this->getCommandAlternatives($command, $commands)) {
if (count($alternatives) === 1) {
$message .= "\n\n" . lang('CLI.altCommandSingular') . "\n ";
} else {
$message .= "\n\n" . lang('CLI.altCommandPlural') . "\n ";
}
$message .= implode("\n ", $alternatives);
}
CLI::error($message);
CLI::newLine();
return false;
}
/**
* Finds alternative of `$name` among collection
* of commands.
*/
protected function getCommandAlternatives(string $name, array $collection): array
{
$alternatives = [];
foreach (array_keys($collection) as $commandName) {
$lev = levenshtein($name, $commandName);
if ($lev <= strlen($commandName) / 3 || strpos($commandName, $name) !== false) {
$alternatives[$commandName] = $lev;
}
}
ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);
return array_keys($alternatives);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\CodeIgniter;
use Exception;
/**
* Console
*/
class Console
{
/**
* Main CodeIgniter instance.
*
* @var CodeIgniter
*/
protected $app;
public function __construct(CodeIgniter $app)
{
$this->app = $app;
}
/**
* Runs the current command discovered on the CLI.
*
* @return mixed
*
* @throws Exception
*/
public function run(bool $useSafeOutput = false)
{
$path = CLI::getURI() ?: 'list';
// Set the path for the application to route to.
$this->app->setPath("ci{$path}");
return $this->app->useSafeOutput($useSafeOutput)->run();
}
/**
* Displays basic information about the Console.
*/
public function showHeader(bool $suppress = false)
{
if ($suppress) {
return;
}
CLI::write(sprintf('CodeIgniter v%s Command Line Tool - Server Time: %s UTC%s', CodeIgniter::CI_VERSION, date('Y-m-d H:i:s'), date('P')), 'green');
CLI::newLine();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use RuntimeException;
/**
* CLIException
*/
class CLIException extends RuntimeException
{
use DebugTraceableTrait;
/**
* Thrown when `$color` specified for `$type` is not within the
* allowed list of colors.
*
* @return CLIException
*/
public static function forInvalidColor(string $type, string $color)
{
return new static(lang('CLI.invalidColor', [$type, $color]));
}
}
+352
View File
@@ -0,0 +1,352 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use Config\Services;
use Throwable;
/**
* GeneratorTrait contains a collection of methods
* to build the commands that generates a file.
*/
trait GeneratorTrait
{
/**
* Component Name
*
* @var string
*/
protected $component;
/**
* File directory
*
* @var string
*/
protected $directory;
/**
* View template name
*
* @var string
*/
protected $template;
/**
* Language string key for required class names.
*
* @var string
*/
protected $classNameLang = '';
/**
* Whether to require class name.
*
* @internal
*
* @var bool
*/
private $hasClassName = true;
/**
* Whether to sort class imports.
*
* @internal
*
* @var bool
*/
private $sortImports = true;
/**
* Whether the `--suffix` option has any effect.
*
* @internal
*
* @var bool
*/
private $enabledSuffixing = true;
/**
* The params array for easy access by other methods.
*
* @internal
*
* @var array
*/
private $params = [];
/**
* Execute the command.
*/
protected function execute(array $params): void
{
$this->params = $params;
if ($this->getOption('namespace') === 'CodeIgniter') {
// @codeCoverageIgnoreStart
CLI::write(lang('CLI.generator.usingCINamespace'), 'yellow');
CLI::newLine();
if (CLI::prompt('Are you sure you want to continue?', ['y', 'n'], 'required') === 'n') {
CLI::newLine();
CLI::write(lang('CLI.generator.cancelOperation'), 'yellow');
CLI::newLine();
return;
}
CLI::newLine();
// @codeCoverageIgnoreEnd
}
// Get the fully qualified class name from the input.
$class = $this->qualifyClassName();
// Get the file path from class name.
$path = $this->buildPath($class);
// Check if path is empty.
if (empty($path)) {
return;
}
$isFile = is_file($path);
// Overwriting files unknowingly is a serious annoyance, So we'll check if
// we are duplicating things, If 'force' option is not supplied, we bail.
if (! $this->getOption('force') && $isFile) {
CLI::error(lang('CLI.generator.fileExist', [clean_path($path)]), 'light_gray', 'red');
CLI::newLine();
return;
}
// Check if the directory to save the file is existing.
$dir = dirname($path);
if (! is_dir($dir)) {
mkdir($dir, 0755, true);
}
helper('filesystem');
// Build the class based on the details we have, We'll be getting our file
// contents from the template, and then we'll do the necessary replacements.
if (! write_file($path, $this->buildContent($class))) {
// @codeCoverageIgnoreStart
CLI::error(lang('CLI.generator.fileError', [clean_path($path)]), 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
if ($this->getOption('force') && $isFile) {
CLI::write(lang('CLI.generator.fileOverwrite', [clean_path($path)]), 'yellow');
CLI::newLine();
return;
}
CLI::write(lang('CLI.generator.fileCreate', [clean_path($path)]), 'green');
CLI::newLine();
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
return $this->parseTemplate($class);
}
/**
* Change file basename before saving.
*
* Useful for components where the file name has a date.
*/
protected function basename(string $filename): string
{
return basename($filename);
}
/**
* Parses the class name and checks if it is already qualified.
*/
protected function qualifyClassName(): string
{
// Gets the class name from input.
$class = $this->params[0] ?? CLI::getSegment(2);
if ($class === null && $this->hasClassName) {
// @codeCoverageIgnoreStart
$nameLang = $this->classNameLang ?: 'CLI.generator.className.default';
$class = CLI::prompt(lang($nameLang), null, 'required');
CLI::newLine();
// @codeCoverageIgnoreEnd
}
helper('inflector');
$component = singular($this->component);
/**
* @see https://regex101.com/r/a5KNCR/1
*/
$pattern = sprintf('/([a-z][a-z0-9_\/\\\\]+)(%s)/i', $component);
if (preg_match($pattern, $class, $matches) === 1) {
$class = $matches[1] . ucfirst($matches[2]);
}
if ($this->enabledSuffixing && $this->getOption('suffix') && ! strripos($class, $component)) {
$class .= ucfirst($component);
}
// Trims input, normalize separators, and ensure that all paths are in Pascalcase.
$class = ltrim(implode('\\', array_map('pascalize', explode('\\', str_replace('/', '\\', trim($class))))), '\\/');
// Gets the namespace from input. Don't forget the ending backslash!
$namespace = trim(str_replace('/', '\\', $this->getOption('namespace') ?? APP_NAMESPACE), '\\') . '\\';
if (strncmp($class, $namespace, strlen($namespace)) === 0) {
return $class; // @codeCoverageIgnore
}
return $namespace . $this->directory . '\\' . str_replace('/', '\\', $class);
}
/**
* Gets the generator view as defined in the `Config\Generators::$views`,
* with fallback to `$template` when the defined view does not exist.
*/
protected function renderTemplate(array $data = []): string
{
try {
return view(config('Generators')->views[$this->name], $data, ['debug' => false]);
} catch (Throwable $e) {
log_message('error', (string) $e);
return view("CodeIgniter\\Commands\\Generators\\Views\\{$this->template}", $data, ['debug' => false]);
}
}
/**
* Performs pseudo-variables contained within view file.
*/
protected function parseTemplate(string $class, array $search = [], array $replace = [], array $data = []): string
{
// Retrieves the namespace part from the fully qualified class name.
$namespace = trim(implode('\\', array_slice(explode('\\', $class), 0, -1)), '\\');
$search[] = '<@php';
$search[] = '{namespace}';
$search[] = '{class}';
$replace[] = '<?php';
$replace[] = $namespace;
$replace[] = str_replace($namespace . '\\', '', $class);
return str_replace($search, $replace, $this->renderTemplate($data));
}
/**
* Builds the contents for class being generated, doing all
* the replacements necessary, and alphabetically sorts the
* imports for a given template.
*/
protected function buildContent(string $class): string
{
$template = $this->prepare($class);
if ($this->sortImports && preg_match('/(?P<imports>(?:^use [^;]+;$\n?)+)/m', $template, $match)) {
$imports = explode("\n", trim($match['imports']));
sort($imports);
return str_replace(trim($match['imports']), implode("\n", $imports), $template);
}
return $template;
}
/**
* Builds the file path from the class name.
*/
protected function buildPath(string $class): string
{
$namespace = trim(str_replace('/', '\\', $this->getOption('namespace') ?? APP_NAMESPACE), '\\');
// Check if the namespace is actually defined and we are not just typing gibberish.
$base = Services::autoloader()->getNamespace($namespace);
if (! $base = reset($base)) {
CLI::error(lang('CLI.namespaceNotDefined', [$namespace]), 'light_gray', 'red');
CLI::newLine();
return '';
}
$base = realpath($base) ?: $base;
$file = $base . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, trim(str_replace($namespace . '\\', '', $class), '\\')) . '.php';
return implode(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $file), 0, -1)) . DIRECTORY_SEPARATOR . $this->basename($file);
}
/**
* Allows child generators to modify the internal `$hasClassName` flag.
*
* @return $this
*/
protected function setHasClassName(bool $hasClassName)
{
$this->hasClassName = $hasClassName;
return $this;
}
/**
* Allows child generators to modify the internal `$sortImports` flag.
*
* @return $this
*/
protected function setSortImports(bool $sortImports)
{
$this->sortImports = $sortImports;
return $this;
}
/**
* Allows child generators to modify the internal `$enabledSuffixing` flag.
*
* @return $this
*/
protected function setEnabledSuffixing(bool $enabledSuffixing)
{
$this->enabledSuffixing = $enabledSuffixing;
return $this;
}
/**
* 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.
*
* @return mixed
*/
protected function getOption(string $name)
{
if (! array_key_exists($name, $this->params)) {
return CLI::getOption($name);
}
return $this->params[$name] ?? true;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache;
use CodeIgniter\Cache\Exceptions\CacheException;
use CodeIgniter\Exceptions\CriticalError;
use CodeIgniter\Test\Mock\MockCache;
use Config\Cache;
/**
* A factory for loading the desired
*/
class CacheFactory
{
/**
* The class to use when mocking
*
* @var string
*/
public static $mockClass = MockCache::class;
/**
* The service to inject the mock as
*
* @var string
*/
public static $mockServiceName = 'cache';
/**
* Attempts to create the desired cache handler, based upon the
*
* @return CacheInterface
*/
public static function getHandler(Cache $config, ?string $handler = null, ?string $backup = null)
{
if (! isset($config->validHandlers) || ! is_array($config->validHandlers)) {
throw CacheException::forInvalidHandlers();
}
if (! isset($config->handler) || ! isset($config->backupHandler)) {
throw CacheException::forNoBackup();
}
$handler = ! empty($handler) ? $handler : $config->handler;
$backup = ! empty($backup) ? $backup : $config->backupHandler;
if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) {
throw CacheException::forHandlerNotFound();
}
$adapter = new $config->validHandlers[$handler]($config);
if (! $adapter->isSupported()) {
$adapter = new $config->validHandlers[$backup]($config);
if (! $adapter->isSupported()) {
// Fall back to the dummy adapter.
$adapter = new $config->validHandlers['dummy']();
}
}
// If $adapter->initialization throws a CriticalError exception, we will attempt to
// use the $backup handler, if that also fails, we resort to the dummy handler.
try {
$adapter->initialize();
} catch (CriticalError $e) {
log_message('critical', $e . ' Resorting to using ' . $backup . ' handler.');
// get the next best cache handler (or dummy if the $backup also fails)
$adapter = self::getHandler($config, $backup, 'dummy');
}
return $adapter;
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache;
/**
* Cache interface
*/
interface CacheInterface
{
/**
* Takes care of any handler-specific setup that must be done.
*/
public function initialize();
/**
* Attempts to fetch an item from the cache store.
*
* @param string $key Cache item name
*
* @return mixed
*/
public function get(string $key);
/**
* Saves an item to the cache store.
*
* @param string $key Cache item name
* @param mixed $value The data to save
* @param int $ttl Time To Live, in seconds (default 60)
*
* @return bool Success or failure
*/
public function save(string $key, $value, int $ttl = 60);
/**
* Deletes a specific item from the cache store.
*
* @param string $key Cache item name
*
* @return bool Success or failure
*/
public function delete(string $key);
/**
* Performs atomic incrementation of a raw stored value.
*
* @param string $key Cache ID
* @param int $offset Step/value to increase by
*
* @return mixed
*/
public function increment(string $key, int $offset = 1);
/**
* Performs atomic decrementation of a raw stored value.
*
* @param string $key Cache ID
* @param int $offset Step/value to increase by
*
* @return mixed
*/
public function decrement(string $key, int $offset = 1);
/**
* Will delete all items in the entire cache.
*
* @return bool Success or failure
*/
public function clean();
/**
* Returns information on the entire cache.
*
* The information returned and the structure of the data
* varies depending on the handler.
*
* @return mixed
*/
public function getCacheInfo();
/**
* Returns detailed information about the specific item in the cache.
*
* @param string $key Cache item name.
*
* @return array|false|null
* Returns null if the item does not exist, otherwise array<string, mixed>
* with at least the 'expire' key for absolute epoch expiry (or null).
* Some handlers may return false when an item does not exist, which is deprecated.
*/
public function getMetaData(string $key);
/**
* Determines if the driver is supported on this system.
*/
public function isSupported(): bool;
}
@@ -0,0 +1,64 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\ExceptionInterface;
use RuntimeException;
/**
* CacheException
*/
class CacheException extends RuntimeException implements ExceptionInterface
{
use DebugTraceableTrait;
/**
* Thrown when handler has no permission to write cache.
*
* @return CacheException
*/
public static function forUnableToWrite(string $path)
{
return new static(lang('Cache.unableToWrite', [$path]));
}
/**
* Thrown when an unrecognized handler is used.
*
* @return CacheException
*/
public static function forInvalidHandlers()
{
return new static(lang('Cache.invalidHandlers'));
}
/**
* Thrown when no backup handler is setup in config.
*
* @return CacheException
*/
public static function forNoBackup()
{
return new static(lang('Cache.noBackup'));
}
/**
* Thrown when specified handler was not found.
*
* @return CacheException
*/
public static function forHandlerNotFound()
{
return new static(lang('Cache.handlerNotFound'));
}
}
@@ -0,0 +1,24 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all framework-related exceptions.
*
* catch (\CodeIgniter\Cache\Exceptions\ExceptionInterface) { ... }
*
* @deprecated 4.1.2
*/
interface ExceptionInterface
{
}
@@ -0,0 +1,106 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use Closure;
use CodeIgniter\Cache\CacheInterface;
use Exception;
use InvalidArgumentException;
/**
* Base class for cache handling
*/
abstract class BaseHandler implements CacheInterface
{
/**
* Reserved characters that cannot be used in a key or tag. May be overridden by the config.
* From https://github.com/symfony/cache-contracts/blob/c0446463729b89dd4fa62e9aeecc80287323615d/ItemInterface.php#L43
*
* @deprecated in favor of the Cache config
*/
public const RESERVED_CHARACTERS = '{}()/\@:';
/**
* Maximum key length.
*/
public const MAX_KEY_LENGTH = PHP_INT_MAX;
/**
* Prefix to apply to cache keys.
* May not be used by all handlers.
*
* @var string
*/
protected $prefix;
/**
* Validates a cache key according to PSR-6.
* Keys that exceed MAX_KEY_LENGTH are hashed.
* From https://github.com/symfony/cache/blob/7b024c6726af21fd4984ac8d1eae2b9f3d90de88/CacheItem.php#L158
*
* @param string $key The key to validate
* @param string $prefix Optional prefix to include in length calculations
*
* @throws InvalidArgumentException When $key is not valid
*/
public static function validateKey($key, $prefix = ''): string
{
if (! is_string($key)) {
throw new InvalidArgumentException('Cache key must be a string');
}
if ($key === '') {
throw new InvalidArgumentException('Cache key cannot be empty.');
}
$reserved = config('Cache')->reservedCharacters ?? self::RESERVED_CHARACTERS;
if ($reserved && strpbrk($key, $reserved) !== false) {
throw new InvalidArgumentException('Cache key contains reserved characters ' . $reserved);
}
// If the key with prefix exceeds the length then return the hashed version
return strlen($prefix . $key) > static::MAX_KEY_LENGTH ? $prefix . md5($key) : $prefix . $key;
}
/**
* Get an item from the cache, or execute the given Closure and store the result.
*
* @param string $key Cache item name
* @param int $ttl Time to live
* @param Closure $callback Callback return value
*
* @return mixed
*/
public function remember(string $key, int $ttl, Closure $callback)
{
$value = $this->get($key);
if ($value !== null) {
return $value;
}
$this->save($key, $value = $callback(), $ttl);
return $value;
}
/**
* Deletes items from the cache store matching a given pattern.
*
* @param string $pattern Cache items glob-style pattern
*
* @throws Exception
*/
public function deleteMatching(string $pattern)
{
throw new Exception('The deleteMatching method is not implemented.');
}
}
@@ -0,0 +1,115 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use Closure;
/**
* Dummy cache handler
*/
class DummyHandler extends BaseHandler
{
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
return null;
}
/**
* {@inheritDoc}
*/
public function remember(string $key, int $ttl, Closure $callback)
{
return null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
return true;
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
return 0;
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
return true;
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return true;
}
/**
* {@inheritDoc}
*/
public function clean()
{
return true;
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return null;
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return true;
}
}
@@ -0,0 +1,423 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use CodeIgniter\Cache\Exceptions\CacheException;
use Config\Cache;
use Throwable;
/**
* File system cache handler
*/
class FileHandler extends BaseHandler
{
/**
* Maximum key length.
*/
public const MAX_KEY_LENGTH = 255;
/**
* Where to store cached files on the disk.
*
* @var string
*/
protected $path;
/**
* Mode for the stored files.
* Must be chmod-safe (octal).
*
* @var int
*
* @see https://www.php.net/manual/en/function.chmod.php
*/
protected $mode;
/**
* @throws CacheException
*/
public function __construct(Cache $config)
{
if (! property_exists($config, 'file')) {
$config->file = [
'storePath' => $config->storePath ?? WRITEPATH . 'cache',
'mode' => 0640,
];
}
$this->path = ! empty($config->file['storePath']) ? $config->file['storePath'] : WRITEPATH . 'cache';
$this->path = rtrim($this->path, '/') . '/';
if (! is_really_writable($this->path)) {
throw CacheException::forUnableToWrite($this->path);
}
$this->mode = $config->file['mode'] ?? 0640;
$this->prefix = $config->prefix;
}
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->getItem($key);
return is_array($data) ? $data['data'] : null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
$contents = [
'time' => time(),
'ttl' => $ttl,
'data' => $value,
];
if ($this->writeFile($this->path . $key, serialize($contents))) {
try {
chmod($this->path . $key, $this->mode);
// @codeCoverageIgnoreStart
} catch (Throwable $e) {
log_message('debug', 'Failed to set mode on cache file: ' . $e);
// @codeCoverageIgnoreEnd
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return is_file($this->path . $key) && unlink($this->path . $key);
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
$deleted = 0;
foreach (glob($this->path . $pattern, GLOB_NOSORT) as $filename) {
if (is_file($filename) && @unlink($filename)) {
$deleted++;
}
}
return $deleted;
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->getItem($key);
if ($data === false) {
$data = [
'data' => 0,
'ttl' => 60,
];
} elseif (! is_int($data['data'])) {
return false;
}
$newValue = $data['data'] + $offset;
return $this->save($key, $newValue, $data['ttl']) ? $newValue : false;
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->getItem($key);
if ($data === false) {
$data = [
'data' => 0,
'ttl' => 60,
];
} elseif (! is_int($data['data'])) {
return false;
}
$newValue = $data['data'] - $offset;
return $this->save($key, $newValue, $data['ttl']) ? $newValue : false;
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->deleteFiles($this->path, false, true);
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->getDirFileInfo($this->path);
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
if (false === $data = $this->getItem($key)) {
return false; // @TODO This will return null in a future release
}
return [
'expire' => $data['ttl'] > 0 ? $data['time'] + $data['ttl'] : null,
'mtime' => filemtime($this->path . $key),
'data' => $data['data'],
];
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return is_writable($this->path);
}
/**
* Does the heavy lifting of actually retrieving the file and
* verifying it's age.
*
* @return mixed
*/
protected function getItem(string $filename)
{
if (! is_file($this->path . $filename)) {
return false;
}
$data = @unserialize(file_get_contents($this->path . $filename));
if (! is_array($data) || ! isset($data['ttl'])) {
return false;
}
if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl']) {
// If the file is still there then try to remove it
if (is_file($this->path . $filename)) {
@unlink($this->path . $filename);
}
return false;
}
return $data;
}
/**
* Writes a file to disk, or returns false if not successful.
*
* @param string $path
* @param string $data
* @param string $mode
*
* @return bool
*/
protected function writeFile($path, $data, $mode = 'wb')
{
if (($fp = @fopen($path, $mode)) === false) {
return false;
}
flock($fp, LOCK_EX);
for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result) {
if (($result = fwrite($fp, substr($data, $written))) === false) {
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
return is_int($result);
}
/**
* Deletes all files contained in the supplied directory path.
* Files must be writable or owned by the system in order to be deleted.
* If the second parameter is set to TRUE, any directories contained
* within the supplied base directory will be nuked as well.
*
* @param string $path File path
* @param bool $delDir Whether to delete any directories found in the path
* @param bool $htdocs Whether to skip deleting .htaccess and index page files
* @param int $_level Current directory depth level (default: 0; internal use only)
*/
protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool
{
// Trim the trailing slash
$path = rtrim($path, '/\\');
if (! $currentDir = @opendir($path)) {
return false;
}
while (false !== ($filename = @readdir($currentDir))) {
if ($filename !== '.' && $filename !== '..') {
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
} elseif ($htdocs !== true || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
@unlink($path . DIRECTORY_SEPARATOR . $filename);
}
}
}
closedir($currentDir);
return ($delDir === true && $_level > 0) ? @rmdir($path) : true;
}
/**
* Reads the specified directory and builds an array containing the filenames,
* filesize, dates, and permissions
*
* Any sub-folders contained within the specified path are read as well.
*
* @param string $sourceDir Path to source
* @param bool $topLevelOnly Look only at the top level directory specified?
* @param bool $_recursion Internal variable to determine recursion status - do not use in calls
*
* @return array|false
*/
protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false)
{
static $_filedata = [];
$relativePath = $sourceDir;
if ($fp = @opendir($sourceDir)) {
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === false) {
$_filedata = [];
$sourceDir = rtrim(realpath($sourceDir) ?: $sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
// Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast
while (false !== ($file = readdir($fp))) {
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
$this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
} elseif ($file[0] !== '.') {
$_filedata[$file] = $this->getFileInfo($sourceDir . $file);
$_filedata[$file]['relative_path'] = $relativePath;
}
}
closedir($fp);
return $_filedata;
}
return false;
}
/**
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
*
* @param string $file Path to file
* @param mixed $returnedValues Array or comma separated string of information returned
*
* @return array|false
*/
protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
{
if (! is_file($file)) {
return false;
}
if (is_string($returnedValues)) {
$returnedValues = explode(',', $returnedValues);
}
$fileInfo = [];
foreach ($returnedValues as $key) {
switch ($key) {
case 'name':
$fileInfo['name'] = basename($file);
break;
case 'server_path':
$fileInfo['server_path'] = $file;
break;
case 'size':
$fileInfo['size'] = filesize($file);
break;
case 'date':
$fileInfo['date'] = filemtime($file);
break;
case 'readable':
$fileInfo['readable'] = is_readable($file);
break;
case 'writable':
$fileInfo['writable'] = is_writable($file);
break;
case 'executable':
$fileInfo['executable'] = is_executable($file);
break;
case 'fileperms':
$fileInfo['fileperms'] = fileperms($file);
break;
}
}
return $fileInfo;
}
}
@@ -0,0 +1,267 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use CodeIgniter\Exceptions\CriticalError;
use Config\Cache;
use Exception;
use Memcache;
use Memcached;
/**
* Mamcached cache handler
*/
class MemcachedHandler extends BaseHandler
{
/**
* The memcached object
*
* @var Memcache|Memcached
*/
protected $memcached;
/**
* Memcached Configuration
*
* @var array
*/
protected $config = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
$this->config = array_merge($this->config, $config->memcached);
}
/**
* Closes the connection to Memcache(d) if present.
*/
public function __destruct()
{
if ($this->memcached instanceof Memcached) {
$this->memcached->quit();
} elseif ($this->memcached instanceof Memcache) {
$this->memcached->close();
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
try {
if (class_exists(Memcached::class)) {
// Create new instance of Memcached
$this->memcached = new Memcached();
if ($this->config['raw']) {
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
}
// Add server
$this->memcached->addServer(
$this->config['host'],
$this->config['port'],
$this->config['weight']
);
// attempt to get status of servers
$stats = $this->memcached->getStats();
// $stats should be an associate array with a key in the format of host:port.
// If it doesn't have the key, we know the server is not working as expected.
if (! isset($stats[$this->config['host'] . ':' . $this->config['port']])) {
throw new CriticalError('Cache: Memcached connection failed.');
}
} elseif (class_exists(Memcache::class)) {
// Create new instance of Memcache
$this->memcached = new Memcache();
// Check if we can connect to the server
$canConnect = $this->memcached->connect(
$this->config['host'],
$this->config['port']
);
// If we can't connect, throw a CriticalError exception
if ($canConnect === false) {
throw new CriticalError('Cache: Memcache connection failed.');
}
// Add server, third parameter is persistence and defaults to TRUE.
$this->memcached->addServer(
$this->config['host'],
$this->config['port'],
true,
$this->config['weight']
);
} else {
throw new CriticalError('Cache: Not support Memcache(d) extension.');
}
} catch (Exception $e) {
throw new CriticalError('Cache: Memcache(d) connection refused (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
if ($this->memcached instanceof Memcached) {
$data = $this->memcached->get($key);
// check for unmatched key
if ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
return null;
}
} elseif ($this->memcached instanceof Memcache) {
$flags = false;
$data = $this->memcached->get($key, $flags);
// check for unmatched key (i.e. $flags is untouched)
if ($flags === false) {
return null;
}
}
return is_array($data) ? $data[0] : $data;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
if (! $this->config['raw']) {
$value = [
$value,
time(),
$ttl,
];
}
if ($this->memcached instanceof Memcached) {
return $this->memcached->set($key, $value, $ttl);
}
if ($this->memcached instanceof Memcache) {
return $this->memcached->set($key, $value, 0, $ttl);
}
return false;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return $this->memcached->delete($key);
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
throw new Exception('The deleteMatching method is not implemented for Memcached. You must select File, Redis or Predis handlers to use it.');
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
if (! $this->config['raw']) {
return false;
}
$key = static::validateKey($key, $this->prefix);
return $this->memcached->increment($key, $offset, $offset, 60);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
if (! $this->config['raw']) {
return false;
}
$key = static::validateKey($key, $this->prefix);
// FIXME: third parameter isn't other handler actions.
return $this->memcached->decrement($key, $offset, $offset, 60);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->memcached->flush();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->memcached->getStats();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
$stored = $this->memcached->get($key);
// if not an array, don't try to count for PHP7.2
if (! is_array($stored) || count($stored) !== 3) {
return false; // @TODO This will return null in a future release
}
[$data, $time, $limit] = $stored;
return [
'expire' => $limit > 0 ? $time + $limit : null,
'mtime' => $time,
'data' => $data,
];
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('memcached') || extension_loaded('memcache');
}
}
@@ -0,0 +1,227 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use CodeIgniter\Exceptions\CriticalError;
use Config\Cache;
use Exception;
use Predis\Client;
use Predis\Collection\Iterator\Keyspace;
/**
* Predis cache handler
*/
class PredisHandler extends BaseHandler
{
/**
* Default config
*
* @var array
*/
protected $config = [
'scheme' => 'tcp',
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
];
/**
* Predis connection
*
* @var Client
*/
protected $redis;
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
if (isset($config->redis)) {
$this->config = array_merge($this->config, $config->redis);
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
try {
$this->redis = new Client($this->config, ['prefix' => $this->prefix]);
$this->redis->time();
} catch (Exception $e) {
throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key);
$data = array_combine(
['__ci_type', '__ci_value'],
$this->redis->hmget($key, ['__ci_type', '__ci_value'])
);
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
return null;
}
switch ($data['__ci_type']) {
case 'array':
case 'object':
return unserialize($data['__ci_value']);
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
return settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null;
case 'resource':
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key);
switch ($dataType = gettype($value)) {
case 'array':
case 'object':
$value = serialize($value);
break;
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
break;
case 'resource':
default:
return false;
}
if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
return false;
}
if ($ttl) {
$this->redis->expireat($key, time() + $ttl);
}
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key);
return $this->redis->del($key) === 1;
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
$matchedKeys = [];
foreach (new Keyspace($this->redis, $pattern) as $key) {
$matchedKeys[] = $key;
}
return $this->redis->del($matchedKeys);
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key);
return $this->redis->hincrby($key, 'data', $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
$key = static::validateKey($key);
return $this->redis->hincrby($key, 'data', -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->redis->flushdb()->getPayload() === 'OK';
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->redis->info();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key);
$data = array_combine(['__ci_value'], $this->redis->hmget($key, ['__ci_value']));
if (isset($data['__ci_value']) && $data['__ci_value'] !== false) {
$time = time();
$ttl = $this->redis->ttl($key);
return [
'expire' => $ttl > 0 ? time() + $ttl : null,
'mtime' => $time,
'data' => $data['__ci_value'],
];
}
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return class_exists(Client::class);
}
}
@@ -0,0 +1,259 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use CodeIgniter\Exceptions\CriticalError;
use Config\Cache;
use Redis;
use RedisException;
/**
* Redis cache handler
*/
class RedisHandler extends BaseHandler
{
/**
* Default config
*
* @var array
*/
protected $config = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
/**
* Redis connection
*
* @var Redis
*/
protected $redis;
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
$this->config = array_merge($this->config, $config->redis);
}
/**
* Closes the connection to Redis if present.
*/
public function __destruct()
{
if (isset($this->redis)) {
$this->redis->close();
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
$config = $this->config;
$this->redis = new Redis();
try {
// Note:: If Redis is your primary cache choice, and it is "offline", every page load will end up been delayed by the timeout duration.
// I feel like some sort of temporary flag should be set, to indicate that we think Redis is "offline", allowing us to bypass the timeout for a set period of time.
if (! $this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
// Note:: I'm unsure if log_message() is necessary, however I'm not 100% comfortable removing it.
log_message('error', 'Cache: Redis connection failed. Check your configuration.');
throw new CriticalError('Cache: Redis connection failed. Check your configuration.');
}
if (isset($config['password']) && ! $this->redis->auth($config['password'])) {
log_message('error', 'Cache: Redis authentication failed.');
throw new CriticalError('Cache: Redis authentication failed.');
}
if (isset($config['database']) && ! $this->redis->select($config['database'])) {
log_message('error', 'Cache: Redis select database failed.');
throw new CriticalError('Cache: Redis select database failed.');
}
} catch (RedisException $e) {
throw new CriticalError('Cache: RedisException occurred with message (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->redis->hMGet($key, ['__ci_type', '__ci_value']);
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
return null;
}
switch ($data['__ci_type']) {
case 'array':
case 'object':
return unserialize($data['__ci_value']);
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
return settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null;
case 'resource':
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
switch ($dataType = gettype($value)) {
case 'array':
case 'object':
$value = serialize($value);
break;
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
break;
case 'resource':
default:
return false;
}
if (! $this->redis->hMSet($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
return false;
}
if ($ttl) {
$this->redis->expireAt($key, time() + $ttl);
}
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return $this->redis->del($key) === 1;
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
$matchedKeys = [];
$iterator = null;
do {
// Scan for some keys
$keys = $this->redis->scan($iterator, $pattern);
// Redis may return empty results, so protect against that
if ($keys !== false) {
foreach ($keys as $key) {
$matchedKeys[] = $key;
}
}
} while ($iterator > 0);
return $this->redis->del($matchedKeys);
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return $this->redis->hIncrBy($key, '__ci_value', $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return $this->increment($key, -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->redis->flushDB();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->redis->info();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
$value = $this->get($key);
if ($value !== null) {
$time = time();
$ttl = $this->redis->ttl($key);
return [
'expire' => $ttl > 0 ? time() + $ttl : null,
'mtime' => $time,
'data' => $value,
];
}
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('redis');
}
}
@@ -0,0 +1,144 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use Config\Cache;
use Exception;
/**
* Cache handler for WinCache from Microsoft & IIS.
*
* @codeCoverageIgnore
*/
class WincacheHandler extends BaseHandler
{
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
}
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$success = false;
$data = wincache_ucache_get($key, $success);
// Success returned by reference from wincache_ucache_get()
return $success ? $data : null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_set($key, $value, $ttl);
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_delete($key);
}
/**
* {@inheritDoc}
*/
public function deleteMatching(string $pattern)
{
throw new Exception('The deleteMatching method is not implemented for Wincache. You must select File, Redis or Predis handlers to use it.');
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_inc($key, $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_dec($key, $offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return wincache_ucache_clear();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return wincache_ucache_info(true);
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
if ($stored = wincache_ucache_info(false, $key)) {
$age = $stored['ucache_entries'][1]['age_seconds'];
$ttl = $stored['ucache_entries'][1]['ttl_seconds'];
$hitcount = $stored['ucache_entries'][1]['hitcount'];
return [
'expire' => $ttl > 0 ? time() + $ttl : null,
'hitcount' => $hitcount,
'age' => $age,
'ttl' => $ttl,
];
}
return false; // @TODO This will return null in a future release
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('wincache') && ini_get('wincache.ucenabled');
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,87 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Cache;
use CodeIgniter\Cache\CacheFactory;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* Clears current cache.
*/
class ClearCache extends BaseCommand
{
/**
* Command grouping.
*
* @var string
*/
protected $group = 'Cache';
/**
* The Command's name
*
* @var string
*/
protected $name = 'cache:clear';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Clears the current system caches.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'cache:clear [<driver>]';
/**
* the Command's Arguments
*
* @var array
*/
protected $arguments = [
'driver' => 'The cache driver to use',
];
/**
* Clears the cache
*/
public function run(array $params)
{
$config = config('Cache');
$handler = $params[0] ?? $config->handler;
if (! array_key_exists($handler, $config->validHandlers)) {
CLI::error($handler . ' is not a valid cache handler.');
return;
}
$config->handler = $handler;
$cache = CacheFactory::getHandler($config);
if (! $cache->clean()) {
// @codeCoverageIgnoreStart
CLI::error('Error while clearing the cache.');
return;
// @codeCoverageIgnoreEnd
}
CLI::write(CLI::color('Cache cleared.', 'green'));
}
}
@@ -0,0 +1,88 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Cache;
use CodeIgniter\Cache\CacheFactory;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\I18n\Time;
/**
* Shows information on the cache.
*/
class InfoCache extends BaseCommand
{
/**
* Command grouping.
*
* @var string
*/
protected $group = 'Cache';
/**
* The Command's name
*
* @var string
*/
protected $name = 'cache:info';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Shows file cache information in the current system.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'cache:info';
/**
* Clears the cache
*/
public function run(array $params)
{
$config = config('Cache');
helper('number');
if ($config->handler !== 'file') {
CLI::error('This command only supports the file cache handler.');
return;
}
$cache = CacheFactory::getHandler($config);
$caches = $cache->getCacheInfo();
$tbody = [];
foreach ($caches as $key => $field) {
$tbody[] = [
$key,
clean_path($field['server_path']),
number_to_size($field['size']),
Time::createFromTimestamp($field['date']),
];
}
$thead = [
CLI::color('Name', 'green'),
CLI::color('Server Path', 'green'),
CLI::color('Size', 'green'),
CLI::color('Date', 'green'),
];
CLI::table($tbody, $thead);
}
}
@@ -0,0 +1,155 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\Factories;
use CodeIgniter\Database\SQLite3\Connection;
use Config\Database;
use Throwable;
/**
* Creates a new database.
*/
class CreateDatabase extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'db:create';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Create a new database schema.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'db:create <db_name> [options]';
/**
* The Command's arguments
*
* @var array<string, string>
*/
protected $arguments = [
'db_name' => 'The database name to use',
];
/**
* The Command's options
*
* @var array<string, string>
*/
protected $options = [
'--ext' => 'File extension of the database file for SQLite3. Can be `db` or `sqlite`. Defaults to `db`.',
];
/**
* Creates a new database.
*/
public function run(array $params)
{
$name = array_shift($params);
if (empty($name)) {
$name = CLI::prompt('Database name', null, 'required'); // @codeCoverageIgnore
}
try {
/**
* @var Database $config
*/
$config = config('Database');
// Set to an empty database to prevent connection errors.
$group = ENVIRONMENT === 'testing' ? 'tests' : $config->defaultGroup;
$config->{$group}['database'] = '';
$db = Database::connect();
// Special SQLite3 handling
if ($db instanceof Connection) {
$ext = $params['ext'] ?? CLI::getOption('ext') ?? 'db';
if (! in_array($ext, ['db', 'sqlite'], true)) {
$ext = CLI::prompt('Please choose a valid file extension', ['db', 'sqlite']); // @codeCoverageIgnore
}
if ($name !== ':memory:') {
$name = str_replace(['.db', '.sqlite'], '', $name) . ".{$ext}";
}
$config->{$group}['DBDriver'] = 'SQLite3';
$config->{$group}['database'] = $name;
if ($name !== ':memory:') {
$dbName = strpos($name, DIRECTORY_SEPARATOR) === false ? WRITEPATH . $name : $name;
if (is_file($dbName)) {
CLI::error("Database \"{$dbName}\" already exists.", 'light_gray', 'red');
CLI::newLine();
return;
}
unset($dbName);
}
// Connect to new SQLite3 to create new database
$db = Database::connect(null, false);
$db->connect();
if (! is_file($db->getDatabase()) && $name !== ':memory:') {
// @codeCoverageIgnoreStart
CLI::error('Database creation failed.', 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
} elseif (! Database::forge()->createDatabase($name)) {
// @codeCoverageIgnoreStart
CLI::error('Database creation failed.', 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
CLI::write("Database \"{$name}\" successfully created.", 'green');
CLI::newLine();
} catch (Throwable $e) {
$this->showError($e);
} finally {
// Reset the altered config no matter what happens.
Factories::reset('config');
}
}
}
@@ -0,0 +1,102 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Services;
use Throwable;
/**
* Runs all new migrations.
*/
class Migrate extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'migrate';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Locates and runs all new migrations against the database.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'migrate [options]';
/**
* the Command's Options
*
* @var array
*/
protected $options = [
'-n' => 'Set migration namespace',
'-g' => 'Set database group',
'--all' => 'Set for all namespaces, will ignore (-n) option',
];
/**
* Ensures that all migrations have been run.
*/
public function run(array $params)
{
$runner = Services::migrations();
$runner->clearCliMessages();
CLI::write(lang('Migrations.latest'), 'yellow');
$namespace = $params['n'] ?? CLI::getOption('n');
$group = $params['g'] ?? CLI::getOption('g');
try {
if (array_key_exists('all', $params) || CLI::getOption('all')) {
$runner->setNamespace(null);
} elseif ($namespace) {
$runner->setNamespace($namespace);
}
if (! $runner->latest($group)) {
CLI::error(lang('Migrations.generalFault'), 'light_gray', 'red'); // @codeCoverageIgnore
}
$messages = $runner->getCliMessages();
foreach ($messages as $message) {
CLI::write($message);
}
CLI::write(lang('Migrations.migrated'), 'green');
// @codeCoverageIgnoreStart
} catch (Throwable $e) {
$this->showError($e);
// @codeCoverageIgnoreEnd
}
}
}
@@ -0,0 +1,87 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* Does a rollback followed by a latest to refresh the current state
* of the database.
*/
class MigrateRefresh extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'migrate:refresh';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Does a rollback followed by a latest to refresh the current state of the database.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'migrate:refresh [options]';
/**
* the Command's Options
*
* @var array
*/
protected $options = [
'-n' => 'Set migration namespace',
'-g' => 'Set database group',
'--all' => 'Set latest for all namespace, will ignore (-n) option',
'-f' => 'Force command - this option allows you to bypass the confirmation question when running this command in a production environment',
];
/**
* Does a rollback followed by a latest to refresh the current state
* of the database.
*/
public function run(array $params)
{
$params['b'] = 0;
if (ENVIRONMENT === 'production') {
// @codeCoverageIgnoreStart
$force = array_key_exists('f', $params) || CLI::getOption('f');
if (! $force && CLI::prompt(lang('Migrations.refreshConfirm'), ['y', 'n']) === 'n') {
return;
}
$params['f'] = null;
// @codeCoverageIgnoreEnd
}
$this->call('migrate:rollback', $params);
$this->call('migrate', $params);
}
}
@@ -0,0 +1,110 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Services;
use Throwable;
/**
* Runs all of the migrations in reverse order, until they have
* all been unapplied.
*/
class MigrateRollback extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'migrate:rollback';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Runs the "down" method for all migrations in the last batch.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'migrate:rollback [options]';
/**
* the Command's Options
*
* @var array
*/
protected $options = [
'-b' => 'Specify a batch to roll back to; e.g. "3" to return to batch #3 or "-2" to roll back twice',
'-g' => 'Set database group',
'-f' => 'Force command - this option allows you to bypass the confirmation question when running this command in a production environment',
];
/**
* Runs all of the migrations in reverse order, until they have
* all been unapplied.
*/
public function run(array $params)
{
if (ENVIRONMENT === 'production') {
// @codeCoverageIgnoreStart
$force = array_key_exists('f', $params) || CLI::getOption('f');
if (! $force && CLI::prompt(lang('Migrations.rollBackConfirm'), ['y', 'n']) === 'n') {
return;
}
// @codeCoverageIgnoreEnd
}
$runner = Services::migrations();
$group = $params['g'] ?? CLI::getOption('g');
if (is_string($group)) {
$runner->setGroup($group);
}
try {
$batch = $params['b'] ?? CLI::getOption('b') ?? $runner->getLastBatch() - 1;
CLI::write(lang('Migrations.rollingBack') . ' ' . $batch, 'yellow');
if (! $runner->regress($batch)) {
CLI::error(lang('Migrations.generalFault'), 'light_gray', 'red'); // @codeCoverageIgnore
}
$messages = $runner->getCliMessages();
foreach ($messages as $message) {
CLI::write($message);
}
CLI::write('Done rolling back migrations.', 'green');
// @codeCoverageIgnoreStart
} catch (Throwable $e) {
$this->showError($e);
// @codeCoverageIgnoreEnd
}
}
}
@@ -0,0 +1,165 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Services;
/**
* Displays a list of all migrations and whether they've been run or not.
*/
class MigrateStatus extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'migrate:status';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Displays a list of all migrations and whether they\'ve been run or not.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'migrate:status [options]';
/**
* the Command's Options
*
* @var array<string, string>
*/
protected $options = [
'-g' => 'Set database group',
];
/**
* Namespaces to ignore when looking for migrations.
*
* @var string[]
*/
protected $ignoredNamespaces = [
'CodeIgniter',
'Config',
'Kint',
'Laminas\ZendFrameworkBridge',
'Laminas\Escaper',
'Psr\Log',
];
/**
* Displays a list of all migrations and whether they've been run or not.
*
* @param array<string, mixed> $params
*/
public function run(array $params)
{
$runner = Services::migrations();
$paramGroup = $params['g'] ?? CLI::getOption('g');
// Get all namespaces
$namespaces = Services::autoloader()->getNamespace();
// Collection of migration status
$status = [];
foreach (array_keys($namespaces) as $namespace) {
if (ENVIRONMENT !== 'testing') {
// Make Tests\\Support discoverable for testing
$this->ignoredNamespaces[] = 'Tests\Support'; // @codeCoverageIgnore
}
if (in_array($namespace, $this->ignoredNamespaces, true)) {
continue;
}
if (APP_NAMESPACE !== 'App' && $namespace === 'App') {
continue; // @codeCoverageIgnore
}
$migrations = $runner->findNamespaceMigrations($namespace);
if (empty($migrations)) {
continue;
}
$runner->setNamespace($namespace);
$history = $runner->getHistory((string) $paramGroup);
ksort($migrations);
foreach ($migrations as $uid => $migration) {
$migrations[$uid]->name = mb_substr($migration->name, mb_strpos($migration->name, $uid . '_'));
$date = '---';
$group = '---';
$batch = '---';
foreach ($history as $row) {
// @codeCoverageIgnoreStart
if ($runner->getObjectUid($row) !== $migration->uid) {
continue;
}
$date = date('Y-m-d H:i:s', $row->time);
$group = $row->group;
$batch = $row->batch;
// @codeCoverageIgnoreEnd
}
$status[] = [
$namespace,
$migration->version,
$migration->name,
$group,
$date,
$batch,
];
}
}
if (! $status) {
// @codeCoverageIgnoreStart
CLI::error(lang('Migrations.noneFound'), 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
$headers = [
CLI::color(lang('Migrations.namespace'), 'yellow'),
CLI::color(lang('Migrations.version'), 'yellow'),
CLI::color(lang('Migrations.filename'), 'yellow'),
CLI::color(lang('Migrations.group'), 'yellow'),
CLI::color(str_replace(': ', '', lang('Migrations.on')), 'yellow'),
CLI::color(lang('Migrations.batch'), 'yellow'),
];
CLI::table($status, $headers);
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Database\Seeder;
use Config\Database;
use Throwable;
/**
* Runs the specified Seeder file to populate the database
* with some data.
*/
class Seed extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'db:seed';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Runs the specified seeder to populate known data into the database.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'db:seed <seeder_name>';
/**
* the Command's Arguments
*
* @var array<string, string>
*/
protected $arguments = [
'seeder_name' => 'The seeder name to run',
];
/**
* Passes to Seeder to populate the database.
*/
public function run(array $params)
{
$seeder = new Seeder(new Database());
$seedName = array_shift($params);
if (empty($seedName)) {
$seedName = CLI::prompt(lang('Migrations.migSeeder'), null, 'required'); // @codeCoverageIgnore
}
try {
$seeder->call($seedName);
} catch (Throwable $e) {
$this->showError($e);
}
}
}
@@ -0,0 +1,283 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
/**
* Get table data if it exists in the database.
*/
class ShowTableInfo extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'db:table';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Retrieves information on the selected table.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = <<<'EOL'
db:table [<table_name>] [options]
Examples:
db:table --show
db:table --metadata
db:table my_table --metadata
db:table my_table
db:table my_table --limit-rows 5 --limit-field-value 10 --desc
EOL;
/**
* The Command's arguments
*
* @var array<string, string>
*/
protected $arguments = [
'table_name' => 'The table name to show info',
];
/**
* The Command's options
*
* @var array<string, string>
*/
protected $options = [
'--show' => 'Lists the names of all database tables.',
'--metadata' => 'Retrieves list containing field information.',
'--desc' => 'Sorts the table rows in DESC order.',
'--limit-rows' => 'Limits the number of rows. Default: 10.',
'--limit-field-value' => 'Limits the length of field values. Default: 15.',
];
/**
* @phpstan-var list<list<string|int>> Table Data.
*/
private array $tbody;
private BaseConnection $db;
/**
* @var bool Sort the table rows in DESC order or not.
*/
private bool $sortDesc = false;
private string $DBPrefix;
public function run(array $params)
{
$this->db = Database::connect();
$this->DBPrefix = $this->db->getPrefix();
$tables = $this->db->listTables();
if (array_key_exists('desc', $params)) {
$this->sortDesc = true;
}
if ($tables === []) {
CLI::error('Database has no tables!', 'light_gray', 'red');
CLI::newLine();
return;
}
if (array_key_exists('show', $params)) {
$this->showAllTables($tables);
return;
}
$tableName = $params[0] ?? null;
$limitRows = (int) ($params['limit-rows'] ?? 10);
$limitFieldValue = (int) ($params['limit-field-value'] ?? 15);
if (! in_array($tableName, $tables, true)) {
$tableNameNo = CLI::promptByKey(
['Here is the list of your database tables:', 'Which table do you want to see?'],
$tables,
'required'
);
CLI::newLine();
$tableName = $tables[$tableNameNo];
}
if (array_key_exists('metadata', $params)) {
$this->showFieldMetaData($tableName);
return;
}
$this->showDataOfTable($tableName, $limitRows, $limitFieldValue);
}
private function removeDBPrefix(): void
{
$this->db->setPrefix('');
}
private function restoreDBPrefix(): void
{
$this->db->setPrefix($this->DBPrefix);
}
private function showDataOfTable(string $tableName, int $limitRows, int $limitFieldValue)
{
CLI::write("Data of Table \"{$tableName}\":", 'black', 'yellow');
CLI::newLine();
$this->removeDBPrefix();
$thead = $this->db->getFieldNames($tableName);
$this->restoreDBPrefix();
// If there is a field named `id`, sort by it.
$sortField = null;
if (in_array('id', $thead, true)) {
$sortField = 'id';
}
$this->tbody = $this->makeTableRows($tableName, $limitRows, $limitFieldValue, $sortField);
CLI::table($this->tbody, $thead);
}
private function showAllTables(array $tables)
{
CLI::write('The following is a list of the names of all database tables:', 'black', 'yellow');
CLI::newLine();
$thead = ['ID', 'Table Name', 'Num of Rows', 'Num of Fields'];
$this->tbody = $this->makeTbodyForShowAllTables($tables);
CLI::table($this->tbody, $thead);
CLI::newLine();
}
private function makeTbodyForShowAllTables(array $tables): array
{
$this->removeDBPrefix();
foreach ($tables as $id => $tableName) {
$table = $this->db->protectIdentifiers($tableName);
$db = $this->db->query("SELECT * FROM {$table}");
$this->tbody[] = [
$id + 1,
$tableName,
$db->getNumRows(),
$db->getFieldCount(),
];
}
$this->restoreDBPrefix();
if ($this->sortDesc) {
krsort($this->tbody);
}
return $this->tbody;
}
private function makeTableRows(
string $tableName,
int $limitRows,
int $limitFieldValue,
?string $sortField = null
): array {
$this->tbody = [];
$this->removeDBPrefix();
$builder = $this->db->table($tableName);
$builder->limit($limitRows);
if ($sortField !== null) {
$builder->orderBy($sortField, $this->sortDesc ? 'DESC' : 'ASC');
}
$rows = $builder->get()->getResultArray();
$this->restoreDBPrefix();
foreach ($rows as $row) {
$row = array_map(
static fn ($item): string => mb_strlen((string) $item) > $limitFieldValue
? mb_substr((string) $item, 0, $limitFieldValue) . '...'
: (string) $item,
$row
);
$this->tbody[] = $row;
}
if ($sortField === null && $this->sortDesc) {
krsort($this->tbody);
}
return $this->tbody;
}
private function showFieldMetaData(string $tableName): void
{
CLI::write("List of Metadata Information in Table \"{$tableName}\":", 'black', 'yellow');
CLI::newLine();
$thead = ['Field Name', 'Type', 'Max Length', 'Nullable', 'Default', 'Primary Key'];
$this->removeDBPrefix();
$fields = $this->db->getFieldData($tableName);
$this->restoreDBPrefix();
foreach ($fields as $row) {
$this->tbody[] = [
$row->name,
$row->type,
$row->max_length,
isset($row->nullable) ? $this->setYesOrNo($row->nullable) : 'n/a',
$row->default,
isset($row->primary_key) ? $this->setYesOrNo($row->primary_key) : 'n/a',
];
}
if ($this->sortDesc) {
krsort($this->tbody);
}
CLI::table($this->tbody, $thead);
}
private function setYesOrNo(bool $fieldValue): string
{
if ($fieldValue) {
return CLI::color('Yes', 'green');
}
return CLI::color('No', 'red');
}
}
@@ -0,0 +1,188 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Encryption;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\DotEnv;
use CodeIgniter\Encryption\Encryption;
/**
* Generates a new encryption key.
*/
class GenerateKey extends BaseCommand
{
/**
* The Command's group.
*
* @var string
*/
protected $group = 'Encryption';
/**
* The Command's name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The Command's usage.
*
* @var string
*/
protected $usage = 'key:generate [options]';
/**
* The Command's short description.
*
* @var string
*/
protected $description = 'Generates a new encryption key and writes it in an `.env` file.';
/**
* The command's options
*
* @var array
*/
protected $options = [
'--force' => 'Force overwrite existing key in `.env` file.',
'--length' => 'The length of the random string that should be returned in bytes. Defaults to 32.',
'--prefix' => 'Prefix to prepend to encoded key (either hex2bin or base64). Defaults to hex2bin.',
'--show' => 'Shows the generated key in the terminal instead of storing in the `.env` file.',
];
/**
* Actually execute the command.
*/
public function run(array $params)
{
$prefix = $params['prefix'] ?? CLI::getOption('prefix');
if (in_array($prefix, [null, true], true)) {
$prefix = 'hex2bin';
} elseif (! in_array($prefix, ['hex2bin', 'base64'], true)) {
$prefix = CLI::prompt('Please provide a valid prefix to use.', ['hex2bin', 'base64'], 'required'); // @codeCoverageIgnore
}
$length = $params['length'] ?? CLI::getOption('length');
if (in_array($length, [null, true], true)) {
$length = 32;
}
$encodedKey = $this->generateRandomKey($prefix, $length);
if (array_key_exists('show', $params) || (bool) CLI::getOption('show')) {
CLI::write($encodedKey, 'yellow');
CLI::newLine();
return;
}
if (! $this->setNewEncryptionKey($encodedKey, $params)) {
CLI::write('Error in setting new encryption key to .env file.', 'light_gray', 'red');
CLI::newLine();
return;
}
// force DotEnv to reload the new env vars
putenv('encryption.key');
unset($_ENV['encryption.key'], $_SERVER['encryption.key']);
$dotenv = new DotEnv(ROOTPATH);
$dotenv->load();
CLI::write('Application\'s new encryption key was successfully set.', 'green');
CLI::newLine();
}
/**
* Generates a key and encodes it.
*/
protected function generateRandomKey(string $prefix, int $length): string
{
$key = Encryption::createKey($length);
if ($prefix === 'hex2bin') {
return 'hex2bin:' . bin2hex($key);
}
return 'base64:' . base64_encode($key);
}
/**
* Sets the new encryption key in your .env file.
*/
protected function setNewEncryptionKey(string $key, array $params): bool
{
$currentKey = env('encryption.key', '');
if ($currentKey !== '' && ! $this->confirmOverwrite($params)) {
// Not yet testable since it requires keyboard input
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
return $this->writeNewEncryptionKeyToFile($currentKey, $key);
}
/**
* Checks whether to overwrite existing encryption key.
*/
protected function confirmOverwrite(array $params): bool
{
return (array_key_exists('force', $params) || CLI::getOption('force')) || CLI::prompt('Overwrite existing key?', ['n', 'y']) === 'y';
}
/**
* Writes the new encryption key to .env file.
*/
protected function writeNewEncryptionKeyToFile(string $oldKey, string $newKey): bool
{
$baseEnv = ROOTPATH . 'env';
$envFile = ROOTPATH . '.env';
if (! is_file($envFile)) {
if (! is_file($baseEnv)) {
CLI::write('Both default shipped `env` file and custom `.env` are missing.', 'yellow');
CLI::write('Here\'s your new key instead: ' . CLI::color($newKey, 'yellow'));
CLI::newLine();
return false;
}
copy($baseEnv, $envFile);
}
$ret = file_put_contents($envFile, preg_replace(
$this->keyPattern($oldKey),
"\nencryption.key = {$newKey}",
file_get_contents($envFile)
));
return $ret !== false;
}
/**
* Get the regex of the current encryption key.
*/
protected function keyPattern(string $oldKey): string
{
$escaped = preg_quote($oldKey, '/');
if ($escaped !== '') {
$escaped = "[{$escaped}]*";
}
return "/^[#\\s]*encryption.key[=\\s]*{$escaped}$/m";
}
}
@@ -0,0 +1,119 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton command file.
*/
class CommandGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:command';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new spark command.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:command <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The command class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--command' => 'The command name. Default: "command:name"',
'--type' => 'The command type. Options [basic, generator]. Default: "basic".',
'--group' => 'The command group. Default: [basic -> "CodeIgniter", generator -> "Generators"].',
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserCommand).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Command';
$this->directory = 'Commands';
$this->template = 'command.tpl.php';
$this->classNameLang = 'CLI.generator.className.command';
$this->execute($params);
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
$command = $this->getOption('command');
$group = $this->getOption('group');
$type = $this->getOption('type');
$command = is_string($command) ? $command : 'command:name';
$type = is_string($type) ? $type : 'basic';
if (! in_array($type, ['basic', 'generator'], true)) {
// @codeCoverageIgnoreStart
$type = CLI::prompt(lang('CLI.generator.commandType'), ['basic', 'generator'], 'required');
CLI::newLine();
// @codeCoverageIgnoreEnd
}
if (! is_string($group)) {
$group = $type === 'generator' ? 'Generators' : 'CodeIgniter';
}
return $this->parseTemplate(
$class,
['{group}', '{command}'],
[$group, $command],
['type' => $type]
);
}
}
@@ -0,0 +1,98 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton config file.
*/
class ConfigGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:config';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new config file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:config <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The config class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserConfig).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Config';
$this->directory = 'Config';
$this->template = 'config.tpl.php';
$this->classNameLang = 'CLI.generator.className.config';
$this->execute($params);
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
$namespace = $this->getOption('namespace') ?? APP_NAMESPACE;
if ($namespace === APP_NAMESPACE) {
$class = substr($class, strlen($namespace . '\\'));
}
return $this->parseTemplate($class);
}
}
@@ -0,0 +1,134 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
use CodeIgniter\Controller;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\RESTful\ResourcePresenter;
/**
* Generates a skeleton controller file.
*/
class ControllerGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:controller';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new controller file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:controller <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The controller class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--bare' => 'Extends from CodeIgniter\Controller instead of BaseController.',
'--restful' => 'Extends from a RESTful resource, Options: [controller, presenter]. Default: "controller".',
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserController).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Controller';
$this->directory = 'Controllers';
$this->template = 'controller.tpl.php';
$this->classNameLang = 'CLI.generator.className.controller';
$this->execute($params);
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
$bare = $this->getOption('bare');
$rest = $this->getOption('restful');
$useStatement = trim(APP_NAMESPACE, '\\') . '\Controllers\BaseController';
$extends = 'BaseController';
// Gets the appropriate parent class to extend.
if ($bare || $rest) {
if ($bare) {
$useStatement = Controller::class;
$extends = 'Controller';
} elseif ($rest) {
$rest = is_string($rest) ? $rest : 'controller';
if (! in_array($rest, ['controller', 'presenter'], true)) {
// @codeCoverageIgnoreStart
$rest = CLI::prompt(lang('CLI.generator.parentClass'), ['controller', 'presenter'], 'required');
CLI::newLine();
// @codeCoverageIgnoreEnd
}
if ($rest === 'controller') {
$useStatement = ResourceController::class;
$extends = 'ResourceController';
} elseif ($rest === 'presenter') {
$useStatement = ResourcePresenter::class;
$extends = 'ResourcePresenter';
}
}
}
return $this->parseTemplate(
$class,
['{useStatement}', '{extends}'],
[$useStatement, $extends],
['type' => $rest]
);
}
}
@@ -0,0 +1,84 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton Entity file.
*/
class EntityGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:entity';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new entity file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:entity <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The entity class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserEntity).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Entity';
$this->directory = 'Entities';
$this->template = 'entity.tpl.php';
$this->classNameLang = 'CLI.generator.className.entity';
$this->execute($params);
}
}
@@ -0,0 +1,84 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton Filter file.
*/
class FilterGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:filter';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new filter file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:filter <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The filter class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserFilter).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Filter';
$this->directory = 'Filters';
$this->template = 'filter.tpl.php';
$this->classNameLang = 'CLI.generator.className.filter';
$this->execute($params);
}
}
@@ -0,0 +1,90 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* Deprecated class for the migration creation command.
*
* @deprecated Use make:migration instead.
*
* @codeCoverageIgnore
*/
class MigrateCreate extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's name
*
* @var string
*/
protected $name = 'migrate:create';
/**
* The Command's short description
*
* @var string
*/
protected $description = '[DEPRECATED] Creates a new migration file. Please use "make:migration" instead.';
/**
* The Command's usage
*
* @var string
*/
protected $usage = 'migrate:create <name> [options]';
/**
* The Command's arguments.
*
* @var array
*/
protected $arguments = [
'name' => 'The migration file name.',
];
/**
* The Command's options.
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Defaults to APP_NAMESPACE',
'--force' => 'Force overwrite existing files.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
// Resolve arguments before passing to make:migration
$params[0] ??= CLI::getSegment(2);
$params['namespace'] ??= CLI::getOption('namespace') ?? APP_NAMESPACE;
if (array_key_exists('force', $params) || CLI::getOption('force')) {
$params['force'] = null;
}
$this->call('make:migration', $params);
}
}
@@ -0,0 +1,121 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton migration file.
*/
class MigrationGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:migration';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new migration file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:migration <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The migration class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--session' => 'Generates the migration file for database sessions.',
'--table' => 'Table name to use for database sessions. Default: "ci_sessions".',
'--dbgroup' => 'Database group to use for database sessions. Default: "default".',
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserMigration).',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Migration';
$this->directory = 'Database\Migrations';
$this->template = 'migration.tpl.php';
if (array_key_exists('session', $params) || CLI::getOption('session')) {
$table = $params['table'] ?? CLI::getOption('table') ?? 'ci_sessions';
$params[0] = "_create_{$table}_table";
}
$this->classNameLang = 'CLI.generator.className.migration';
$this->execute($params);
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
$data['session'] = false;
if ($this->getOption('session')) {
$table = $this->getOption('table');
$DBGroup = $this->getOption('dbgroup');
$data['session'] = true;
$data['table'] = is_string($table) ? $table : 'ci_sessions';
$data['DBGroup'] = is_string($DBGroup) ? $DBGroup : 'default';
$data['DBDriver'] = config('Database')->{$data['DBGroup']}['DBDriver'];
$data['matchIP'] = config('App')->sessionMatchIP;
}
return $this->parseTemplate($class, [], [], $data);
}
/**
* Change file basename before saving.
*/
protected function basename(string $filename): string
{
return gmdate(config('Migrations')->timestampFormat) . basename($filename);
}
}
@@ -0,0 +1,134 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton Model file.
*/
class ModelGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:model';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new model file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:model <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The model class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--table' => 'Supply a table name. Default: "the lowercased plural of the class name".',
'--dbgroup' => 'Database group to use. Default: "default".',
'--return' => 'Return type, Options: [array, object, entity]. Default: "array".',
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserModel).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Model';
$this->directory = 'Models';
$this->template = 'model.tpl.php';
$this->classNameLang = 'CLI.generator.className.model';
$this->execute($params);
}
/**
* Prepare options and do the necessary replacements.
*/
protected function prepare(string $class): string
{
$table = $this->getOption('table');
$dbGroup = $this->getOption('dbgroup');
$return = $this->getOption('return');
$baseClass = class_basename($class);
if (preg_match('/^(\S+)Model$/i', $baseClass, $match) === 1) {
$baseClass = $match[1];
}
$table = is_string($table) ? $table : plural(strtolower($baseClass));
$dbGroup = is_string($dbGroup) ? $dbGroup : 'default';
$return = is_string($return) ? $return : 'array';
if (! in_array($return, ['array', 'object', 'entity'], true)) {
// @codeCoverageIgnoreStart
$return = CLI::prompt(lang('CLI.generator.returnType'), ['array', 'object', 'entity'], 'required');
CLI::newLine();
// @codeCoverageIgnoreEnd
}
if ($return === 'entity') {
$return = str_replace('Models', 'Entities', $class);
if (preg_match('/^(\S+)Model$/i', $return, $match) === 1) {
$return = $match[1];
if ($this->getOption('suffix')) {
$return .= 'Entity';
}
}
$return = '\\' . trim($return, '\\') . '::class';
$this->call('make:entity', array_merge([$baseClass], $this->params));
} else {
$return = "'{$return}'";
}
return $this->parseTemplate($class, ['{table}', '{dbGroup}', '{return}'], [$table, $dbGroup, $return]);
}
}
@@ -0,0 +1,121 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a complete set of scaffold files.
*/
class ScaffoldGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:scaffold';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a complete set of scaffold files.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:scaffold <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The class name',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--bare' => 'Add the "--bare" option to controller component.',
'--restful' => 'Add the "--restful" option to controller component.',
'--table' => 'Add the "--table" option to the model component.',
'--dbgroup' => 'Add the "--dbgroup" option to model component.',
'--return' => 'Add the "--return" option to the model component.',
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name.',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->params = $params;
$options = [];
if ($this->getOption('namespace')) {
$options['namespace'] = $this->getOption('namespace');
}
if ($this->getOption('suffix')) {
$options['suffix'] = null;
}
if ($this->getOption('force')) {
$options['force'] = null;
}
$controllerOpts = [];
if ($this->getOption('bare')) {
$controllerOpts['bare'] = null;
} elseif ($this->getOption('restful')) {
$controllerOpts['restful'] = $this->getOption('restful');
}
$modelOpts = [
'table' => $this->getOption('table'),
'dbgroup' => $this->getOption('dbgroup'),
'return' => $this->getOption('return'),
];
$class = $params[0] ?? CLI::getSegment(2);
// Call those commands!
$this->call('make:controller', array_merge([$class], $controllerOpts, $options));
$this->call('make:model', array_merge([$class], $modelOpts, $options));
$this->call('make:migration', array_merge([$class], $options));
$this->call('make:seeder', array_merge([$class], $options));
}
}
@@ -0,0 +1,84 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton seeder file.
*/
class SeederGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:seeder';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new seeder file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:seeder <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The seeder class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserSeeder).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Seeder';
$this->directory = 'Database\Seeds';
$this->template = 'seeder.tpl.php';
$this->classNameLang = 'CLI.generator.className.seeder';
$this->execute($params);
}
}
@@ -0,0 +1,110 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a migration file for database sessions.
*
* @deprecated Use `make:migration --session` instead.
*
* @codeCoverageIgnore
*/
class SessionMigrationGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'session:migration';
/**
* The Command's Description
*
* @var string
*/
protected $description = '[DEPRECATED] Generates the migration file for database sessions, Please use "make:migration --session" instead.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'session:migration [options]';
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'-t' => 'Supply a table name.',
'-g' => 'Database group to use. Default: "default".',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Migration';
$this->directory = 'Database\Migrations';
$this->template = 'migration.tpl.php';
$table = 'ci_sessions';
if (array_key_exists('t', $params) || CLI::getOption('t')) {
$table = $params['t'] ?? CLI::getOption('t');
}
$params[0] = "_create_{$table}_table";
$this->execute($params);
}
/**
* Performs the necessary replacements.
*/
protected function prepare(string $class): string
{
$data['session'] = true;
$data['table'] = $this->getOption('t');
$data['DBGroup'] = $this->getOption('g');
$data['matchIP'] = config('App')->sessionMatchIP ?? false;
$data['table'] = is_string($data['table']) ? $data['table'] : 'ci_sessions';
$data['DBGroup'] = is_string($data['DBGroup']) ? $data['DBGroup'] : 'default';
return $this->parseTemplate($class, [], [], $data);
}
/**
* Change file basename before saving.
*/
protected function basename(string $filename): string
{
return gmdate(config('Migrations')->timestampFormat) . basename($filename);
}
}
@@ -0,0 +1,84 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Generators;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\GeneratorTrait;
/**
* Generates a skeleton Validation file.
*/
class ValidationGenerator extends BaseCommand
{
use GeneratorTrait;
/**
* The Command's Group
*
* @var string
*/
protected $group = 'Generators';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'make:validation';
/**
* The Command's Description
*
* @var string
*/
protected $description = 'Generates a new validation file.';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = 'make:validation <name> [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [
'name' => 'The validation class name.',
];
/**
* The Command's Options
*
* @var array
*/
protected $options = [
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
'--suffix' => 'Append the component title to the class name (e.g. User => UserValidation).',
'--force' => 'Force overwrite existing file.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$this->component = 'Validation';
$this->directory = 'Validation';
$this->template = 'validation.tpl.php';
$this->classNameLang = 'CLI.generator.className.validation';
$this->execute($params);
}
}
@@ -0,0 +1,76 @@
<@php
namespace {namespace};
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
<?php if ($type === 'generator'): ?>
use CodeIgniter\CLI\GeneratorTrait;
<?php endif ?>
class {class} extends BaseCommand
{
<?php if ($type === 'generator'): ?>
use GeneratorTrait;
<?php endif ?>
/**
* The Command's Group
*
* @var string
*/
protected $group = '{group}';
/**
* The Command's Name
*
* @var string
*/
protected $name = '{command}';
/**
* The Command's Description
*
* @var string
*/
protected $description = '';
/**
* The Command's Usage
*
* @var string
*/
protected $usage = '{command} [arguments] [options]';
/**
* The Command's Arguments
*
* @var array
*/
protected $arguments = [];
/**
* The Command's Options
*
* @var array
*/
protected $options = [];
/**
* Actually execute a command.
*
* @param array $params
*/
public function run(array $params)
{
<?php if ($type === 'generator'): ?>
$this->component = 'Command';
$this->directory = 'Commands';
$this->template = 'command.tpl.php';
$this->execute($params);
<?php else: ?>
//
<?php endif ?>
}
}
@@ -0,0 +1,10 @@
<@php
namespace {namespace};
use CodeIgniter\Config\BaseConfig;
class {class} extends BaseConfig
{
//
}
@@ -0,0 +1,177 @@
<@php
namespace {namespace};
use {useStatement};
class {class} extends {extends}
{
<?php if ($type === 'controller'): ?>
/**
* Return an array of resource objects, themselves in array format
*
* @return mixed
*/
public function index()
{
//
}
/**
* Return the properties of a resource object
*
* @return mixed
*/
public function show($id = null)
{
//
}
/**
* Return a new resource object, with default properties
*
* @return mixed
*/
public function new()
{
//
}
/**
* Create a new resource object, from "posted" parameters
*
* @return mixed
*/
public function create()
{
//
}
/**
* Return the editable properties of a resource object
*
* @return mixed
*/
public function edit($id = null)
{
//
}
/**
* Add or update a model resource, from "posted" properties
*
* @return mixed
*/
public function update($id = null)
{
//
}
/**
* Delete the designated resource object from the model
*
* @return mixed
*/
public function delete($id = null)
{
//
}
<?php elseif ($type === 'presenter'): ?>
/**
* Present a view of resource objects
*
* @return mixed
*/
public function index()
{
//
}
/**
* Present a view to present a specific resource object
*
* @param mixed $id
*
* @return mixed
*/
public function show($id = null)
{
//
}
/**
* Present a view to present a new single resource object
*
* @return mixed
*/
public function new()
{
//
}
/**
* Process the creation/insertion of a new resource object.
* This should be a POST.
*
* @return mixed
*/
public function create()
{
//
}
/**
* Present a view to edit the properties of a specific resource object
*
* @param mixed $id
*
* @return mixed
*/
public function edit($id = null)
{
//
}
/**
* Process the updating, full or partial, of a specific resource object.
* This should be a POST.
*
* @param mixed $id
*
* @return mixed
*/
public function update($id = null)
{
//
}
/**
* Present a view to confirm the deletion of a specific resource object
*
* @param mixed $id
*
* @return mixed
*/
public function remove($id = null)
{
//
}
/**
* Process the deletion of a specific resource object
*
* @param mixed $id
*
* @return mixed
*/
public function delete($id = null)
{
//
}
<?php else: ?>
public function index()
{
//
}
<?php endif ?>
}
@@ -0,0 +1,12 @@
<@php
namespace {namespace};
use CodeIgniter\Entity\Entity;
class {class} extends Entity
{
protected $datamap = [];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [];
}
@@ -0,0 +1,47 @@
<@php
namespace {namespace};
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class {class} implements FilterInterface
{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return mixed
*/
public function before(RequestInterface $request, $arguments = null)
{
//
}
/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return mixed
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}
@@ -0,0 +1,50 @@
<@php
namespace {namespace};
use CodeIgniter\Database\Migration;
class {class} extends Migration
{
<?php if ($session): ?>
protected $DBGroup = '<?= $DBGroup ?>';
public function up()
{
$this->forge->addField([
'id' => ['type' => 'VARCHAR', 'constraint' => 128, 'null' => false],
<?php if ($DBDriver === 'MySQLi'): ?>
'ip_address' => ['type' => 'VARCHAR', 'constraint' => 45, 'null' => false],
'timestamp timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL',
'data' => ['type' => 'BLOB', 'null' => false],
<?php elseif ($DBDriver === 'Postgre'): ?>
'ip_address inet NOT NULL',
'timestamp timestamptz DEFAULT CURRENT_TIMESTAMP NOT NULL',
"data bytea DEFAULT '' NOT NULL",
<?php endif; ?>
]);
<?php if ($matchIP) : ?>
$this->forge->addKey(['id', 'ip_address'], true);
<?php else: ?>
$this->forge->addKey('id', true);
<?php endif ?>
$this->forge->addKey('timestamp');
$this->forge->createTable('<?= $table ?>', true);
}
public function down()
{
$this->forge->dropTable('<?= $table ?>', true);
}
<?php else: ?>
public function up()
{
//
}
public function down()
{
//
}
<?php endif ?>
}
@@ -0,0 +1,42 @@
<@php
namespace {namespace};
use CodeIgniter\Model;
class {class} extends Model
{
protected $DBGroup = '{dbGroup}';
protected $table = '{table}';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = {return};
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
@@ -0,0 +1,13 @@
<@php
namespace {namespace};
use CodeIgniter\Database\Seeder;
class {class} extends Seeder
{
public function run()
{
//
}
}
@@ -0,0 +1,11 @@
<@php
namespace {namespace};
class {class}
{
// public function custom_rule(): bool
// {
// return true;
// }
}
+85
View File
@@ -0,0 +1,85 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands;
use CodeIgniter\CLI\BaseCommand;
/**
* CI Help command for the spark script.
*
* Lists the basic usage information for the spark script,
* and provides a way to list help for other commands.
*/
class Help extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'help';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Displays basic usage information.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'help [<command_name>]';
/**
* the Command's Arguments
*
* @var array
*/
protected $arguments = [
'command_name' => 'The command name [default: "help"]',
];
/**
* the Command's Options
*
* @var array
*/
protected $options = [];
/**
* Displays the help for spark commands.
*/
public function run(array $params)
{
$command = array_shift($params);
$command ??= 'help';
$commands = $this->commands->getCommands();
if (! $this->commands->verifyCommand($command, $commands)) {
return;
}
$class = new $commands[$command]['class']($this->logger, $this->commands);
$class->showHelp();
}
}
@@ -0,0 +1,70 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Housekeeping;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* ClearDebugbar Command
*/
class ClearDebugbar extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Housekeeping';
/**
* The Command's name
*
* @var string
*/
protected $name = 'debugbar:clear';
/**
* The Command's usage
*
* @var string
*/
protected $usage = 'debugbar:clear';
/**
* The Command's short description.
*
* @var string
*/
protected $description = 'Clears all debugbar JSON files.';
/**
* Actually runs the command.
*/
public function run(array $params)
{
helper('filesystem');
if (! delete_files(WRITEPATH . 'debugbar')) {
// @codeCoverageIgnoreStart
CLI::error('Error deleting the debugbar JSON files.');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
CLI::write('Debugbar cleared.', 'green');
CLI::newLine();
}
}
@@ -0,0 +1,91 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Housekeeping;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* ClearLogs command.
*/
class ClearLogs extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Housekeeping';
/**
* The Command's name
*
* @var string
*/
protected $name = 'logs:clear';
/**
* The Command's short description
*
* @var string
*/
protected $description = 'Clears all log files.';
/**
* The Command's usage
*
* @var string
*/
protected $usage = 'logs:clear [option';
/**
* The Command's options
*
* @var array
*/
protected $options = [
'--force' => 'Force delete of all logs files without prompting.',
];
/**
* Actually execute a command.
*/
public function run(array $params)
{
$force = array_key_exists('force', $params) || CLI::getOption('force');
if (! $force && CLI::prompt('Are you sure you want to delete the logs?', ['n', 'y']) === 'n') {
// @codeCoverageIgnoreStart
CLI::error('Deleting logs aborted.', 'light_gray', 'red');
CLI::error('If you want, use the "-force" option to force delete all log files.', 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
helper('filesystem');
if (! delete_files(WRITEPATH . 'logs', false, true)) {
// @codeCoverageIgnoreStart
CLI::error('Error in deleting the logs files.', 'light_gray', 'red');
CLI::newLine();
return;
// @codeCoverageIgnoreEnd
}
CLI::write('Logs cleared.', 'green');
CLI::newLine();
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* CI Help command for the spark script.
*
* Lists the basic usage information for the spark script,
* and provides a way to list help for other commands.
*/
class ListCommands extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'list';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Lists the available commands.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'list';
/**
* the Command's Arguments
*
* @var array
*/
protected $arguments = [];
/**
* the Command's Options
*
* @var array
*/
protected $options = [
'--simple' => 'Prints a list of the commands with no other info',
];
/**
* Displays the help for the spark cli script itself.
*/
public function run(array $params)
{
$commands = $this->commands->getCommands();
ksort($commands);
// Check for 'simple' format
return array_key_exists('simple', $params) || CLI::getOption('simple')
? $this->listSimple($commands)
: $this->listFull($commands);
}
/**
* Lists the commands with accompanying info.
*/
protected function listFull(array $commands)
{
// Sort into buckets by group
$groups = [];
foreach ($commands as $title => $command) {
if (! isset($groups[$command['group']])) {
$groups[$command['group']] = [];
}
$groups[$command['group']][$title] = $command;
}
$length = max(array_map('strlen', array_keys($commands)));
ksort($groups);
// Display it all...
foreach ($groups as $group => $commands) {
CLI::write($group, 'yellow');
foreach ($commands as $name => $command) {
$name = $this->setPad($name, $length, 2, 2);
$output = CLI::color($name, 'green');
if (isset($command['description'])) {
$output .= CLI::wrap($command['description'], 125, strlen($name));
}
CLI::write($output);
}
if ($group !== array_key_last($groups)) {
CLI::newLine();
}
}
}
/**
* Lists the commands only.
*/
protected function listSimple(array $commands)
{
foreach (array_keys($commands) as $title) {
CLI::write($title);
}
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Server;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* Launch the PHP development server
*
* Not testable, as it throws phpunit for a loop :-/
*
* @codeCoverageIgnore
*/
class Serve extends BaseCommand
{
/**
* Group
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* Name
*
* @var string
*/
protected $name = 'serve';
/**
* Description
*
* @var string
*/
protected $description = 'Launches the CodeIgniter PHP-Development Server.';
/**
* Usage
*
* @var string
*/
protected $usage = 'serve';
/**
* Arguments
*
* @var array
*/
protected $arguments = [];
/**
* The current port offset.
*
* @var int
*/
protected $portOffset = 0;
/**
* The max number of ports to attempt to serve from
*
* @var int
*/
protected $tries = 10;
/**
* Options
*
* @var array
*/
protected $options = [
'--php' => 'The PHP Binary [default: "PHP_BINARY"]',
'--host' => 'The HTTP Host [default: "localhost"]',
'--port' => 'The HTTP Host Port [default: "8080"]',
];
/**
* Run the server
*/
public function run(array $params)
{
// Collect any user-supplied options and apply them.
$php = escapeshellarg(CLI::getOption('php') ?? PHP_BINARY);
$host = CLI::getOption('host') ?? 'localhost';
$port = (int) (CLI::getOption('port') ?? 8080) + $this->portOffset;
// 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, $status);
if ($status && $this->portOffset < $this->tries) {
$this->portOffset++;
$this->run($params);
}
}
}
@@ -0,0 +1,47 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
/*
* CodeIgniter PHP-Development Server Rewrite Rules
*
* This script works with the CLI serve command to help run a seamless
* development server based around PHP's built-in development
* server. This file simply tries to mimic Apache's mod_rewrite
* functionality so the site will operate as normal.
*/
// @codeCoverageIgnoreStart
// Avoid this file run when listing commands
if (PHP_SAPI === 'cli') {
return;
}
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// All request handle by index.php file.
$_SERVER['SCRIPT_NAME'] = '/index.php';
// Front Controller path - expected to be in the default folder
$fcpath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
// Full path
$path = $fcpath . ltrim($uri, '/');
// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path))) {
return false;
}
// Otherwise, we'll load the index file and let
// the framework handle the request from here.
require_once $fcpath . 'index.php';
// @codeCoverageIgnoreEnd
@@ -0,0 +1,155 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\DotEnv;
/**
* Command to display the current environment,
* or set a new one in the `.env` file.
*/
final class Environment extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'env';
/**
* The Command's short description
*
* @var string
*/
protected $description = 'Retrieves the current environment, or set a new one.';
/**
* The Command's usage
*
* @var string
*/
protected $usage = 'env [<environment>]';
/**
* The Command's arguments
*
* @var array<string, string>
*/
protected $arguments = [
'environment' => '[Optional] The new environment to set. If none is provided, this will print the current environment.',
];
/**
* The Command's options
*
* @var array
*/
protected $options = [];
/**
* Allowed values for environment. `testing` is excluded
* since spark won't work on it.
*
* @var array<int, string>
*/
private static array $knownTypes = [
'production',
'development',
];
/**
* {@inheritDoc}
*/
public function run(array $params)
{
if ($params === []) {
CLI::write(sprintf('Your environment is currently set as %s.', CLI::color($_SERVER['CI_ENVIRONMENT'] ?? ENVIRONMENT, 'green')));
CLI::newLine();
return;
}
$env = strtolower(array_shift($params));
if ($env === 'testing') {
CLI::error('The "testing" environment is reserved for PHPUnit testing.', 'light_gray', 'red');
CLI::error('You will not be able to run spark under a "testing" environment.', 'light_gray', 'red');
CLI::newLine();
return;
}
if (! in_array($env, self::$knownTypes, true)) {
CLI::error(sprintf('Invalid environment type "%s". Expected one of "%s".', $env, implode('" and "', self::$knownTypes)), 'light_gray', 'red');
CLI::newLine();
return;
}
if (! $this->writeNewEnvironmentToEnvFile($env)) {
CLI::error('Error in writing new environment to .env file.', 'light_gray', 'red');
CLI::newLine();
return;
}
// force DotEnv to reload the new environment
// however we cannot redefine the ENVIRONMENT constant
putenv('CI_ENVIRONMENT');
unset($_ENV['CI_ENVIRONMENT'], $_SERVER['CI_ENVIRONMENT']);
(new DotEnv(ROOTPATH))->load();
CLI::write(sprintf('Environment is successfully changed to "%s".', $env), 'green');
CLI::write('The ENVIRONMENT constant will be changed in the next script execution.');
CLI::newLine();
}
/**
* @see https://regex101.com/r/4sSORp/1 for the regex in action
*/
private function writeNewEnvironmentToEnvFile(string $newEnv): bool
{
$baseEnv = ROOTPATH . 'env';
$envFile = ROOTPATH . '.env';
if (! is_file($envFile)) {
if (! is_file($baseEnv)) {
CLI::write('Both default shipped `env` file and custom `.env` are missing.', 'yellow');
CLI::write('It is impossible to write the new environment type.', 'yellow');
CLI::newLine();
return false;
}
copy($baseEnv, $envFile);
}
$pattern = preg_quote($_SERVER['CI_ENVIRONMENT'] ?? ENVIRONMENT, '/');
$pattern = sprintf('/^[#\s]*CI_ENVIRONMENT[=\s]+%s$/m', $pattern);
return file_put_contents(
$envFile,
preg_replace($pattern, "\nCI_ENVIRONMENT = {$newEnv}", file_get_contents($envFile), -1, $count)
) !== false && $count > 0;
}
}
@@ -0,0 +1,95 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Autoload;
/**
* Lists namespaces set in Config\Autoload with their
* full server path. Helps you to verify that you have
* the namespaces setup correctly.
*/
class Namespaces extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'namespaces';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Verifies your namespaces are setup correctly.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'namespaces';
/**
* the Command's Arguments
*
* @var array
*/
protected $arguments = [];
/**
* the Command's Options
*
* @var array
*/
protected $options = [];
/**
* Displays the help for the spark cli script itself.
*/
public function run(array $params)
{
$config = new Autoload();
$tbody = [];
foreach ($config->psr4 as $ns => $path) {
$path = realpath($path) ?: $path;
$tbody[] = [
$ns,
realpath($path) ?: $path,
is_dir($path) ? 'Yes' : 'MISSING',
];
}
$thead = [
'Namespace',
'Path',
'Found?',
];
CLI::table($tbody, $thead);
}
}
@@ -0,0 +1,104 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Publisher\Publisher;
/**
* Discovers all Publisher classes from the "Publishers/" directory
* across namespaces. Executes `publish()` from each instance, parsing
* each result.
*/
class Publish extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'publish';
/**
* The Command's short description
*
* @var string
*/
protected $description = 'Discovers and executes all predefined Publisher classes.';
/**
* The Command's usage
*
* @var string
*/
protected $usage = 'publish [<directory>]';
/**
* The Command's arguments
*
* @var array<string, string>
*/
protected $arguments = [
'directory' => '[Optional] The directory to scan within each namespace. Default: "Publishers".',
];
/**
* the Command's Options
*
* @var array
*/
protected $options = [];
/**
* Displays the help for the spark cli script itself.
*/
public function run(array $params)
{
$directory = array_shift($params) ?? 'Publishers';
if ([] === $publishers = Publisher::discover($directory)) {
CLI::write(lang('Publisher.publishMissing', [$directory]));
return;
}
foreach ($publishers as $publisher) {
if ($publisher->publish()) {
CLI::write(lang('Publisher.publishSuccess', [
get_class($publisher),
count($publisher->getPublished()),
$publisher->getDestination(),
]), 'green');
} else {
CLI::error(lang('Publisher.publishFailure', [
get_class($publisher),
$publisher->getDestination(),
]), 'light_gray', 'red');
foreach ($publisher->getErrors() as $file => $exception) {
CLI::write($file);
CLI::error($exception->getMessage());
CLI::newLine();
}
}
}
}
}
@@ -0,0 +1,159 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities;
use Closure;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Commands\Utilities\Routes\AutoRouteCollector;
use CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved\AutoRouteCollector as AutoRouteCollectorImproved;
use CodeIgniter\Commands\Utilities\Routes\FilterCollector;
use CodeIgniter\Commands\Utilities\Routes\SampleURIGenerator;
use Config\Services;
/**
* Lists all the routes. This will include any Routes files
* that can be discovered, and will include routes that are not defined
* in routes files, but are instead discovered through auto-routing.
*/
class Routes extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'CodeIgniter';
/**
* The Command's name
*
* @var string
*/
protected $name = 'routes';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Displays all routes.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'routes';
/**
* the Command's Arguments
*
* @var array
*/
protected $arguments = [];
/**
* the Command's Options
*
* @var array
*/
protected $options = [];
/**
* Displays the help for the spark cli script itself.
*/
public function run(array $params)
{
$collection = Services::routes(true);
$methods = [
'get',
'head',
'post',
'patch',
'put',
'delete',
'options',
'trace',
'connect',
'cli',
];
$tbody = [];
$uriGenerator = new SampleURIGenerator();
$filterCollector = new FilterCollector();
foreach ($methods as $method) {
$routes = $collection->getRoutes($method);
foreach ($routes as $route => $handler) {
if (is_string($handler) || $handler instanceof Closure) {
$sampleUri = $uriGenerator->get($route);
$filters = $filterCollector->get($method, $sampleUri);
$tbody[] = [
strtoupper($method),
$route,
is_string($handler) ? $handler : '(Closure)',
implode(' ', array_map('class_basename', $filters['before'])),
implode(' ', array_map('class_basename', $filters['after'])),
];
}
}
}
if ($collection->shouldAutoRoute()) {
$autoRoutesImproved = config('Feature')->autoRoutesImproved ?? false;
if ($autoRoutesImproved) {
$autoRouteCollector = new AutoRouteCollectorImproved(
$collection->getDefaultNamespace(),
$collection->getDefaultController(),
$collection->getDefaultMethod(),
$methods,
$collection->getRegisteredControllers('*')
);
$autoRoutes = $autoRouteCollector->get();
} else {
$autoRouteCollector = new AutoRouteCollector(
$collection->getDefaultNamespace(),
$collection->getDefaultController(),
$collection->getDefaultMethod()
);
$autoRoutes = $autoRouteCollector->get();
foreach ($autoRoutes as &$routes) {
// There is no `auto` method, but it is intentional not to get route filters.
$filters = $filterCollector->get('auto', $uriGenerator->get($routes[1]));
$routes[] = implode(' ', array_map('class_basename', $filters['before']));
$routes[] = implode(' ', array_map('class_basename', $filters['after']));
}
}
$tbody = [...$tbody, ...$autoRoutes];
}
$thead = [
'Method',
'Route',
'Handler',
'Before Filters',
'After Filters',
];
CLI::table($tbody, $thead);
}
}
@@ -0,0 +1,66 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
/**
* Collects data for auto route listing.
*/
final class AutoRouteCollector
{
/**
* @var string namespace to search
*/
private string $namespace;
private string $defaultController;
private string $defaultMethod;
/**
* @param string $namespace namespace to search
*/
public function __construct(string $namespace, string $defaultController, string $defaultMethod)
{
$this->namespace = $namespace;
$this->defaultController = $defaultController;
$this->defaultMethod = $defaultMethod;
}
/**
* @return array<int, array<int, string>>
* @phpstan-return list<list<string>>
*/
public function get(): array
{
$finder = new ControllerFinder($this->namespace);
$reader = new ControllerMethodReader($this->namespace);
$tbody = [];
foreach ($finder->find() as $class) {
$output = $reader->read(
$class,
$this->defaultController,
$this->defaultMethod
);
foreach ($output as $item) {
$tbody[] = [
'auto',
$item['route'],
$item['handler'],
];
}
}
return $tbody;
}
}
@@ -0,0 +1,138 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved;
use CodeIgniter\Commands\Utilities\Routes\ControllerFinder;
use CodeIgniter\Commands\Utilities\Routes\FilterCollector;
/**
* Collects data for Auto Routing Improved.
*/
final class AutoRouteCollector
{
/**
* @var string namespace to search
*/
private string $namespace;
private string $defaultController;
private string $defaultMethod;
private array $httpMethods;
/**
* List of controllers in Defined Routes that should not be accessed via Auto-Routing.
*
* @var class-string[]
*/
private array $protectedControllers;
/**
* @param string $namespace namespace to search
*/
public function __construct(
string $namespace,
string $defaultController,
string $defaultMethod,
array $httpMethods,
array $protectedControllers
) {
$this->namespace = $namespace;
$this->defaultController = $defaultController;
$this->defaultMethod = $defaultMethod;
$this->httpMethods = $httpMethods;
$this->protectedControllers = $protectedControllers;
}
/**
* @return array<int, array<int, string>>
* @phpstan-return list<list<string>>
*/
public function get(): array
{
$finder = new ControllerFinder($this->namespace);
$reader = new ControllerMethodReader($this->namespace, $this->httpMethods);
$tbody = [];
foreach ($finder->find() as $class) {
// Exclude controllers in Defined Routes.
if (in_array('\\' . $class, $this->protectedControllers, true)) {
continue;
}
$routes = $reader->read(
$class,
$this->defaultController,
$this->defaultMethod
);
if ($routes === []) {
continue;
}
$routes = $this->addFilters($routes);
foreach ($routes as $item) {
$tbody[] = [
strtoupper($item['method']) . '(auto)',
$item['route'] . $item['route_params'],
$item['handler'],
$item['before'],
$item['after'],
];
}
}
return $tbody;
}
private function addFilters($routes)
{
$filterCollector = new FilterCollector(true);
foreach ($routes as &$route) {
// Search filters for the URI with all params
$sampleUri = $this->generateSampleUri($route);
$filtersLongest = $filterCollector->get($route['method'], $route['route'] . $sampleUri);
// Search filters for the URI without optional params
$sampleUri = $this->generateSampleUri($route, false);
$filtersShortest = $filterCollector->get($route['method'], $route['route'] . $sampleUri);
// Get common array elements
$filters['before'] = array_intersect($filtersLongest['before'], $filtersShortest['before']);
$filters['after'] = array_intersect($filtersLongest['after'], $filtersShortest['after']);
$route['before'] = implode(' ', array_map('class_basename', $filters['before']));
$route['after'] = implode(' ', array_map('class_basename', $filters['after']));
}
return $routes;
}
private function generateSampleUri(array $route, bool $longest = true): string
{
$sampleUri = '';
if (isset($route['params'])) {
$i = 1;
foreach ($route['params'] as $required) {
if ($longest && ! $required) {
$sampleUri .= '/' . $i++;
}
}
}
return $sampleUri;
}
}
@@ -0,0 +1,182 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved;
use ReflectionClass;
use ReflectionMethod;
/**
* Reads a controller and returns a list of auto route listing.
*/
final class ControllerMethodReader
{
/**
* @var string the default namespace
*/
private string $namespace;
private array $httpMethods;
/**
* @param string $namespace the default namespace
*/
public function __construct(string $namespace, array $httpMethods)
{
$this->namespace = $namespace;
$this->httpMethods = $httpMethods;
}
/**
* Returns found route info in the controller.
*
* @phpstan-param class-string $class
*
* @return array<int, array<string, array|string>>
* @phpstan-return list<array<string, string|array>>
*/
public function read(string $class, string $defaultController = 'Home', string $defaultMethod = 'index'): array
{
$reflection = new ReflectionClass($class);
if ($reflection->isAbstract()) {
return [];
}
$classname = $reflection->getName();
$classShortname = $reflection->getShortName();
$output = [];
$classInUri = $this->getUriByClass($classname);
foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$methodName = $method->getName();
foreach ($this->httpMethods as $httpVerb) {
if (strpos($methodName, $httpVerb) === 0) {
// Remove HTTP verb prefix.
$methodInUri = lcfirst(substr($methodName, strlen($httpVerb)));
if ($methodInUri === $defaultMethod) {
$routeWithoutController = $this->getRouteWithoutController(
$classShortname,
$defaultController,
$classInUri,
$classname,
$methodName,
$httpVerb
);
if ($routeWithoutController !== []) {
$output = [...$output, ...$routeWithoutController];
continue;
}
// Route for the default method.
$output[] = [
'method' => $httpVerb,
'route' => $classInUri,
'route_params' => '',
'handler' => '\\' . $classname . '::' . $methodName,
'params' => [],
];
continue;
}
$route = $classInUri . '/' . $methodInUri;
$params = [];
$routeParams = '';
$refParams = $method->getParameters();
foreach ($refParams as $param) {
$required = true;
if ($param->isOptional()) {
$required = false;
$routeParams .= '[/..]';
} else {
$routeParams .= '/..';
}
// [variable_name => required?]
$params[$param->getName()] = $required;
}
$output[] = [
'method' => $httpVerb,
'route' => $route,
'route_params' => $routeParams,
'handler' => '\\' . $classname . '::' . $methodName,
'params' => $params,
];
}
}
}
return $output;
}
/**
* @phpstan-param class-string $classname
*
* @return string URI path part from the folder(s) and controller
*/
private function getUriByClass(string $classname): string
{
// remove the namespace
$pattern = '/' . preg_quote($this->namespace, '/') . '/';
$class = ltrim(preg_replace($pattern, '', $classname), '\\');
$classParts = explode('\\', $class);
$classPath = '';
foreach ($classParts as $part) {
// make the first letter lowercase, because auto routing makes
// the URI path's first letter uppercase and search the controller
$classPath .= lcfirst($part) . '/';
}
return rtrim($classPath, '/');
}
/**
* Gets a route without default controller.
*/
private function getRouteWithoutController(
string $classShortname,
string $defaultController,
string $uriByClass,
string $classname,
string $methodName,
string $httpVerb
): array {
$output = [];
if ($classShortname === $defaultController) {
$pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#';
$routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/');
$routeWithoutController = $routeWithoutController ?: '/';
$output[] = [
'method' => $httpVerb,
'route' => $routeWithoutController,
'route_params' => '',
'handler' => '\\' . $classname . '::' . $methodName,
'params' => [],
];
}
return $output;
}
}
@@ -0,0 +1,76 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
use CodeIgniter\Autoloader\FileLocator;
use CodeIgniter\Config\Services;
/**
* Finds all controllers in a namespace for auto route listing.
*/
final class ControllerFinder
{
/**
* @var string namespace to search
*/
private string $namespace;
private FileLocator $locator;
/**
* @param string $namespace namespace to search
*/
public function __construct(string $namespace)
{
$this->namespace = $namespace;
$this->locator = Services::locator();
}
/**
* @return string[]
* @phpstan-return class-string[]
*/
public function find(): array
{
$nsArray = explode('\\', trim($this->namespace, '\\'));
$count = count($nsArray);
$ns = '';
for ($i = 0; $i < $count; $i++) {
$ns .= '\\' . array_shift($nsArray);
$path = implode('\\', $nsArray);
$files = $this->locator->listNamespaceFiles($ns, $path);
if ($files !== []) {
break;
}
}
$classes = [];
foreach ($files as $file) {
if (\is_file($file)) {
$classnameOrEmpty = $this->locator->getClassname($file);
if ($classnameOrEmpty !== '') {
/** @phpstan-var class-string $classname */
$classname = $classnameOrEmpty;
$classes[] = $classname;
}
}
}
return $classes;
}
}
@@ -0,0 +1,176 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
use ReflectionClass;
use ReflectionMethod;
/**
* Reads a controller and returns a list of auto route listing.
*/
final class ControllerMethodReader
{
/**
* @var string the default namespace
*/
private string $namespace;
/**
* @param string $namespace the default namespace
*/
public function __construct(string $namespace)
{
$this->namespace = $namespace;
}
/**
* @phpstan-param class-string $class
*
* @return array<int, array{route: string, handler: string}>
* @phpstan-return list<array{route: string, handler: string}>
*/
public function read(string $class, string $defaultController = 'Home', string $defaultMethod = 'index'): array
{
$reflection = new ReflectionClass($class);
if ($reflection->isAbstract()) {
return [];
}
$classname = $reflection->getName();
$classShortname = $reflection->getShortName();
$output = [];
$uriByClass = $this->getUriByClass($classname);
if ($this->hasRemap($reflection)) {
$methodName = '_remap';
$routeWithoutController = $this->getRouteWithoutController(
$classShortname,
$defaultController,
$uriByClass,
$classname,
$methodName
);
$output = [...$output, ...$routeWithoutController];
$output[] = [
'route' => $uriByClass . '[/...]',
'handler' => '\\' . $classname . '::' . $methodName,
];
return $output;
}
foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$methodName = $method->getName();
$route = $uriByClass . '/' . $methodName;
// Exclude BaseController and initController
// See system/Config/Routes.php
if (preg_match('#\AbaseController.*#', $route) === 1) {
continue;
}
if (preg_match('#.*/initController\z#', $route) === 1) {
continue;
}
if ($methodName === $defaultMethod) {
$routeWithoutController = $this->getRouteWithoutController(
$classShortname,
$defaultController,
$uriByClass,
$classname,
$methodName
);
$output = [...$output, ...$routeWithoutController];
$output[] = [
'route' => $uriByClass,
'handler' => '\\' . $classname . '::' . $methodName,
];
}
$output[] = [
'route' => $route . '[/...]',
'handler' => '\\' . $classname . '::' . $methodName,
];
}
return $output;
}
/**
* Whether the class has a _remap() method.
*/
private function hasRemap(ReflectionClass $class): bool
{
if ($class->hasMethod('_remap')) {
$remap = $class->getMethod('_remap');
return $remap->isPublic();
}
return false;
}
/**
* @phpstan-param class-string $classname
*
* @return string URI path part from the folder(s) and controller
*/
private function getUriByClass(string $classname): string
{
// remove the namespace
$pattern = '/' . preg_quote($this->namespace, '/') . '/';
$class = ltrim(preg_replace($pattern, '', $classname), '\\');
$classParts = explode('\\', $class);
$classPath = '';
foreach ($classParts as $part) {
// make the first letter lowercase, because auto routing makes
// the URI path's first letter uppercase and search the controller
$classPath .= lcfirst($part) . '/';
}
return rtrim($classPath, '/');
}
/**
* Gets a route without default controller.
*/
private function getRouteWithoutController(
string $classShortname,
string $defaultController,
string $uriByClass,
string $classname,
string $methodName
): array {
$output = [];
if ($classShortname === $defaultController) {
$pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#';
$routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/');
$routeWithoutController = $routeWithoutController ?: '/';
$output[] = [
'route' => $routeWithoutController,
'handler' => '\\' . $classname . '::' . $methodName,
];
}
return $output;
}
}
@@ -0,0 +1,79 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
use CodeIgniter\Config\Services;
use CodeIgniter\Filters\Filters;
use CodeIgniter\HTTP\Request;
use CodeIgniter\Router\Router;
/**
* Collects filters for a route.
*/
final class FilterCollector
{
/**
* Whether to reset Defined Routes.
*
* If set to true, route filters are not found.
*/
private bool $resetRoutes;
public function __construct(bool $resetRoutes = false)
{
$this->resetRoutes = $resetRoutes;
}
/**
* @param string $method HTTP method
* @param string $uri URI path to find filters for
*
* @return array{before: list<string>, after: list<string>} array of filter alias or classname
*/
public function get(string $method, string $uri): array
{
if ($method === 'cli') {
return [
'before' => [],
'after' => [],
];
}
$request = Services::request(null, false);
$request->setMethod($method);
$router = $this->createRouter($request);
$filters = $this->createFilters($request);
$finder = new FilterFinder($router, $filters);
return $finder->find($uri);
}
private function createRouter(Request $request): Router
{
$routes = Services::routes();
if ($this->resetRoutes) {
$routes->resetRoutes();
}
return new Router($routes, $request);
}
private function createFilters(Request $request): Filters
{
$config = config('Filters');
return new Filters($config, $request, Services::response());
}
}
@@ -0,0 +1,78 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Router\Exceptions\RedirectException;
use CodeIgniter\Router\Router;
use Config\Services;
/**
* Finds filters.
*/
final class FilterFinder
{
private Router $router;
private Filters $filters;
public function __construct(?Router $router = null, ?Filters $filters = null)
{
$this->router = $router ?? Services::router();
$this->filters = $filters ?? Services::filters();
}
private function getRouteFilters(string $uri): array
{
$this->router->handle($uri);
$multipleFiltersEnabled = config('Feature')->multipleFilters ?? false;
if (! $multipleFiltersEnabled) {
$filter = $this->router->getFilter();
return $filter === null ? [] : [$filter];
}
return $this->router->getFilters();
}
/**
* @param string $uri URI path to find filters for
*
* @return array{before: list<string>, after: list<string>} array of filter alias or classname
*/
public function find(string $uri): array
{
$this->filters->reset();
// Add route filters
try {
$routeFilters = $this->getRouteFilters($uri);
$this->filters->enableFilters($routeFilters, 'before');
$this->filters->enableFilters($routeFilters, 'after');
$this->filters->initialize($uri);
return $this->filters->getFilters();
} catch (RedirectException $e) {
return [
'before' => [],
'after' => [],
];
} catch (PageNotFoundException $e) {
return [
'before' => ['<unknown>'],
'after' => ['<unknown>'],
];
}
}
}
@@ -0,0 +1,61 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Utilities\Routes;
use CodeIgniter\Config\Services;
use CodeIgniter\Router\RouteCollection;
/**
* Generate a sample URI path from route key regex.
*/
final class SampleURIGenerator
{
private RouteCollection $routes;
/**
* Sample URI path for placeholder.
*
* @var array<string, string>
*/
private array $samples = [
'any' => '123/abc',
'segment' => 'abc_123',
'alphanum' => 'abc123',
'num' => '123',
'alpha' => 'abc',
'hash' => 'abc_123',
];
public function __construct(?RouteCollection $routes = null)
{
$this->routes = $routes ?? Services::routes();
}
/**
* @param string $routeKey route key regex
*
* @return string sample URI path
*/
public function get(string $routeKey): string
{
$sampleUri = $routeKey;
foreach ($this->routes->getPlaceholders() as $placeholder => $regex) {
$sample = $this->samples[$placeholder] ?? '::unknown::';
$sampleUri = str_replace('(' . $regex . ')', $sample, $sampleUri);
}
// auto route
return str_replace('[/...]', '/1/2/3/4/5', $sampleUri);
}
}
File diff suppressed because it is too large Load Diff
+161
View File
@@ -0,0 +1,161 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
/**
* This class is used by Composer during installs and updates
* to move files to locations within the system folder so that end-users
* do not need to use Composer to install a package, but can simply
* download.
*
* @codeCoverageIgnore
*
* @internal
*/
final class ComposerScripts
{
/**
* Path to the ThirdParty directory.
*/
private static string $path = __DIR__ . '/ThirdParty/';
/**
* Direct dependencies of CodeIgniter to copy
* contents to `system/ThirdParty/`.
*
* @var array<string, array<string, string>>
*/
private static array $dependencies = [
'kint-src' => [
'license' => __DIR__ . '/../vendor/kint-php/kint/LICENSE',
'from' => __DIR__ . '/../vendor/kint-php/kint/src/',
'to' => __DIR__ . '/ThirdParty/Kint/',
],
'kint-resources' => [
'from' => __DIR__ . '/../vendor/kint-php/kint/resources/',
'to' => __DIR__ . '/ThirdParty/Kint/resources/',
],
'escaper' => [
'license' => __DIR__ . '/../vendor/laminas/laminas-escaper/LICENSE.md',
'from' => __DIR__ . '/../vendor/laminas/laminas-escaper/src/',
'to' => __DIR__ . '/ThirdParty/Escaper/',
],
'psr-log' => [
'license' => __DIR__ . '/../vendor/psr/log/LICENSE',
'from' => __DIR__ . '/../vendor/psr/log/Psr/Log/',
'to' => __DIR__ . '/ThirdParty/PSR/Log/',
],
];
/**
* This static method is called by Composer after every update event,
* i.e., `composer install`, `composer update`, `composer remove`.
*/
public static function postUpdate()
{
self::recursiveDelete(self::$path);
foreach (self::$dependencies as $dependency) {
self::recursiveMirror($dependency['from'], $dependency['to']);
if (isset($dependency['license'])) {
$license = basename($dependency['license']);
copy($dependency['license'], $dependency['to'] . '/' . $license);
}
}
self::copyKintInitFiles();
self::recursiveDelete(self::$dependencies['psr-log']['to'] . 'Test/');
}
/**
* Recursively remove the contents of the previous `system/ThirdParty`.
*/
private static function recursiveDelete(string $directory): void
{
if (! is_dir($directory)) {
echo sprintf('Cannot recursively delete "%s" as it does not exist.', $directory);
}
/** @var SplFileInfo $file */
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(rtrim($directory, '\\/'), FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
) as $file) {
$path = $file->getPathname();
if ($file->isDir()) {
@rmdir($path);
} else {
@unlink($path);
}
}
}
/**
* Recursively copy the files and directories of the origin directory
* into the target directory, i.e. "mirror" its contents.
*/
private static function recursiveMirror(string $originDir, string $targetDir): void
{
$originDir = rtrim($originDir, '\\/');
$targetDir = rtrim($targetDir, '\\/');
if (! is_dir($originDir)) {
echo sprintf('The origin directory "%s" was not found.', $originDir);
exit(1);
}
if (is_dir($targetDir)) {
echo sprintf('The target directory "%s" is existing. Run %s::recursiveDelete(\'%s\') first.', $targetDir, self::class, $targetDir);
exit(1);
}
@mkdir($targetDir, 0755, true);
$dirLen = strlen($originDir);
/** @var SplFileInfo $file */
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($originDir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
) as $file) {
$origin = $file->getPathname();
$target = $targetDir . substr($origin, $dirLen);
if ($file->isDir()) {
@mkdir($target, 0755);
} else {
@copy($origin, $target);
}
}
}
/**
* Copy Kint's init files into `system/ThirdParty/Kint/`
*/
private static function copyKintInitFiles(): void
{
$originDir = self::$dependencies['kint-src']['from'] . '../';
$targetDir = self::$dependencies['kint-src']['to'];
foreach (['init.php', 'init_helpers.php'] as $kintInit) {
@copy($originDir . $kintInit, $targetDir . $kintInit);
}
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use Laminas\Escaper\Escaper;
use Laminas\Escaper\Exception\ExceptionInterface;
use Laminas\Escaper\Exception\InvalidArgumentException as EscaperInvalidArgumentException;
use Laminas\Escaper\Exception\RuntimeException;
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;
use Psr\Log\NullLogger;
/**
* AUTOLOADER CONFIGURATION
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*/
class AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The '/app' and '/system' directories are already mapped for you.
* you may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, string>
*/
public $psr4 = [];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* @var array<int, string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* Do not change the name of the CodeIgniter namespace or your application
* will break.
*
* @var array<string, string>
*/
protected $corePsr4 = [
'CodeIgniter' => SYSTEMPATH,
'App' => APPPATH, // To ensure filters, etc still found,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* @var array<string, string>
*/
protected $coreClassmap = [
AbstractLogger::class => SYSTEMPATH . 'ThirdParty/PSR/Log/AbstractLogger.php',
InvalidArgumentException::class => SYSTEMPATH . 'ThirdParty/PSR/Log/InvalidArgumentException.php',
LoggerAwareInterface::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerAwareInterface.php',
LoggerAwareTrait::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerAwareTrait.php',
LoggerInterface::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerInterface.php',
LoggerTrait::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerTrait.php',
LogLevel::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LogLevel.php',
NullLogger::class => SYSTEMPATH . 'ThirdParty/PSR/Log/NullLogger.php',
ExceptionInterface::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/ExceptionInterface.php',
EscaperInvalidArgumentException::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/InvalidArgumentException.php',
RuntimeException::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/RuntimeException.php',
Escaper::class => SYSTEMPATH . 'ThirdParty/Escaper/Escaper.php',
];
/**
* -------------------------------------------------------------------
* Core Files
* -------------------------------------------------------------------
* List of files from the framework to be autoloaded early.
*
* @var array<int, string>
*/
protected $coreFiles = [];
/**
* Constructor.
*
* Merge the built-in and developer-configured psr4 and classmap,
* with preference to the developer ones.
*/
public function __construct()
{
if (isset($_SERVER['CI_ENVIRONMENT']) && $_SERVER['CI_ENVIRONMENT'] === 'testing') {
$this->psr4['Tests\Support'] = SUPPORTPATH;
$this->classmap['CodeIgniter\Log\TestLogger'] = SYSTEMPATH . 'Test/TestLogger.php';
$this->classmap['CIDatabaseTestCase'] = SYSTEMPATH . 'Test/CIDatabaseTestCase.php';
}
$this->psr4 = array_merge($this->corePsr4, $this->psr4);
$this->classmap = array_merge($this->coreClassmap, $this->classmap);
$this->files = [...$this->coreFiles, ...$this->files];
}
}
+216
View File
@@ -0,0 +1,216 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use Config\Encryption;
use Config\Modules;
use Config\Services;
use ReflectionClass;
use ReflectionException;
use RuntimeException;
/**
* Class BaseConfig
*
* Not intended to be used on its own, this class will attempt to
* automatically populate the child class' properties with values
* from the environment.
*
* These can be set within the .env file.
*/
class BaseConfig
{
/**
* An optional array of classes that will act as Registrars
* for rapidly setting config class properties.
*
* @var array
*/
public static $registrars = [];
/**
* Has module discovery happened yet?
*
* @var bool
*/
protected static $didDiscovery = false;
/**
* The modules configuration.
*
* @var Modules
*/
protected static $moduleConfig;
/**
* Will attempt to get environment variables with names
* that match the properties of the child class.
*
* The "shortPrefix" is the lowercase-only config class name.
*/
public function __construct()
{
static::$moduleConfig = config('Modules');
$this->registerProperties();
$properties = array_keys(get_object_vars($this));
$prefix = static::class;
$slashAt = strrpos($prefix, '\\');
$shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt + 1));
foreach ($properties as $property) {
$this->initEnvValue($this->{$property}, $property, $prefix, $shortPrefix);
if ($this instanceof Encryption && $property === 'key') {
if (strpos($this->{$property}, 'hex2bin:') === 0) {
// Handle hex2bin prefix
$this->{$property} = hex2bin(substr($this->{$property}, 8));
} elseif (strpos($this->{$property}, 'base64:') === 0) {
// Handle base64 prefix
$this->{$property} = base64_decode(substr($this->{$property}, 7), true);
}
}
}
}
/**
* Initialization an environment-specific configuration setting
*
* @param mixed $property
*
* @return void
*/
protected function initEnvValue(&$property, string $name, string $prefix, string $shortPrefix)
{
if (is_array($property)) {
foreach (array_keys($property) as $key) {
$this->initEnvValue($property[$key], "{$name}.{$key}", $prefix, $shortPrefix);
}
} elseif (($value = $this->getEnvValue($name, $prefix, $shortPrefix)) !== false && $value !== null) {
if ($value === 'false') {
$value = false;
} elseif ($value === 'true') {
$value = true;
}
if (is_bool($value)) {
$property = $value;
return;
}
$value = trim($value, '\'"');
if (is_int($property)) {
$value = (int) $value;
} elseif (is_float($property)) {
$value = (float) $value;
}
$property = $value;
}
}
/**
* Retrieve an environment-specific configuration setting
*
* @return string|null
*/
protected function getEnvValue(string $property, string $prefix, string $shortPrefix)
{
$shortPrefix = ltrim($shortPrefix, '\\');
$underscoreProperty = str_replace('.', '_', $property);
switch (true) {
case array_key_exists("{$shortPrefix}.{$property}", $_ENV):
return $_ENV["{$shortPrefix}.{$property}"];
case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_ENV):
return $_ENV["{$shortPrefix}_{$underscoreProperty}"];
case array_key_exists("{$shortPrefix}.{$property}", $_SERVER):
return $_SERVER["{$shortPrefix}.{$property}"];
case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_SERVER):
return $_SERVER["{$shortPrefix}_{$underscoreProperty}"];
case array_key_exists("{$prefix}.{$property}", $_ENV):
return $_ENV["{$prefix}.{$property}"];
case array_key_exists("{$prefix}_{$underscoreProperty}", $_ENV):
return $_ENV["{$prefix}_{$underscoreProperty}"];
case array_key_exists("{$prefix}.{$property}", $_SERVER):
return $_SERVER["{$prefix}.{$property}"];
case array_key_exists("{$prefix}_{$underscoreProperty}", $_SERVER):
return $_SERVER["{$prefix}_{$underscoreProperty}"];
default:
$value = getenv("{$shortPrefix}.{$property}");
$value = $value === false ? getenv("{$shortPrefix}_{$underscoreProperty}") : $value;
$value = $value === false ? getenv("{$prefix}.{$property}") : $value;
$value = $value === false ? getenv("{$prefix}_{$underscoreProperty}") : $value;
return $value === false ? null : $value;
}
}
/**
* Provides external libraries a simple way to register one or more
* options into a config file.
*
* @throws ReflectionException
*/
protected function registerProperties()
{
if (! static::$moduleConfig->shouldDiscover('registrars')) {
return;
}
if (! static::$didDiscovery) {
$locator = Services::locator();
$registrarsFiles = $locator->search('Config/Registrar.php');
foreach ($registrarsFiles as $file) {
$className = $locator->getClassname($file);
static::$registrars[] = new $className();
}
static::$didDiscovery = true;
}
$shortName = (new ReflectionClass($this))->getShortName();
// Check the registrar class for a method named after this class' shortName
foreach (static::$registrars as $callable) {
// ignore non-applicable registrars
if (! method_exists($callable, $shortName)) {
continue; // @codeCoverageIgnore
}
$properties = $callable::$shortName();
if (! is_array($properties)) {
throw new RuntimeException('Registrars must return an array of properties and their values.');
}
foreach ($properties as $property => $value) {
if (isset($this->{$property}) && is_array($this->{$property}) && is_array($value)) {
$this->{$property} = array_merge($this->{$property}, $value);
} else {
$this->{$property} = $value;
}
}
}
}
}
+384
View File
@@ -0,0 +1,384 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use CodeIgniter\Autoloader\Autoloader;
use CodeIgniter\Autoloader\FileLocator;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\CLI\Commands;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\MigrationRunner;
use CodeIgniter\Debug\Exceptions;
use CodeIgniter\Debug\Iterator;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Debug\Toolbar;
use CodeIgniter\Email\Email;
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\ContentSecurityPolicy;
use CodeIgniter\HTTP\CURLRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Negotiate;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Images\Handlers\BaseHandler;
use CodeIgniter\Language\Language;
use CodeIgniter\Log\Logger;
use CodeIgniter\Pager\Pager;
use CodeIgniter\Router\RouteCollection;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use CodeIgniter\Security\Security;
use CodeIgniter\Session\Session;
use CodeIgniter\Throttle\Throttler;
use CodeIgniter\Typography\Typography;
use CodeIgniter\Validation\Validation;
use CodeIgniter\View\Cell;
use CodeIgniter\View\Parser;
use CodeIgniter\View\RendererInterface;
use CodeIgniter\View\View;
use Config\App;
use Config\Autoload;
use Config\Cache;
use Config\ContentSecurityPolicy as CSPConfig;
use Config\Encryption;
use Config\Exceptions as ConfigExceptions;
use Config\Filters as ConfigFilters;
use Config\Format as ConfigFormat;
use Config\Honeypot as ConfigHoneyPot;
use Config\Images;
use Config\Migrations;
use Config\Modules;
use Config\Pager as ConfigPager;
use Config\Services as AppServices;
use Config\Toolbar as ConfigToolbar;
use Config\Validation as ConfigValidation;
use Config\View as ConfigView;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This is used in place of a Dependency Injection container primarily
* due to its simplicity, which allows a better long-term maintenance
* of the applications built on top of CodeIgniter. A bonus side-effect
* is that IDEs are able to determine what class you are calling
* whereas with DI Containers there usually isn't a way for them to do this.
*
* Warning: To allow overrides by service providers do not use static calls,
* instead call out to \Config\Services (imported as AppServices).
*
* @see http://blog.ircmaxell.com/2015/11/simple-easy-risk-and-change.html
* @see http://www.infoq.com/presentations/Simple-Made-Easy
*
* @method static CacheInterface cache(Cache $config = null, $getShared = true)
* @method static CLIRequest clirequest(App $config = null, $getShared = true)
* @method static CodeIgniter codeigniter(App $config = null, $getShared = true)
* @method static Commands commands($getShared = true)
* @method static void createRequest(App $config, bool $isCli = false)
* @method static ContentSecurityPolicy csp(CSPConfig $config = null, $getShared = true)
* @method static CURLRequest curlrequest($options = [], ResponseInterface $response = null, App $config = null, $getShared = true)
* @method static Email email($config = null, $getShared = true)
* @method static EncrypterInterface encrypter(Encryption $config = null, $getShared = false)
* @method static Exceptions exceptions(ConfigExceptions $config = null, IncomingRequest $request = null, Response $response = null, $getShared = true)
* @method static Filters filters(ConfigFilters $config = null, $getShared = true)
* @method static Format format(ConfigFormat $config = null, $getShared = true)
* @method static Honeypot honeypot(ConfigHoneyPot $config = null, $getShared = true)
* @method static BaseHandler image($handler = null, Images $config = null, $getShared = true)
* @method static IncomingRequest incomingrequest(?App $config = null, bool $getShared = true)
* @method static Iterator iterator($getShared = true)
* @method static Language language($locale = null, $getShared = true)
* @method static Logger logger($getShared = true)
* @method static MigrationRunner migrations(Migrations $config = null, ConnectionInterface $db = null, $getShared = true)
* @method static Negotiate negotiator(RequestInterface $request = null, $getShared = true)
* @method static Pager pager(ConfigPager $config = null, RendererInterface $view = null, $getShared = true)
* @method static Parser parser($viewPath = null, ConfigView $config = null, $getShared = true)
* @method static RedirectResponse redirectresponse(App $config = null, $getShared = true)
* @method static View renderer($viewPath = null, ConfigView $config = null, $getShared = true)
* @method static IncomingRequest|CLIRequest request(App $config = null, $getShared = true)
* @method static Response response(App $config = null, $getShared = true)
* @method static Router router(RouteCollectionInterface $routes = null, Request $request = null, $getShared = true)
* @method static RouteCollection routes($getShared = true)
* @method static Security security(App $config = null, $getShared = true)
* @method static Session session(App $config = null, $getShared = true)
* @method static Throttler throttler($getShared = true)
* @method static Timer timer($getShared = true)
* @method static Toolbar toolbar(ConfigToolbar $config = null, $getShared = true)
* @method static Typography typography($getShared = true)
* @method static URI uri($uri = null, $getShared = true)
* @method static Validation validation(ConfigValidation $config = null, $getShared = true)
* @method static Cell viewcell($getShared = true)
*/
class BaseService
{
/**
* Cache for instance of any services that
* have been requested as a "shared" instance.
* Keys should be lowercase service names.
*
* @var array
*/
protected static $instances = [];
/**
* Mock objects for testing which are returned if exist.
*
* @var array
*/
protected static $mocks = [];
/**
* Have we already discovered other Services?
*
* @var bool
*/
protected static $discovered = false;
/**
* A cache of other service classes we've found.
*
* @var array
*/
protected static $services = [];
/**
* A cache of the names of services classes found.
*
* @var array<string>
*/
private static array $serviceNames = [];
/**
* Returns a shared instance of any of the class' services.
*
* $key must be a name matching a service.
*
* @param mixed ...$params
*
* @return mixed
*/
protected static function getSharedInstance(string $key, ...$params)
{
$key = strtolower($key);
// Returns mock if exists
if (isset(static::$mocks[$key])) {
return static::$mocks[$key];
}
if (! isset(static::$instances[$key])) {
// Make sure $getShared is false
$params[] = false;
static::$instances[$key] = AppServices::$key(...$params);
}
return static::$instances[$key];
}
/**
* The Autoloader class is the central class that handles our
* spl_autoload_register method, and helper methods.
*
* @return 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 file locator provides utility methods for looking for non-classes
* within namespaced folders, as well as convenience methods for
* loading 'helpers', and 'libraries'.
*
* @return FileLocator
*/
public static function locator(bool $getShared = true)
{
if ($getShared) {
if (empty(static::$instances['locator'])) {
static::$instances['locator'] = new FileLocator(static::autoloader());
}
return static::$mocks['locator'] ?? static::$instances['locator'];
}
return new FileLocator(static::autoloader());
}
/**
* Provides the ability to perform case-insensitive calling of service
* names.
*
* @return mixed
*/
public static function __callStatic(string $name, array $arguments)
{
$service = static::serviceExists($name);
if ($service === null) {
return null;
}
return $service::$name(...$arguments);
}
/**
* Check if the requested service is defined and return the declaring
* class. Return null if not found.
*/
public static function serviceExists(string $name): ?string
{
static::buildServicesCache();
$services = array_merge(self::$serviceNames, [Services::class]);
$name = strtolower($name);
foreach ($services as $service) {
if (method_exists($service, $name)) {
return $service;
}
}
return null;
}
/**
* Reset shared instances and mocks for testing.
*/
public static function reset(bool $initAutoloader = true)
{
static::$mocks = [];
static::$instances = [];
if ($initAutoloader) {
static::autoloader()->initialize(new Autoload(), new Modules());
}
}
/**
* Resets any mock and shared instances for a single service.
*/
public static function resetSingle(string $name)
{
$name = strtolower($name);
unset(static::$mocks[$name], static::$instances[$name]);
}
/**
* Inject mock object for testing.
*
* @param mixed $mock
*/
public static function injectMock(string $name, $mock)
{
static::$mocks[strtolower($name)] = $mock;
}
/**
* 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.
*
* @return mixed
*
* @deprecated
*
* @codeCoverageIgnore
*/
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, [Services::class], true)) {
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($class, $name)) {
return $class::$name(...$arguments);
}
}
return null;
}
protected static function buildServicesCache(): void
{
if (! static::$discovered) {
$config = config('Modules');
if ($config->shouldDiscover('services')) {
$locator = static::locator();
$files = $locator->search('Config/Services');
// Get instances of all service classes and cache them locally.
foreach ($files as $file) {
$classname = $locator->getClassname($file);
if ($classname !== Services::class) {
self::$serviceNames[] = $classname;
static::$services[] = new $classname();
}
}
}
static::$discovered = true;
}
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
/**
* @deprecated Use CodeIgniter\Config\Factories::config()
*/
class Config
{
/**
* Create new configuration instances or return
* a shared instance
*
* @param string $name Configuration name
* @param bool $getShared Use shared instance
*
* @return mixed|null
*/
public static function get(string $name, bool $getShared = true)
{
return Factories::config($name, ['getShared' => $getShared]);
}
/**
* Helper method for injecting mock instances while testing.
*
* @param object $instance
*/
public static function injectMock(string $name, $instance)
{
Factories::injectMock('config', $name, $instance);
}
/**
* Resets the static arrays
*/
public static function reset()
{
Factories::reset('config');
}
}
+234
View File
@@ -0,0 +1,234 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use InvalidArgumentException;
/**
* Environment-specific configuration
*/
class DotEnv
{
/**
* The directory where the .env file can be located.
*
* @var string
*/
protected $path;
/**
* Builds the path to our file.
*/
public function __construct(string $path, string $file = '.env')
{
$this->path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file;
}
/**
* The main entry point, will load the .env file and process it
* so that we end up with all settings in the PHP environment vars
* (i.e. getenv(), $_ENV, and $_SERVER)
*/
public function load(): bool
{
$vars = $this->parse();
return $vars !== null;
}
/**
* Parse the .env file into an array of key => value
*/
public function parse(): ?array
{
// We don't want to enforce the presence of a .env file, they should be optional.
if (! is_file($this->path)) {
return null;
}
// Ensure the file is readable
if (! is_readable($this->path)) {
throw new InvalidArgumentException("The .env file is not readable: {$this->path}");
}
$vars = [];
$lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
// Is it a comment?
if (strpos(trim($line), '#') === 0) {
continue;
}
// If there is an equal sign, then we know we are assigning a variable.
if (strpos($line, '=') !== false) {
[$name, $value] = $this->normaliseVariable($line);
$vars[$name] = $value;
$this->setVariable($name, $value);
}
}
return $vars;
}
/**
* Sets the variable into the environment. Will parse the string
* first to look for {name}={value} pattern, ensure that nested
* variables are handled, and strip it of single and double quotes.
*/
protected function setVariable(string $name, string $value = '')
{
if (! getenv($name, true)) {
putenv("{$name}={$value}");
}
if (empty($_ENV[$name])) {
$_ENV[$name] = $value;
}
if (empty($_SERVER[$name])) {
$_SERVER[$name] = $value;
}
}
/**
* Parses for assignment, cleans the $name and $value, and ensures
* that nested variables are handled.
*/
public function normaliseVariable(string $name, string $value = ''): array
{
// Split our compound string into its parts.
if (strpos($name, '=') !== false) {
[$name, $value] = explode('=', $name, 2);
}
$name = trim($name);
$value = trim($value);
// Sanitize the name
$name = preg_replace('/^export[ \t]++(\S+)/', '$1', $name);
$name = str_replace(['\'', '"'], '', $name);
// Sanitize the value
$value = $this->sanitizeValue($value);
$value = $this->resolveNestedVariables($value);
return [$name, $value];
}
/**
* Strips quotes from the environment variable value.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*
* @throws InvalidArgumentException
*/
protected function sanitizeValue(string $value): string
{
if (! $value) {
return $value;
}
// Does it begin with a quote?
if (strpbrk($value[0], '"\'') !== false) {
// value starts with a quote
$quote = $value[0];
$regexPattern = sprintf(
'/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx',
$quote
);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\{$quote}", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = trim($parts[0]);
// Unquoted values cannot contain whitespace
if (preg_match('/\s+/', $value) > 0) {
throw new InvalidArgumentException('.env values containing spaces must be surrounded by quotes.');
}
}
return $value;
}
/**
* Resolve the nested variables.
*
* Look for ${varname} patterns in the variable value and replace with an existing
* environment variable.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*/
protected function resolveNestedVariables(string $value): string
{
if (strpos($value, '$') !== false) {
$value = preg_replace_callback(
'/\${([a-zA-Z0-9_\.]+)}/',
function ($matchedPatterns) {
$nestedVariable = $this->getVariable($matchedPatterns[1]);
if ($nestedVariable === null) {
return $matchedPatterns[0];
}
return $nestedVariable;
},
$value
);
}
return $value;
}
/**
* Search the different places for environment variables and return first value found.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*
* @return string|null
*/
protected function getVariable(string $name)
{
switch (true) {
case array_key_exists($name, $_ENV):
return $_ENV[$name];
case array_key_exists($name, $_SERVER):
return $_SERVER[$name];
default:
$value = getenv($name);
// switch getenv default to null
return $value === false ? null : $value;
}
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use Config\Services;
/**
* Factories for creating instances.
*
* Factories allow dynamic loading of components by their path
* and name. The "shared instance" implementation provides a
* large performance boost and helps keep code clean of lengthy
* instantiation checks.
*
* @method static BaseConfig config(...$arguments)
*/
class Factories
{
/**
* Store of component-specific options, usually
* from CodeIgniter\Config\Factory.
*
* @var array<string, array<string, bool|string|null>>
*/
protected static $options = [];
/**
* Explicit options for the Config
* component to prevent logic loops.
*
* @var array<string, bool|string|null>
*/
private static array $configOptions = [
'component' => 'config',
'path' => 'Config',
'instanceOf' => null,
'getShared' => true,
'preferApp' => true,
];
/**
* Mapping of class basenames (no namespace) to
* their instances.
*
* @var array<string, array<string, string>>
* @phpstan-var array<string, array<string, class-string>>
*/
protected static $basenames = [];
/**
* Store for instances of any component that
* has been requested as "shared".
* A multi-dimensional array with components as
* keys to the array of name-indexed instances.
*
* @var array<string, array<string, object>>
* @phpstan-var array<string, array<class-string, object>>
*/
protected static $instances = [];
/**
* This method is only to prevent PHPStan error.
* If we have a solution, we can remove this method.
* See https://github.com/codeigniter4/CodeIgniter4/pull/5358
*
* @template T of Model
*
* @phpstan-param class-string<T> $name
*
* @return Model
* @phpstan-return T
*/
public static function models(string $name, array $options = [], ?ConnectionInterface &$conn = null)
{
return self::__callStatic('models', [$name, $options, $conn]);
}
/**
* Loads instances based on the method component name. Either
* creates a new instance or returns an existing shared instance.
*
* @return object|null
*/
public static function __callStatic(string $component, array $arguments)
{
// First argument is the name, second is options
$name = trim(array_shift($arguments), '\\ ');
$options = array_shift($arguments) ?? [];
// Determine the component-specific options
$options = array_merge(self::getOptions(strtolower($component)), $options);
if (! $options['getShared']) {
if ($class = self::locateClass($options, $name)) {
return new $class(...$arguments);
}
return null;
}
$basename = self::getBasename($name);
// Check for an existing instance
if (isset(self::$basenames[$options['component']][$basename])) {
$class = self::$basenames[$options['component']][$basename];
// Need to verify if the shared instance matches the request
if (self::verifyInstanceOf($options, $class)) {
return self::$instances[$options['component']][$class];
}
}
// Try to locate the class
if (! $class = self::locateClass($options, $name)) {
return null;
}
self::$instances[$options['component']][$class] = new $class(...$arguments);
self::$basenames[$options['component']][$basename] = $class;
return self::$instances[$options['component']][$class];
}
/**
* Finds a component class
*
* @param array $options The array of component-specific directives
* @param string $name Class name, namespace optional
*/
protected static function locateClass(array $options, string $name): ?string
{
// Check for low-hanging fruit
if (class_exists($name, false) && self::verifyPreferApp($options, $name) && self::verifyInstanceOf($options, $name)) {
return $name;
}
// Determine the relative class names we need
$basename = self::getBasename($name);
$appname = $options['component'] === 'config'
? 'Config\\' . $basename
: rtrim(APP_NAMESPACE, '\\') . '\\' . $options['path'] . '\\' . $basename;
// If an App version was requested then see if it verifies
if ($options['preferApp'] && class_exists($appname) && self::verifyInstanceOf($options, $name)) {
return $appname;
}
// If we have ruled out an App version and the class exists then try it
if (class_exists($name) && self::verifyInstanceOf($options, $name)) {
return $name;
}
// Have to do this the hard way...
$locator = Services::locator();
// Check if the class was namespaced
if (strpos($name, '\\') !== false) {
if (! $file = $locator->locateFile($name, $options['path'])) {
return null;
}
$files = [$file];
}
// No namespace? Search for it
// Check all namespaces, prioritizing App and modules
elseif (! $files = $locator->search($options['path'] . DIRECTORY_SEPARATOR . $name)) {
return null;
}
// Check all files for a valid class
foreach ($files as $file) {
$class = $locator->getClassname($file);
if ($class && self::verifyInstanceOf($options, $class)) {
return $class;
}
}
return null;
}
/**
* Verifies that a class & config satisfy the "preferApp" option
*
* @param array $options The array of component-specific directives
* @param string $name Class name, namespace optional
*/
protected static function verifyPreferApp(array $options, string $name): bool
{
// Anything without that restriction passes
if (! $options['preferApp']) {
return true;
}
// Special case for Config since its App namespace is actually \Config
if ($options['component'] === 'config') {
return strpos($name, 'Config') === 0;
}
return strpos($name, APP_NAMESPACE) === 0;
}
/**
* Verifies that a class & config satisfy the "instanceOf" option
*
* @param array $options The array of component-specific directives
* @param string $name Class name, namespace optional
*/
protected static function verifyInstanceOf(array $options, string $name): bool
{
// Anything without that restriction passes
if (! $options['instanceOf']) {
return true;
}
return is_a($name, $options['instanceOf'], true);
}
/**
* Returns the component-specific configuration
*
* @param string $component Lowercase, plural component name
*
* @return array<string, bool|string|null>
*/
public static function getOptions(string $component): array
{
$component = strtolower($component);
// Check for a stored version
if (isset(self::$options[$component])) {
return self::$options[$component];
}
$values = $component === 'config'
// Handle Config as a special case to prevent logic loops
? self::$configOptions
// Load values from the best Factory configuration (will include Registrars)
: config('Factory')->{$component} ?? [];
return self::setOptions($component, $values);
}
/**
* Normalizes, stores, and returns the configuration for a specific component
*
* @param string $component Lowercase, plural component name
*
* @return array<string, bool|string|null> The result after applying defaults and normalization
*/
public static function setOptions(string $component, array $values): array
{
// Allow the config to replace the component name, to support "aliases"
$values['component'] = strtolower($values['component'] ?? $component);
// Reset this component so instances can be rediscovered with the updated config
self::reset($values['component']);
// If no path was available then use the component
$values['path'] = trim($values['path'] ?? ucfirst($values['component']), '\\ ');
// Add defaults for any missing values
$values = array_merge(Factory::$default, $values);
// Store the result to the supplied name and potential alias
self::$options[$component] = $values;
self::$options[$values['component']] = $values;
return $values;
}
/**
* Resets the static arrays, optionally just for one component
*
* @param string|null $component Lowercase, plural component name
*/
public static function reset(?string $component = null)
{
if ($component) {
unset(
static::$options[$component],
static::$basenames[$component],
static::$instances[$component]
);
return;
}
static::$options = [];
static::$basenames = [];
static::$instances = [];
}
/**
* Helper method for injecting mock instances
*
* @param string $component Lowercase, plural component name
* @param string $name The name of the instance
*/
public static function injectMock(string $component, string $name, object $instance)
{
// Force a configuration to exist for this component
$component = strtolower($component);
self::getOptions($component);
$class = get_class($instance);
$basename = self::getBasename($name);
self::$instances[$component][$class] = $instance;
self::$basenames[$component][$basename] = $class;
}
/**
* Gets a basename from a class name, namespaced or not.
*/
public static function getBasename(string $name): string
{
// Determine the basename
if ($basename = strrchr($name, '\\')) {
return substr($basename, 1);
}
return $name;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
/**
* Factories Configuration file.
*
* Provides overriding directives for how
* Factories should handle discovery and
* instantiation of specific components.
* Each property should correspond to the
* lowercase, plural component name.
*/
class Factory extends BaseConfig
{
/**
* Supplies a default set of options to merge for
* all unspecified factory components.
*
* @var array
*/
public static $default = [
'component' => null,
'path' => null,
'instanceOf' => null,
'getShared' => true,
'preferApp' => true,
];
/**
* Specifies that Models should always favor child
* classes to allow easy extension of module Models.
*
* @var array
*/
public $models = [
'preferApp' => true,
];
}
+113
View File
@@ -0,0 +1,113 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
/**
* Describes foreign characters for transliteration with the text helper.
*/
class ForeignCharacters
{
/**
* Without further ado, the list of foreign characters.
*/
public $characterList = [
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a',
'/Б/' => 'B',
'/б/' => 'b',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Д/' => 'D',
'/д/' => 'd',
'/Ð|Ď|Đ|Δ/' => 'Dj',
'/ð|ď|đ|δ/' => 'dj',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Ε|Έ|Ẽ|Ẻ|Ẹ|Ề|Ế|Ễ|Ể|Ệ|Е|Э/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě|έ|ε|ẽ|ẻ|ẹ|ề|ế|ễ|ể|ệ|е|э/' => 'e',
'/Ф/' => 'F',
'/ф/' => 'f',
'/Ĝ|Ğ|Ġ|Ģ|Γ|Г|Ґ/' => 'G',
'/ĝ|ğ|ġ|ģ|γ|г|ґ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|Η|Ή|Ί|Ι|Ϊ|Ỉ|Ị|И|Ы/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|η|ή|ί|ι|ϊ|ỉ|ị|и|ы|ї/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ|Κ|К/' => 'K',
'/ķ|κ|к/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł|Λ|Л/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł|λ|л/' => 'l',
'/М/' => 'M',
'/м/' => 'm',
'/Ñ|Ń|Ņ|Ň|Ν|Н/' => 'N',
'/ñ|ń|ņ|ň|ʼn|ν|н/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ο|Ό|Ω|Ώ|Ỏ|Ọ|Ồ|Ố|Ỗ|Ổ|Ộ|Ờ|Ớ|Ỡ|Ở|Ợ|О/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ο|ό|ω|ώ|ỏ|ọ|ồ|ố|ỗ|ổ|ộ|ờ|ớ|ỡ|ở|ợ|о/' => 'o',
'/П/' => 'P',
'/п/' => 'p',
'/Ŕ|Ŗ|Ř|Ρ|Р/' => 'R',
'/ŕ|ŗ|ř|ρ|р/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š|Σ|С/' => 'S',
'/ś|ŝ|ş|ș|š|ſ|σ|ς|с/' => 's',
'/Ț|Ţ|Ť|Ŧ|τ|Т/' => 'T',
'/ț|ţ|ť|ŧ|т/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|Ũ|Ủ|Ụ|Ừ|Ứ|Ữ|Ử|Ự|У/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|υ|ύ|ϋ|ủ|ụ|ừ|ứ|ữ|ử|ự|у/' => 'u',
'/Ƴ|Ɏ|Ỵ|Ẏ|Ӳ|Ӯ|Ў|Ý|Ÿ|Ŷ|Υ|Ύ|Ϋ|Ỳ|Ỹ|Ỷ|Ỵ|Й/' => 'Y',
'/ẙ|ʏ|ƴ|ɏ|ỵ|ẏ|ӳ|ӯ|ў|ý|ÿ|ŷ|ỳ|ỹ|ỷ|ỵ|й/' => 'y',
'/В/' => 'V',
'/в/' => 'v',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž|Ζ|З/' => 'Z',
'/ź|ż|ž|ζ|з/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f',
'/ξ/' => 'ks',
'/π/' => 'p',
'/β/' => 'v',
'/μ/' => 'm',
'/ψ/' => 'ps',
'/Ё/' => 'Yo',
'/ё/' => 'yo',
'/Є/' => 'Ye',
'/є/' => 'ye',
'/Ї/' => 'Yi',
'/Ж/' => 'Zh',
'/ж/' => 'zh',
'/Х/' => 'Kh',
'/х/' => 'kh',
'/Ц/' => 'Ts',
'/ц/' => 'ts',
'/Ч/' => 'Ch',
'/ч/' => 'ch',
'/Ш/' => 'Sh',
'/ш/' => 'sh',
'/Щ/' => 'Shch',
'/щ/' => 'shch',
'/Ъ|ъ|Ь|ь/' => '',
'/Ю/' => 'Yu',
'/ю/' => 'yu',
'/Я/' => 'Ya',
'/я/' => 'ya',
];
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BaseConfig
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string,string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(?css|js|map|htm?|xml|json|webmanifest|tff|eot|woff?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
/**
* Disables Registrars to prevent modules from altering the restrictions.
*/
final protected function registerProperties()
{
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
/*
* System URI Routing
*
* This file contains any routing to system tools, such as command-line
* tools for migrations, etc.
*
* It is called by Config\Routes, and has the $routes RouteCollection
* already loaded up and ready for us to use.
*/
// CLI Catchall - uses a _remap to call Commands
$routes->cli('ci(:any)', '\CodeIgniter\CLI\CommandRunner::index/$1');
+777
View File
@@ -0,0 +1,777 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use CodeIgniter\Cache\CacheFactory;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\CLI\Commands;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\MigrationRunner;
use CodeIgniter\Debug\Exceptions;
use CodeIgniter\Debug\Iterator;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Debug\Toolbar;
use CodeIgniter\Email\Email;
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Encryption\Encryption;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\ContentSecurityPolicy;
use CodeIgniter\HTTP\CURLRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Negotiate;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\URI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Images\Handlers\BaseHandler;
use CodeIgniter\Language\Language;
use CodeIgniter\Log\Logger;
use CodeIgniter\Pager\Pager;
use CodeIgniter\Router\RouteCollection;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use CodeIgniter\Security\Security;
use CodeIgniter\Session\Handlers\Database\MySQLiHandler;
use CodeIgniter\Session\Handlers\Database\PostgreHandler;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use CodeIgniter\Session\Session;
use CodeIgniter\Throttle\Throttler;
use CodeIgniter\Typography\Typography;
use CodeIgniter\Validation\Validation;
use CodeIgniter\View\Cell;
use CodeIgniter\View\Parser;
use CodeIgniter\View\RendererInterface;
use CodeIgniter\View\View;
use Config\App;
use Config\Cache;
use Config\ContentSecurityPolicy as CSPConfig;
use Config\Database;
use Config\Email as EmailConfig;
use Config\Encryption as EncryptionConfig;
use Config\Exceptions as ExceptionsConfig;
use Config\Filters as FiltersConfig;
use Config\Format as FormatConfig;
use Config\Honeypot as HoneypotConfig;
use Config\Images;
use Config\Migrations;
use Config\Pager as PagerConfig;
use Config\Services as AppServices;
use Config\Toolbar as ToolbarConfig;
use Config\Validation as ValidationConfig;
use Config\View as ViewConfig;
use Locale;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This is used in place of a Dependency Injection container primarily
* due to its simplicity, which allows a better long-term maintenance
* of the applications built on top of CodeIgniter. A bonus side-effect
* is that IDEs are able to determine what class you are calling
* whereas with DI Containers there usually isn't a way for them to do this.
*
* @see http://blog.ircmaxell.com/2015/11/simple-easy-risk-and-change.html
* @see http://www.infoq.com/presentations/Simple-Made-Easy
*/
class Services extends BaseService
{
/**
* The cache class provides a simple way to store and retrieve
* complex data for later.
*
* @return CacheInterface
*/
public static function cache(?Cache $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('cache', $config);
}
$config ??= new Cache();
return CacheFactory::getHandler($config);
}
/**
* The CLI Request class provides for ways to interact with
* a command line request.
*
* @return CLIRequest
*
* @internal
*/
public static function clirequest(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('clirequest', $config);
}
$config ??= config('App');
return new CLIRequest($config);
}
/**
* CodeIgniter, the core of the framework.
*
* @return CodeIgniter
*/
public static function codeigniter(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('codeigniter', $config);
}
$config ??= config('App');
return new CodeIgniter($config);
}
/**
* The commands utility for running and working with CLI commands.
*
* @return Commands
*/
public static function commands(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('commands');
}
return new Commands();
}
/**
* Content Security Policy
*
* @return ContentSecurityPolicy
*/
public static function csp(?CSPConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('csp', $config);
}
$config ??= config('ContentSecurityPolicy');
return new ContentSecurityPolicy($config);
}
/**
* The CURL Request class acts as a simple HTTP client for interacting
* with other servers, typically through APIs.
*
* @return CURLRequest
*/
public static function curlrequest(array $options = [], ?ResponseInterface $response = null, ?App $config = null, bool $getShared = true)
{
if ($getShared === true) {
return static::getSharedInstance('curlrequest', $options, $response, $config);
}
$config ??= config('App');
$response ??= new Response($config);
return new CURLRequest(
$config,
new URI($options['base_uri'] ?? null),
$response,
$options
);
}
/**
* The Email class allows you to send email via mail, sendmail, SMTP.
*
* @param array|EmailConfig|null $config
*
* @return Email
*/
public static function email($config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('email', $config);
}
if (empty($config) || ! (is_array($config) || $config instanceof EmailConfig)) {
$config = config('Email');
}
return new Email($config);
}
/**
* The Encryption class provides two-way encryption.
*
* @param bool $getShared
*
* @return EncrypterInterface Encryption handler
*/
public static function encrypter(?EncryptionConfig $config = null, $getShared = false)
{
if ($getShared === true) {
return static::getSharedInstance('encrypter', $config);
}
$config ??= config('Encryption');
$encryption = new Encryption($config);
return $encryption->initialize($config);
}
/**
* The Exceptions class holds the methods that handle:
*
* - set_exception_handler
* - set_error_handler
* - register_shutdown_function
*
* @return Exceptions
*/
public static function exceptions(
?ExceptionsConfig $config = null,
?IncomingRequest $request = null,
?Response $response = null,
bool $getShared = true
) {
if ($getShared) {
return static::getSharedInstance('exceptions', $config, $request, $response);
}
$config ??= config('Exceptions');
$request ??= AppServices::request();
$response ??= AppServices::response();
return new Exceptions($config, $request, $response);
}
/**
* Filters allow you to run tasks before and/or after a controller
* is executed. During before filters, the request can be modified,
* and actions taken based on the request, while after filters can
* act on or modify the response itself before it is sent to the client.
*
* @return Filters
*/
public static function filters(?FiltersConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('filters', $config);
}
$config ??= config('Filters');
return new Filters($config, AppServices::request(), AppServices::response());
}
/**
* The Format class is a convenient place to create Formatters.
*
* @return Format
*/
public static function format(?FormatConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('format', $config);
}
$config ??= config('Format');
return new Format($config);
}
/**
* The Honeypot provides a secret input on forms that bots should NOT
* fill in, providing an additional safeguard when accepting user input.
*
* @return Honeypot
*/
public static function honeypot(?HoneypotConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('honeypot', $config);
}
$config ??= config('Honeypot');
return new Honeypot($config);
}
/**
* Acts as a factory for ImageHandler classes and returns an instance
* of the handler. Used like Services::image()->withFile($path)->rotate(90)->save();
*
* @return BaseHandler
*/
public static function image(?string $handler = null, ?Images $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('image', $handler, $config);
}
$config ??= config('Images');
$handler = $handler ?: $config->defaultHandler;
$class = $config->handlers[$handler];
return new $class($config);
}
/**
* The Iterator class provides a simple way of looping over a function
* and timing the results and memory usage. Used when debugging and
* optimizing applications.
*
* @return Iterator
*/
public static function iterator(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('iterator');
}
return new Iterator();
}
/**
* Responsible for loading the language string translations.
*
* @return Language
*/
public static function language(?string $locale = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('language', $locale)->setLocale($locale);
}
if (AppServices::request() instanceof IncomingRequest) {
$requestLocale = AppServices::request()->getLocale();
} else {
$requestLocale = Locale::getDefault();
}
// Use '?:' for empty string check
$locale = $locale ?: $requestLocale;
return new Language($locale);
}
/**
* The Logger class is a PSR-3 compatible Logging class that supports
* multiple handlers that process the actual logging.
*
* @return Logger
*/
public static function logger(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('logger');
}
return new Logger(config('Logger'));
}
/**
* Return the appropriate Migration runner.
*
* @return MigrationRunner
*/
public static function migrations(?Migrations $config = null, ?ConnectionInterface $db = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('migrations', $config, $db);
}
$config ??= config('Migrations');
return new MigrationRunner($config, $db);
}
/**
* The Negotiate class provides the content negotiation features for
* working the request to determine correct language, encoding, charset,
* and more.
*
* @return Negotiate
*/
public static function negotiator(?RequestInterface $request = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('negotiator', $request);
}
$request ??= AppServices::request();
return new Negotiate($request);
}
/**
* Return the appropriate pagination handler.
*
* @return Pager
*/
public static function pager(?PagerConfig $config = null, ?RendererInterface $view = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('pager', $config, $view);
}
$config ??= config('Pager');
$view ??= AppServices::renderer();
return new Pager($config, $view);
}
/**
* The Parser is a simple template parser.
*
* @return Parser
*/
public static function parser(?string $viewPath = null, ?ViewConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('parser', $viewPath, $config);
}
$viewPath = $viewPath ?: config('Paths')->viewDirectory;
$config ??= config('View');
return new Parser($config, $viewPath, AppServices::locator(), CI_DEBUG, AppServices::logger());
}
/**
* The Renderer class is the class that actually displays a file to the user.
* The default View class within CodeIgniter is intentionally simple, but this
* service could easily be replaced by a template engine if the user needed to.
*
* @return View
*/
public static function renderer(?string $viewPath = null, ?ViewConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('renderer', $viewPath, $config);
}
$viewPath = $viewPath ?: config('Paths')->viewDirectory;
$config ??= config('View');
return new View($config, $viewPath, AppServices::locator(), CI_DEBUG, AppServices::logger());
}
/**
* Returns the current Request object.
*
* createRequest() injects IncomingRequest or CLIRequest.
*
* @return CLIRequest|IncomingRequest
*
* @deprecated The parameter $config and $getShared are deprecated.
*/
public static function request(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('request', $config);
}
// @TODO remove the following code for backward compatibility
return static::incomingrequest($config, $getShared);
}
/**
* Create the current Request object, either IncomingRequest or CLIRequest.
*
* This method is called from CodeIgniter::getRequestObject().
*
* @internal
*/
public static function createRequest(App $config, bool $isCli = false): void
{
if ($isCli) {
$request = AppServices::clirequest($config);
} else {
$request = AppServices::incomingrequest($config);
// guess at protocol if needed
$request->setProtocolVersion($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1');
}
// Inject the request object into Services::request().
static::$instances['request'] = $request;
}
/**
* The IncomingRequest class models an HTTP request.
*
* @return IncomingRequest
*
* @internal
*/
public static function incomingrequest(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('request', $config);
}
$config ??= config('App');
return new IncomingRequest(
$config,
AppServices::uri(),
'php://input',
new UserAgent()
);
}
/**
* The Response class models an HTTP response.
*
* @return Response
*/
public static function response(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('response', $config);
}
$config ??= config('App');
return new Response($config);
}
/**
* The Redirect class provides nice way of working with redirects.
*
* @return RedirectResponse
*/
public static function redirectresponse(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('redirectresponse', $config);
}
$config ??= config('App');
$response = new RedirectResponse($config);
$response->setProtocolVersion(AppServices::request()->getProtocolVersion());
return $response;
}
/**
* The Routes service is a class that allows for easily building
* a collection of routes.
*
* @return RouteCollection
*/
public static function routes(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('routes');
}
return new RouteCollection(AppServices::locator(), config('Modules'));
}
/**
* The Router class uses a RouteCollection's array of routes, and determines
* the correct Controller and Method to execute.
*
* @return Router
*/
public static function router(?RouteCollectionInterface $routes = null, ?Request $request = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('router', $routes, $request);
}
$routes ??= AppServices::routes();
$request ??= AppServices::request();
return new Router($routes, $request);
}
/**
* The Security class provides a few handy tools for keeping the site
* secure, most notably the CSRF protection tools.
*
* @return Security
*/
public static function security(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('security', $config);
}
$config ??= config('App');
return new Security($config);
}
/**
* Return the session manager.
*
* @return Session
*/
public static function session(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('session', $config);
}
$config ??= config('App');
$logger = AppServices::logger();
$driverName = $config->sessionDriver;
if ($driverName === DatabaseHandler::class) {
$DBGroup = $config->sessionDBGroup ?? config(Database::class)->defaultGroup;
$db = Database::connect($DBGroup);
$driver = $db->getPlatform();
if ($driver === 'MySQLi') {
$driverName = MySQLiHandler::class;
} elseif ($driver === 'Postgre') {
$driverName = PostgreHandler::class;
}
}
$driver = new $driverName($config, AppServices::request()->getIPAddress());
$driver->setLogger($logger);
$session = new Session($driver, $config);
$session->setLogger($logger);
if (session_status() === PHP_SESSION_NONE) {
$session->start();
}
return $session;
}
/**
* The Throttler class provides a simple method for implementing
* rate limiting in your applications.
*
* @return Throttler
*/
public static function throttler(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('throttler');
}
return new Throttler(AppServices::cache());
}
/**
* The Timer class provides a simple way to Benchmark portions of your
* application.
*
* @return Timer
*/
public static function timer(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('timer');
}
return new Timer();
}
/**
* Return the debug toolbar.
*
* @return Toolbar
*/
public static function toolbar(?ToolbarConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('toolbar', $config);
}
$config ??= config('Toolbar');
return new Toolbar($config);
}
/**
* The URI class provides a way to model and manipulate URIs.
*
* @param string $uri
*
* @return URI
*/
public static function uri(?string $uri = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('uri', $uri);
}
return new URI($uri);
}
/**
* The Validation class provides tools for validating input data.
*
* @return Validation
*/
public static function validation(?ValidationConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('validation', $config);
}
$config ??= config('Validation');
return new Validation($config, AppServices::renderer());
}
/**
* View cells are intended to let you insert HTML into view
* that has been generated by any callable in the system.
*
* @return Cell
*/
public static function viewcell(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('viewcell');
}
return new Cell(AppServices::cache());
}
/**
* The Typography class provides a way to format text in semantically relevant ways.
*
* @return Typography
*/
public static function typography(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('typography');
}
return new Typography();
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Config;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* View configuration
*/
class View extends BaseConfig
{
/**
* When false, the view method will clear the data between each
* call.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
*
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*/
public $plugins = [];
/**
* Built-in View filters.
*
* @var array
*/
protected $coreFilters = [
'abs' => '\abs',
'capitalize' => '\CodeIgniter\View\Filters::capitalize',
'date' => '\CodeIgniter\View\Filters::date',
'date_modify' => '\CodeIgniter\View\Filters::date_modify',
'default' => '\CodeIgniter\View\Filters::default',
'esc' => '\CodeIgniter\View\Filters::esc',
'excerpt' => '\CodeIgniter\View\Filters::excerpt',
'highlight' => '\CodeIgniter\View\Filters::highlight',
'highlight_code' => '\CodeIgniter\View\Filters::highlight_code',
'limit_words' => '\CodeIgniter\View\Filters::limit_words',
'limit_chars' => '\CodeIgniter\View\Filters::limit_chars',
'local_currency' => '\CodeIgniter\View\Filters::local_currency',
'local_number' => '\CodeIgniter\View\Filters::local_number',
'lower' => '\strtolower',
'nl2br' => '\CodeIgniter\View\Filters::nl2br',
'number_format' => '\number_format',
'prose' => '\CodeIgniter\View\Filters::prose',
'round' => '\CodeIgniter\View\Filters::round',
'strip_tags' => '\strip_tags',
'title' => '\CodeIgniter\View\Filters::title',
'upper' => '\strtoupper',
];
/**
* Built-in View plugins.
*
* @var array
*/
protected $corePlugins = [
'csp_script_nonce' => '\CodeIgniter\View\Plugins::cspScriptNonce',
'csp_style_nonce' => '\CodeIgniter\View\Plugins::cspStyleNonce',
'current_url' => '\CodeIgniter\View\Plugins::currentURL',
'previous_url' => '\CodeIgniter\View\Plugins::previousURL',
'mailto' => '\CodeIgniter\View\Plugins::mailto',
'safe_mailto' => '\CodeIgniter\View\Plugins::safeMailto',
'lang' => '\CodeIgniter\View\Plugins::lang',
'validation_errors' => '\CodeIgniter\View\Plugins::validationErrors',
'route' => '\CodeIgniter\View\Plugins::route',
'siteURL' => '\CodeIgniter\View\Plugins::siteURL',
];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var class-string<ViewDecoratorInterface>[]
*/
public array $decorators = [];
/**
* Merge the built-in and developer-configured filters and plugins,
* with preference to the developer ones.
*/
public function __construct()
{
$this->filters = array_merge($this->coreFilters, $this->filters);
$this->plugins = array_merge($this->corePlugins, $this->plugins);
parent::__construct();
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Exceptions\ValidationException;
use CodeIgniter\Validation\Validation;
use Config\Services;
use Psr\Log\LoggerInterface;
/**
* Class Controller
*/
class Controller
{
/**
* Helpers that will be automatically loaded on class instantiation.
*
* @var array
*/
protected $helpers = [];
/**
* Instance of the main Request object.
*
* @var RequestInterface
*/
protected $request;
/**
* Instance of the main response object.
*
* @var ResponseInterface
*/
protected $response;
/**
* Instance of logger to use.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Should enforce HTTPS access for all methods in this controller.
*
* @var int Number of seconds to set HSTS header
*/
protected $forceHTTPS = 0;
/**
* Once validation has been run, will hold the Validation instance.
*
* @var Validation
*/
protected $validator;
/**
* Constructor.
*
* @throws HTTPException
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->request = $request;
$this->response = $response;
$this->logger = $logger;
if ($this->forceHTTPS > 0) {
$this->forceHTTPS($this->forceHTTPS);
}
// Autoload helper files.
helper($this->helpers);
}
/**
* A convenience method to use when you need to ensure that a single
* method is reached only via HTTPS. If it isn't, then a redirect
* will happen back to this method and HSTS header will be sent
* to have modern browsers transform requests automatically.
*
* @param int $duration The number of seconds this link should be
* considered secure for. Only with HSTS header.
* Default value is 1 year.
*
* @throws HTTPException
*/
protected function forceHTTPS(int $duration = 31_536_000)
{
force_https($duration, $this->request, $this->response);
}
/**
* Provides a simple way to tie into the main CodeIgniter class and
* tell it how long to cache the current page for.
*/
protected function cachePage(int $time)
{
CodeIgniter::cache($time);
}
/**
* Handles "auto-loading" helper files.
*
* @deprecated Use `helper` function instead of using this method.
*
* @codeCoverageIgnore
*/
protected function loadHelpers()
{
if (empty($this->helpers)) {
return;
}
helper($this->helpers);
}
/**
* A shortcut to performing validation on Request data.
*
* @param array|string $rules
* @param array $messages An array of custom error messages
*/
protected function validate($rules, array $messages = []): bool
{
$this->setValidator($rules, $messages);
return $this->validator->withRequest($this->request)->run();
}
/**
* A shortcut to performing validation on any input data.
*
* @param array $data The data to validate
* @param array|string $rules
* @param array $messages An array of custom error messages
* @param string|null $dbGroup The database group to use
*/
protected function validateData(array $data, $rules, array $messages = [], ?string $dbGroup = null): bool
{
$this->setValidator($rules, $messages);
return $this->validator->run($data, null, $dbGroup);
}
/**
* @param array|string $rules
*/
private function setValidator($rules, array $messages): void
{
$this->validator = Services::validation();
// If you replace the $rules array with the name of the group
if (is_string($rules)) {
$validation = config('Validation');
// If the rule wasn't found in the \Config\Validation, we
// should throw an exception so the developer can find it.
if (! isset($validation->{$rules})) {
throw ValidationException::forRuleNotFound($rules);
}
// If no error message is defined, use the error message in the Config\Validation file
if (! $messages) {
$errorName = $rules . '_errors';
$messages = $validation->{$errorName} ?? [];
}
$rules = $validation->{$rules};
}
$this->validator->setRules($rules, $messages);
}
}
@@ -0,0 +1,109 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
use DateTimeInterface;
/**
* Interface for a fresh Cookie instance with selected attribute(s)
* only changed from the original instance.
*/
interface CloneableCookieInterface extends CookieInterface
{
/**
* Creates a new Cookie with a new cookie prefix.
*
* @return static
*/
public function withPrefix(string $prefix = '');
/**
* Creates a new Cookie with a new name.
*
* @return static
*/
public function withName(string $name);
/**
* Creates a new Cookie with new value.
*
* @return static
*/
public function withValue(string $value);
/**
* Creates a new Cookie with a new cookie expires time.
*
* @param DateTimeInterface|int|string $expires
*
* @return static
*/
public function withExpires($expires);
/**
* Creates a new Cookie that will expire the cookie from the browser.
*
* @return static
*/
public function withExpired();
/**
* Creates a new Cookie that will virtually never expire from the browser.
*
* @return static
*
* @deprecated See https://github.com/codeigniter4/CodeIgniter4/pull/6413
*/
public function withNeverExpiring();
/**
* Creates a new Cookie with a new path on the server the cookie is available.
*
* @return static
*/
public function withPath(?string $path);
/**
* Creates a new Cookie with a new domain the cookie is available.
*
* @return static
*/
public function withDomain(?string $domain);
/**
* Creates a new Cookie with a new "Secure" attribute.
*
* @return static
*/
public function withSecure(bool $secure = true);
/**
* Creates a new Cookie with a new "HttpOnly" attribute
*
* @return static
*/
public function withHTTPOnly(bool $httponly = true);
/**
* Creates a new Cookie with a new "SameSite" attribute.
*
* @return static
*/
public function withSameSite(string $samesite);
/**
* Creates a new Cookie with URL encoding option updated.
*
* @return static
*/
public function withRaw(bool $raw = true);
}
+783
View File
@@ -0,0 +1,783 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
use ArrayAccess;
use CodeIgniter\Cookie\Exceptions\CookieException;
use Config\Cookie as CookieConfig;
use DateTimeInterface;
use InvalidArgumentException;
use LogicException;
use ReturnTypeWillChange;
/**
* A `Cookie` class represents an immutable HTTP cookie value object.
*
* Being immutable, modifying one or more of its attributes will return
* a new `Cookie` instance, rather than modifying itself. Users should
* reassign this new instance to a new variable to capture it.
*
* ```php
* $cookie = new Cookie('test_cookie', 'test_value');
* $cookie->getName(); // test_cookie
*
* $cookie->withName('prod_cookie');
* $cookie->getName(); // test_cookie
*
* $cookie2 = $cookie->withName('prod_cookie');
* $cookie2->getName(); // prod_cookie
* ```
*/
class Cookie implements ArrayAccess, CloneableCookieInterface
{
/**
* @var string
*/
protected $prefix = '';
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $value;
/**
* @var int
*/
protected $expires;
/**
* @var string
*/
protected $path = '/';
/**
* @var string
*/
protected $domain = '';
/**
* @var bool
*/
protected $secure = false;
/**
* @var bool
*/
protected $httponly = true;
/**
* @var string
*/
protected $samesite = self::SAMESITE_LAX;
/**
* @var bool
*/
protected $raw = false;
/**
* Default attributes for a Cookie object. The keys here are the
* lowercase attribute names. Do not camelCase!
*
* @var array<string, mixed>
*/
private static array $defaults = [
'prefix' => '',
'expires' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => true,
'samesite' => self::SAMESITE_LAX,
'raw' => false,
];
/**
* A cookie name can be any US-ASCII characters, except control characters,
* spaces, tabs, or separator characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
private static string $reservedCharsList = "=,; \t\r\n\v\f()<>@:\\\"/[]?{}";
/**
* Set the default attributes to a Cookie instance by injecting
* the values from the `CookieConfig` config or an array.
*
* This method is called from Response::__construct().
*
* @param array<string, mixed>|CookieConfig $config
*
* @return array<string, mixed> The old defaults array. Useful for resetting.
*/
public static function setDefaults($config = [])
{
$oldDefaults = self::$defaults;
$newDefaults = [];
if ($config instanceof CookieConfig) {
$newDefaults = [
'prefix' => $config->prefix,
'expires' => $config->expires,
'path' => $config->path,
'domain' => $config->domain,
'secure' => $config->secure,
'httponly' => $config->httponly,
'samesite' => $config->samesite,
'raw' => $config->raw,
];
} elseif (is_array($config)) {
$newDefaults = $config;
}
// This array union ensures that even if passed `$config` is not
// `CookieConfig` or `array`, no empty defaults will occur.
self::$defaults = $newDefaults + $oldDefaults;
return $oldDefaults;
}
// =========================================================================
// CONSTRUCTORS
// =========================================================================
/**
* Create a new Cookie instance from a `Set-Cookie` header.
*
* @return static
*
* @throws CookieException
*/
public static function fromHeaderString(string $cookie, bool $raw = false)
{
$data = self::$defaults;
$data['raw'] = $raw;
$parts = preg_split('/\;[\s]*/', $cookie);
$part = explode('=', array_shift($parts), 2);
$name = $raw ? $part[0] : urldecode($part[0]);
$value = isset($part[1]) ? ($raw ? $part[1] : urldecode($part[1])) : '';
unset($part);
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
[$attr, $val] = explode('=', $part);
} else {
$attr = $part;
$val = true;
}
$data[strtolower($attr)] = $val;
}
return new static($name, $value, $data);
}
/**
* Construct a new Cookie instance.
*
* @param string $name The cookie's name
* @param string $value The cookie's value
* @param array<string, mixed> $options The cookie's options
*
* @throws CookieException
*/
final public function __construct(string $name, string $value = '', array $options = [])
{
$options += self::$defaults;
$options['expires'] = static::convertExpiresTimestamp($options['expires']);
// If both `Expires` and `Max-Age` are set, `Max-Age` has precedence.
if (isset($options['max-age']) && is_numeric($options['max-age'])) {
$options['expires'] = time() + (int) $options['max-age'];
unset($options['max-age']);
}
// to preserve backward compatibility with array-based cookies in previous CI versions
$prefix = ($options['prefix'] === '') ? self::$defaults['prefix'] : $options['prefix'];
$path = $options['path'] ?: self::$defaults['path'];
$domain = $options['domain'] ?: self::$defaults['domain'];
// empty string SameSite should use the default for browsers
$samesite = $options['samesite'] ?: self::$defaults['samesite'];
$raw = $options['raw'];
$secure = $options['secure'];
$httponly = $options['httponly'];
$this->validateName($name, $raw);
$this->validatePrefix($prefix, $secure, $path, $domain);
$this->validateSameSite($samesite, $secure);
$this->prefix = $prefix;
$this->name = $name;
$this->value = $value;
$this->expires = static::convertExpiresTimestamp($options['expires']);
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
$this->httponly = $httponly;
$this->samesite = ucfirst(strtolower($samesite));
$this->raw = $raw;
}
// =========================================================================
// GETTERS
// =========================================================================
/**
* {@inheritDoc}
*/
public function getId(): string
{
return implode(';', [$this->getPrefixedName(), $this->getPath(), $this->getDomain()]);
}
/**
* {@inheritDoc}
*/
public function getPrefix(): string
{
return $this->prefix;
}
/**
* {@inheritDoc}
*/
public function getName(): string
{
return $this->name;
}
/**
* {@inheritDoc}
*/
public function getPrefixedName(): string
{
$name = $this->getPrefix();
if ($this->isRaw()) {
$name .= $this->getName();
} else {
$search = str_split(self::$reservedCharsList);
$replace = array_map('rawurlencode', $search);
$name .= str_replace($search, $replace, $this->getName());
}
return $name;
}
/**
* {@inheritDoc}
*/
public function getValue(): string
{
return $this->value;
}
/**
* {@inheritDoc}
*/
public function getExpiresTimestamp(): int
{
return $this->expires;
}
/**
* {@inheritDoc}
*/
public function getExpiresString(): string
{
return gmdate(self::EXPIRES_FORMAT, $this->expires);
}
/**
* {@inheritDoc}
*/
public function isExpired(): bool
{
return $this->expires === 0 || $this->expires < time();
}
/**
* {@inheritDoc}
*/
public function getMaxAge(): int
{
$maxAge = $this->expires - time();
return $maxAge >= 0 ? $maxAge : 0;
}
/**
* {@inheritDoc}
*/
public function getPath(): string
{
return $this->path;
}
/**
* {@inheritDoc}
*/
public function getDomain(): string
{
return $this->domain;
}
/**
* {@inheritDoc}
*/
public function isSecure(): bool
{
return $this->secure;
}
/**
* {@inheritDoc}
*/
public function isHTTPOnly(): bool
{
return $this->httponly;
}
/**
* {@inheritDoc}
*/
public function getSameSite(): string
{
return $this->samesite;
}
/**
* {@inheritDoc}
*/
public function isRaw(): bool
{
return $this->raw;
}
/**
* {@inheritDoc}
*/
public function getOptions(): array
{
// This is the order of options in `setcookie`. DO NOT CHANGE.
return [
'expires' => $this->expires,
'path' => $this->path,
'domain' => $this->domain,
'secure' => $this->secure,
'httponly' => $this->httponly,
'samesite' => $this->samesite ?: ucfirst(self::SAMESITE_LAX),
];
}
// =========================================================================
// CLONING
// =========================================================================
/**
* {@inheritDoc}
*/
public function withPrefix(string $prefix = '')
{
$this->validatePrefix($prefix, $this->secure, $this->path, $this->domain);
$cookie = clone $this;
$cookie->prefix = $prefix;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withName(string $name)
{
$this->validateName($name, $this->raw);
$cookie = clone $this;
$cookie->name = $name;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withValue(string $value)
{
$cookie = clone $this;
$cookie->value = $value;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withExpires($expires)
{
$cookie = clone $this;
$cookie->expires = static::convertExpiresTimestamp($expires);
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withExpired()
{
$cookie = clone $this;
$cookie->expires = 0;
return $cookie;
}
/**
* @deprecated See https://github.com/codeigniter4/CodeIgniter4/pull/6413
*/
public function withNeverExpiring()
{
$cookie = clone $this;
$cookie->expires = time() + 5 * YEAR;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withPath(?string $path)
{
$path = $path ?: self::$defaults['path'];
$this->validatePrefix($this->prefix, $this->secure, $path, $this->domain);
$cookie = clone $this;
$cookie->path = $path;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withDomain(?string $domain)
{
$domain ??= self::$defaults['domain'];
$this->validatePrefix($this->prefix, $this->secure, $this->path, $domain);
$cookie = clone $this;
$cookie->domain = $domain;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withSecure(bool $secure = true)
{
$this->validatePrefix($this->prefix, $secure, $this->path, $this->domain);
$this->validateSameSite($this->samesite, $secure);
$cookie = clone $this;
$cookie->secure = $secure;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withHTTPOnly(bool $httponly = true)
{
$cookie = clone $this;
$cookie->httponly = $httponly;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withSameSite(string $samesite)
{
$this->validateSameSite($samesite, $this->secure);
$cookie = clone $this;
$cookie->samesite = ucfirst(strtolower($samesite));
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withRaw(bool $raw = true)
{
$this->validateName($this->name, $raw);
$cookie = clone $this;
$cookie->raw = $raw;
return $cookie;
}
// =========================================================================
// ARRAY ACCESS FOR BC
// =========================================================================
/**
* Whether an offset exists.
*
* @param mixed $offset
*/
public function offsetExists($offset): bool
{
return $offset === 'expire' ? true : property_exists($this, $offset);
}
/**
* Offset to retrieve.
*
* @param mixed $offset
*
* @return mixed
*
* @throws InvalidArgumentException
*/
#[ReturnTypeWillChange]
public function offsetGet($offset)
{
if (! $this->offsetExists($offset)) {
throw new InvalidArgumentException(sprintf('Undefined offset "%s".', $offset));
}
return $offset === 'expire' ? $this->expires : $this->{$offset};
}
/**
* Offset to set.
*
* @param mixed $offset
* @param mixed $value
*
* @throws LogicException
*/
public function offsetSet($offset, $value): void
{
throw new LogicException(sprintf('Cannot set values of properties of %s as it is immutable.', static::class));
}
/**
* Offset to unset.
*
* @param mixed $offset
*
* @throws LogicException
*/
public function offsetUnset($offset): void
{
throw new LogicException(sprintf('Cannot unset values of properties of %s as it is immutable.', static::class));
}
// =========================================================================
// CONVERTERS
// =========================================================================
/**
* {@inheritDoc}
*/
public function toHeaderString(): string
{
return $this->__toString();
}
/**
* {@inheritDoc}
*/
public function __toString()
{
$cookieHeader = [];
if ($this->getValue() === '') {
$cookieHeader[] = $this->getPrefixedName() . '=deleted';
$cookieHeader[] = 'Expires=' . gmdate(self::EXPIRES_FORMAT, 0);
$cookieHeader[] = 'Max-Age=0';
} else {
$value = $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
$cookieHeader[] = sprintf('%s=%s', $this->getPrefixedName(), $value);
if ($this->getExpiresTimestamp() !== 0) {
$cookieHeader[] = 'Expires=' . $this->getExpiresString();
$cookieHeader[] = 'Max-Age=' . $this->getMaxAge();
}
}
if ($this->getPath() !== '') {
$cookieHeader[] = 'Path=' . $this->getPath();
}
if ($this->getDomain() !== '') {
$cookieHeader[] = 'Domain=' . $this->getDomain();
}
if ($this->isSecure()) {
$cookieHeader[] = 'Secure';
}
if ($this->isHTTPOnly()) {
$cookieHeader[] = 'HttpOnly';
}
$samesite = $this->getSameSite();
if ($samesite === '') {
// modern browsers warn in console logs that an empty SameSite attribute
// will be given the `Lax` value
$samesite = self::SAMESITE_LAX;
}
$cookieHeader[] = 'SameSite=' . ucfirst(strtolower($samesite));
return implode('; ', $cookieHeader);
}
/**
* {@inheritDoc}
*/
public function toArray(): array
{
return [
'name' => $this->name,
'value' => $this->value,
'prefix' => $this->prefix,
'raw' => $this->raw,
] + $this->getOptions();
}
/**
* Converts expires time to Unix format.
*
* @param DateTimeInterface|int|string $expires
*/
protected static function convertExpiresTimestamp($expires = 0): int
{
if ($expires instanceof DateTimeInterface) {
$expires = $expires->format('U');
}
if (! is_string($expires) && ! is_int($expires)) {
throw CookieException::forInvalidExpiresTime(gettype($expires));
}
if (! is_numeric($expires)) {
$expires = strtotime($expires);
if ($expires === false) {
throw CookieException::forInvalidExpiresValue();
}
}
return $expires > 0 ? (int) $expires : 0;
}
// =========================================================================
// VALIDATION
// =========================================================================
/**
* Validates the cookie name per RFC 2616.
*
* If `$raw` is true, names should not contain invalid characters
* as `setrawcookie()` will reject this.
*
* @throws CookieException
*/
protected function validateName(string $name, bool $raw): void
{
if ($raw && strpbrk($name, self::$reservedCharsList) !== false) {
throw CookieException::forInvalidCookieName($name);
}
if ($name === '') {
throw CookieException::forEmptyCookieName();
}
}
/**
* Validates the special prefixes if some attribute requirements are met.
*
* @throws CookieException
*/
protected function validatePrefix(string $prefix, bool $secure, string $path, string $domain): void
{
if (strpos($prefix, '__Secure-') === 0 && ! $secure) {
throw CookieException::forInvalidSecurePrefix();
}
if (strpos($prefix, '__Host-') === 0 && (! $secure || $domain !== '' || $path !== '/')) {
throw CookieException::forInvalidHostPrefix();
}
}
/**
* Validates the `SameSite` to be within the allowed types.
*
* @throws CookieException
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
*/
protected function validateSameSite(string $samesite, bool $secure): void
{
if ($samesite === '') {
$samesite = self::$defaults['samesite'];
}
if ($samesite === '') {
$samesite = self::SAMESITE_LAX;
}
if (! in_array(strtolower($samesite), self::ALLOWED_SAMESITE_VALUES, true)) {
throw CookieException::forInvalidSameSite($samesite);
}
if (strtolower($samesite) === self::SAMESITE_NONE && ! $secure) {
throw CookieException::forInvalidSameSiteNone();
}
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
/**
* Interface for a value object representation of an HTTP cookie.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
*/
interface CookieInterface
{
/**
* Cookies will be sent in all contexts, i.e in responses to both
* first-party and cross-origin requests. If `SameSite=None` is set,
* the cookie `Secure` attribute must also be set (or the cookie will be blocked).
*/
public const SAMESITE_NONE = 'none';
/**
* Cookies are not sent on normal cross-site subrequests (for example to
* load images or frames into a third party site), but are sent when a
* user is navigating to the origin site (i.e. when following a link).
*/
public const SAMESITE_LAX = 'lax';
/**
* Cookies will only be sent in a first-party context and not be sent
* along with requests initiated by third party websites.
*/
public const SAMESITE_STRICT = 'strict';
/**
* RFC 6265 allowed values for the "SameSite" attribute.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
*/
public const ALLOWED_SAMESITE_VALUES = [
self::SAMESITE_NONE,
self::SAMESITE_LAX,
self::SAMESITE_STRICT,
];
/**
* Expires date format.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date
* @see https://tools.ietf.org/html/rfc7231#section-7.1.1.2
*/
public const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T';
/**
* Returns a unique identifier for the cookie consisting
* of its prefixed name, path, and domain.
*/
public function getId(): string;
/**
* Gets the cookie prefix.
*/
public function getPrefix(): string;
/**
* Gets the cookie name.
*/
public function getName(): string;
/**
* Gets the cookie name prepended with the prefix, if any.
*/
public function getPrefixedName(): string;
/**
* Gets the cookie value.
*/
public function getValue(): string;
/**
* Gets the time in Unix timestamp the cookie expires.
*/
public function getExpiresTimestamp(): int;
/**
* Gets the formatted expires time.
*/
public function getExpiresString(): string;
/**
* Checks if the cookie is expired.
*/
public function isExpired(): bool;
/**
* Gets the "Max-Age" cookie attribute.
*/
public function getMaxAge(): int;
/**
* Gets the "Path" cookie attribute.
*/
public function getPath(): string;
/**
* Gets the "Domain" cookie attribute.
*/
public function getDomain(): string;
/**
* Gets the "Secure" cookie attribute.
*
* Checks if the cookie is only sent to the server when a request is made
* with the `https:` scheme (except on `localhost`), and therefore is more
* resistent to man-in-the-middle attacks.
*/
public function isSecure(): bool;
/**
* Gets the "HttpOnly" cookie attribute.
*
* Checks if JavaScript is forbidden from accessing the cookie.
*/
public function isHTTPOnly(): bool;
/**
* Gets the "SameSite" cookie attribute.
*/
public function getSameSite(): string;
/**
* Checks if the cookie should be sent with no URL encoding.
*/
public function isRaw(): bool;
/**
* Gets the options that are passable to the `setcookie` variant
* available on PHP 7.3+
*
* @return array<string, mixed>
*/
public function getOptions(): array;
/**
* Returns the Cookie as a header value.
*/
public function toHeaderString(): string;
/**
* Returns the string representation of the Cookie object.
*
* @return string
*/
public function __toString();
/**
* Returns the array representation of the Cookie object.
*
* @return array<string, mixed>
*/
public function toArray(): array;
}
+256
View File
@@ -0,0 +1,256 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
use ArrayIterator;
use CodeIgniter\Cookie\Exceptions\CookieException;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* The CookieStore object represents an immutable collection of `Cookie` value objects.
*
* @implements IteratorAggregate<string, Cookie>
*/
class CookieStore implements Countable, IteratorAggregate
{
/**
* The cookie collection.
*
* @var array<string, Cookie>
*/
protected $cookies = [];
/**
* Creates a CookieStore from an array of `Set-Cookie` headers.
*
* @param string[] $headers
*
* @return static
*
* @throws CookieException
*/
public static function fromCookieHeaders(array $headers, bool $raw = false)
{
/**
* @var Cookie[] $cookies
*/
$cookies = array_filter(array_map(static function (string $header) use ($raw) {
try {
return Cookie::fromHeaderString($header, $raw);
} catch (CookieException $e) {
log_message('error', (string) $e);
return false;
}
}, $headers));
return new static($cookies);
}
/**
* @param Cookie[] $cookies
*
* @throws CookieException
*/
final public function __construct(array $cookies)
{
$this->validateCookies($cookies);
foreach ($cookies as $cookie) {
$this->cookies[$cookie->getId()] = $cookie;
}
}
/**
* Checks if a `Cookie` object identified by name and
* prefix is present in the collection.
*/
public function has(string $name, string $prefix = '', ?string $value = null): bool
{
$name = $prefix . $name;
foreach ($this->cookies as $cookie) {
if ($cookie->getPrefixedName() !== $name) {
continue;
}
if ($value === null) {
return true; // for BC
}
return $cookie->getValue() === $value;
}
return false;
}
/**
* Retrieves an instance of `Cookie` identified by a name and prefix.
* This throws an exception if not found.
*
* @throws CookieException
*/
public function get(string $name, string $prefix = ''): Cookie
{
$name = $prefix . $name;
foreach ($this->cookies as $cookie) {
if ($cookie->getPrefixedName() === $name) {
return $cookie;
}
}
throw CookieException::forUnknownCookieInstance([$name, $prefix]);
}
/**
* Store a new cookie and return a new collection. The original collection
* is left unchanged.
*
* @return static
*/
public function put(Cookie $cookie)
{
$store = clone $this;
$store->cookies[$cookie->getId()] = $cookie;
return $store;
}
/**
* Removes a cookie from a collection and returns an updated collection.
* The original collection is left unchanged.
*
* Removing a cookie from the store **DOES NOT** delete it from the browser.
* If you intend to delete a cookie *from the browser*, you must put an empty
* value cookie with the same name to the store.
*
* @return static
*/
public function remove(string $name, string $prefix = '')
{
$default = Cookie::setDefaults();
$id = implode(';', [$prefix . $name, $default['path'], $default['domain']]);
$store = clone $this;
foreach (array_keys($store->cookies) as $index) {
if ($index === $id) {
unset($store->cookies[$index]);
}
}
return $store;
}
/**
* Dispatches all cookies in store.
*
* @deprecated Response should dispatch cookies.
*/
public function dispatch(): void
{
foreach ($this->cookies as $cookie) {
$name = $cookie->getPrefixedName();
$value = $cookie->getValue();
$options = $cookie->getOptions();
if ($cookie->isRaw()) {
$this->setRawCookie($name, $value, $options);
} else {
$this->setCookie($name, $value, $options);
}
}
$this->clear();
}
/**
* Returns all cookie instances in store.
*
* @return array<string, Cookie>
*/
public function display(): array
{
return $this->cookies;
}
/**
* Clears the cookie collection.
*/
public function clear(): void
{
$this->cookies = [];
}
/**
* Gets the Cookie count in this collection.
*/
public function count(): int
{
return count($this->cookies);
}
/**
* Gets the iterator for the cookie collection.
*
* @return Traversable<string, Cookie>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->cookies);
}
/**
* Validates all cookies passed to be instances of Cookie.
*
* @throws CookieException
*/
protected function validateCookies(array $cookies): void
{
foreach ($cookies as $index => $cookie) {
$type = is_object($cookie) ? get_class($cookie) : gettype($cookie);
if (! $cookie instanceof Cookie) {
throw CookieException::forInvalidCookieInstance([static::class, Cookie::class, $type, $index]);
}
}
}
/**
* Extracted call to `setrawcookie()` in order to run unit tests on it.
*
* @codeCoverageIgnore
*
* @deprecated
*/
protected function setRawCookie(string $name, string $value, array $options): void
{
setrawcookie($name, $value, $options);
}
/**
* Extracted call to `setcookie()` in order to run unit tests on it.
*
* @codeCoverageIgnore
*
* @deprecated
*/
protected function setCookie(string $name, string $value, array $options): void
{
setcookie($name, $value, $options);
}
}
@@ -0,0 +1,127 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
/**
* CookieException is thrown for invalid cookies initialization and management.
*/
class CookieException extends FrameworkException
{
/**
* Thrown for invalid type given for the "Expires" attribute.
*
* @return static
*/
public static function forInvalidExpiresTime(string $type)
{
return new static(lang('Cookie.invalidExpiresTime', [$type]));
}
/**
* Thrown when the value provided for "Expires" is invalid.
*
* @return static
*/
public static function forInvalidExpiresValue()
{
return new static(lang('Cookie.invalidExpiresValue'));
}
/**
* Thrown when the cookie name contains invalid characters per RFC 2616.
*
* @return static
*/
public static function forInvalidCookieName(string $name)
{
return new static(lang('Cookie.invalidCookieName', [$name]));
}
/**
* Thrown when the cookie name is empty.
*
* @return static
*/
public static function forEmptyCookieName()
{
return new static(lang('Cookie.emptyCookieName'));
}
/**
* Thrown when using the `__Secure-` prefix but the `Secure` attribute
* is not set to true.
*
* @return static
*/
public static function forInvalidSecurePrefix()
{
return new static(lang('Cookie.invalidSecurePrefix'));
}
/**
* Thrown when using the `__Host-` prefix but the `Secure` flag is not
* set, the `Domain` is set, and the `Path` is not `/`.
*
* @return static
*/
public static function forInvalidHostPrefix()
{
return new static(lang('Cookie.invalidHostPrefix'));
}
/**
* Thrown when the `SameSite` attribute given is not of the valid types.
*
* @return static
*/
public static function forInvalidSameSite(string $sameSite)
{
return new static(lang('Cookie.invalidSameSite', [$sameSite]));
}
/**
* Thrown when the `SameSite` attribute is set to `None` but the `Secure`
* attribute is not set.
*
* @return static
*/
public static function forInvalidSameSiteNone()
{
return new static(lang('Cookie.invalidSameSiteNone'));
}
/**
* Thrown when the `CookieStore` class is filled with invalid Cookie objects.
*
* @param array<int|string> $data
*
* @return static
*/
public static function forInvalidCookieInstance(array $data)
{
return new static(lang('Cookie.invalidCookieInstance', $data));
}
/**
* Thrown when the queried Cookie object does not exist in the cookie collection.
*
* @param string[] $data
*
* @return static
*/
public static function forUnknownCookieInstance(array $data)
{
return new static(lang('Cookie.unknownCookieInstance', $data));
}
}
+536
View File
@@ -0,0 +1,536 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;
use Config\Exceptions as ExceptionsConfig;
use Config\Paths;
use ErrorException;
use Psr\Log\LogLevel;
use Throwable;
/**
* Exceptions manager
*/
class Exceptions
{
use ResponseTrait;
/**
* Nesting level of the output buffering mechanism
*
* @var int
*/
public $ob_level;
/**
* The path to the directory containing the
* cli and html error view directories.
*
* @var string
*/
protected $viewPath;
/**
* Config for debug exceptions.
*
* @var ExceptionsConfig
*/
protected $config;
/**
* The request.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* The outgoing response.
*
* @var Response
*/
protected $response;
/**
* @param CLIRequest|IncomingRequest $request
*/
public function __construct(ExceptionsConfig $config, $request, Response $response)
{
$this->ob_level = ob_get_level();
$this->viewPath = rtrim($config->errorViewPath, '\\/ ') . DIRECTORY_SEPARATOR;
$this->config = $config;
$this->request = $request;
$this->response = $response;
// workaround for upgraded users
if (! isset($this->config->sensitiveDataInTrace)) {
$this->config->sensitiveDataInTrace = [];
}
}
/**
* Responsible for registering the error, exception and shutdown
* handling of our application.
*
* @codeCoverageIgnore
*/
public function initialize()
{
set_exception_handler([$this, 'exceptionHandler']);
set_error_handler([$this, 'errorHandler']);
register_shutdown_function([$this, 'shutdownHandler']);
}
/**
* Catches any uncaught errors and exceptions, including most Fatal errors
* (Yay PHP7!). Will log the error, display it if display_errors is on,
* and fire an event that allows custom actions to be taken at this point.
*
* @codeCoverageIgnore
*/
public function exceptionHandler(Throwable $exception)
{
[$statusCode, $exitCode] = $this->determineCodes($exception);
if ($this->config->log === true && ! in_array($statusCode, $this->config->ignoreCodes, true)) {
log_message('critical', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
'message' => $exception->getMessage(),
'exFile' => clean_path($exception->getFile()), // {file} refers to THIS file
'exLine' => $exception->getLine(), // {line} refers to THIS line
'trace' => self::renderBacktrace($exception->getTrace()),
]);
}
if (! is_cli()) {
try {
$this->response->setStatusCode($statusCode);
} catch (HTTPException $e) {
// Workaround for invalid HTTP status code.
$statusCode = 500;
$this->response->setStatusCode($statusCode);
}
if (! headers_sent()) {
header(sprintf('HTTP/%s %s %s', $this->request->getProtocolVersion(), $this->response->getStatusCode(), $this->response->getReasonPhrase()), true, $statusCode);
}
if (strpos($this->request->getHeaderLine('accept'), 'text/html') === false) {
$this->respond(ENVIRONMENT === 'development' ? $this->collectVars($exception, $statusCode) : '', $statusCode)->send();
exit($exitCode);
}
}
$this->render($exception, $statusCode);
exit($exitCode);
}
/**
* The callback to be registered to `set_error_handler()`.
*
* @return bool
*
* @throws ErrorException
*
* @codeCoverageIgnore
*/
public function errorHandler(int $severity, string $message, ?string $file = null, ?int $line = null)
{
if (error_reporting() & $severity) {
// @TODO Remove if Faker is fixed.
if ($this->isFakerDeprecationError($severity, $message, $file, $line)) {
// Ignore the error.
return true;
}
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false; // return false to propagate the error to PHP standard error handler
}
/**
* Workaround for Faker deprecation errors in PHP 8.2.
*
* @see https://github.com/FakerPHP/Faker/issues/479
*/
private function isFakerDeprecationError(int $severity, string $message, ?string $file = null, ?int $line = null)
{
if (
$severity === E_DEPRECATED
&& strpos($file, VENDORPATH . 'fakerphp/faker/') !== false
&& $message === 'Use of "static" in callables is deprecated'
) {
log_message(
LogLevel::WARNING,
'[DEPRECATED] {message} in {errFile} on line {errLine}.',
[
'message' => $message,
'errFile' => clean_path($file ?? ''),
'errLine' => $line ?? 0,
]
);
return true;
}
return false;
}
/**
* Checks to see if any errors have happened during shutdown that
* need to be caught and handle them.
*
* @codeCoverageIgnore
*/
public function shutdownHandler()
{
$error = error_get_last();
if ($error === null) {
return;
}
['type' => $type, 'message' => $message, 'file' => $file, 'line' => $line] = $error;
if (in_array($type, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE], true)) {
$this->exceptionHandler(new ErrorException($message, 0, $type, $file, $line));
}
}
/**
* Determines the view to display based on the exception thrown,
* whether an HTTP or CLI request, etc.
*
* @return string The path and filename of the view file to use
*/
protected function determineView(Throwable $exception, string $templatePath): string
{
// Production environments should have a custom exception file.
$view = 'production.php';
$templatePath = rtrim($templatePath, '\\/ ') . DIRECTORY_SEPARATOR;
if (str_ireplace(['off', 'none', 'no', 'false', 'null'], '', ini_get('display_errors'))) {
$view = 'error_exception.php';
}
// 404 Errors
if ($exception instanceof PageNotFoundException) {
return 'error_404.php';
}
// Allow for custom views based upon the status code
if (is_file($templatePath . 'error_' . $exception->getCode() . '.php')) {
return 'error_' . $exception->getCode() . '.php';
}
return $view;
}
/**
* Given an exception and status code will display the error to the client.
*/
protected function render(Throwable $exception, int $statusCode)
{
// Determine possible directories of error views
$path = $this->viewPath;
$altPath = rtrim((new Paths())->viewDirectory, '\\/ ') . DIRECTORY_SEPARATOR . 'errors' . DIRECTORY_SEPARATOR;
$path .= (is_cli() ? 'cli' : 'html') . DIRECTORY_SEPARATOR;
$altPath .= (is_cli() ? 'cli' : 'html') . DIRECTORY_SEPARATOR;
// Determine the views
$view = $this->determineView($exception, $path);
$altView = $this->determineView($exception, $altPath);
// Check if the view exists
if (is_file($path . $view)) {
$viewFile = $path . $view;
} elseif (is_file($altPath . $altView)) {
$viewFile = $altPath . $altView;
}
if (! isset($viewFile)) {
echo 'The error view files were not found. Cannot render exception trace.';
exit(1);
}
if (ob_get_level() > $this->ob_level + 1) {
ob_end_clean();
}
echo(function () use ($exception, $statusCode, $viewFile): string {
$vars = $this->collectVars($exception, $statusCode);
extract($vars, EXTR_SKIP);
ob_start();
include $viewFile;
return ob_get_clean();
})();
}
/**
* Gathers the variables that will be made available to the view.
*/
protected function collectVars(Throwable $exception, int $statusCode): array
{
$trace = $exception->getTrace();
if ($this->config->sensitiveDataInTrace !== []) {
$this->maskSensitiveData($trace, $this->config->sensitiveDataInTrace);
}
return [
'title' => get_class($exception),
'type' => get_class($exception),
'code' => $statusCode,
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $trace,
];
}
/**
* Mask sensitive data in the trace.
*
* @param array|object $trace
*/
protected function maskSensitiveData(&$trace, array $keysToMask, string $path = '')
{
foreach ($keysToMask as $keyToMask) {
$explode = explode('/', $keyToMask);
$index = end($explode);
if (strpos(strrev($path . '/' . $index), strrev($keyToMask)) === 0) {
if (is_array($trace) && array_key_exists($index, $trace)) {
$trace[$index] = '******************';
} elseif (is_object($trace) && property_exists($trace, $index) && isset($trace->{$index})) {
$trace->{$index} = '******************';
}
}
}
if (is_object($trace)) {
$trace = get_object_vars($trace);
}
if (is_array($trace)) {
foreach ($trace as $pathKey => $subarray) {
$this->maskSensitiveData($subarray, $keysToMask, $path . '/' . $pathKey);
}
}
}
/**
* Determines the HTTP status code and the exit status code for this request.
*/
protected function determineCodes(Throwable $exception): array
{
$statusCode = abs($exception->getCode());
if ($statusCode < 100 || $statusCode > 599) {
$exitStatus = $statusCode + EXIT__AUTO_MIN;
if ($exitStatus > EXIT__AUTO_MAX) {
$exitStatus = EXIT_ERROR;
}
$statusCode = 500;
} else {
$exitStatus = EXIT_ERROR;
}
return [$statusCode, $exitStatus];
}
// --------------------------------------------------------------------
// Display Methods
// --------------------------------------------------------------------
/**
* This makes nicer looking paths for the error output.
*
* @deprecated Use dedicated `clean_path()` function.
*/
public static function cleanPath(string $file): string
{
switch (true) {
case strpos($file, APPPATH) === 0:
$file = 'APPPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(APPPATH));
break;
case strpos($file, SYSTEMPATH) === 0:
$file = 'SYSTEMPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(SYSTEMPATH));
break;
case strpos($file, FCPATH) === 0:
$file = 'FCPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(FCPATH));
break;
case defined('VENDORPATH') && strpos($file, VENDORPATH) === 0:
$file = 'VENDORPATH' . DIRECTORY_SEPARATOR . substr($file, strlen(VENDORPATH));
break;
}
return $file;
}
/**
* Describes memory usage in real-world units. Intended for use
* with memory_get_usage, etc.
*/
public static function describeMemory(int $bytes): string
{
if ($bytes < 1024) {
return $bytes . 'B';
}
if ($bytes < 1_048_576) {
return round($bytes / 1024, 2) . 'KB';
}
return round($bytes / 1_048_576, 2) . 'MB';
}
/**
* Creates a syntax-highlighted version of a PHP file.
*
* @return bool|string
*/
public static function highlightFile(string $file, int $lineNumber, int $lines = 15)
{
if (empty($file) || ! is_readable($file)) {
return false;
}
// Set our highlight colors:
if (function_exists('ini_set')) {
ini_set('highlight.comment', '#767a7e; font-style: italic');
ini_set('highlight.default', '#c7c7c7');
ini_set('highlight.html', '#06B');
ini_set('highlight.keyword', '#f1ce61;');
ini_set('highlight.string', '#869d6a');
}
try {
$source = file_get_contents($file);
} catch (Throwable $e) {
return false;
}
$source = str_replace(["\r\n", "\r"], "\n", $source);
$source = explode("\n", highlight_string($source, true));
$source = str_replace('<br />', "\n", $source[1]);
$source = explode("\n", str_replace("\r\n", "\n", $source));
// Get just the part to show
$start = max($lineNumber - (int) round($lines / 2), 0);
// Get just the lines we need to display, while keeping line numbers...
$source = array_splice($source, $start, $lines, true);
// Used to format the line number in the source
$format = '% ' . strlen((string) ($start + $lines)) . 'd';
$out = '';
// Because the highlighting may have an uneven number
// of open and close span tags on one line, we need
// to ensure we can close them all to get the lines
// showing correctly.
$spans = 1;
foreach ($source as $n => $row) {
$spans += substr_count($row, '<span') - substr_count($row, '</span');
$row = str_replace(["\r", "\n"], ['', ''], $row);
if (($n + $start + 1) === $lineNumber) {
preg_match_all('#<[^>]+>#', $row, $tags);
$out .= sprintf(
"<span class='line highlight'><span class='number'>{$format}</span> %s\n</span>%s",
$n + $start + 1,
strip_tags($row),
implode('', $tags[0])
);
} else {
$out .= sprintf('<span class="line"><span class="number">' . $format . '</span> %s', $n + $start + 1, $row) . "\n";
}
}
if ($spans > 0) {
$out .= str_repeat('</span>', $spans);
}
return '<pre><code>' . $out . '</code></pre>';
}
private static function renderBacktrace(array $backtrace): string
{
$backtraces = [];
foreach ($backtrace as $index => $trace) {
$frame = $trace + ['file' => '[internal function]', 'line' => '', 'class' => '', 'type' => '', 'args' => []];
if ($frame['file'] !== '[internal function]') {
$frame['file'] = sprintf('%s(%s)', $frame['file'], $frame['line']);
}
unset($frame['line']);
$idx = $index;
$idx = str_pad((string) ++$idx, 2, ' ', STR_PAD_LEFT);
$args = implode(', ', array_map(static function ($value): string {
switch (true) {
case is_object($value):
return sprintf('Object(%s)', get_class($value));
case is_array($value):
return $value !== [] ? '[...]' : '[]';
case $value === null:
return 'null';
case is_resource($value):
return sprintf('resource (%s)', get_resource_type($value));
case is_string($value):
return var_export(clean_path($value), true);
default:
return var_export($value, true);
}
}, $frame['args']));
$backtraces[] = sprintf(
'%s %s: %s%s%s(%s)',
$idx,
clean_path($frame['file']),
$frame['class'],
$frame['type'],
$frame['function'],
$args
);
}
return implode("\n", $backtraces);
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use Closure;
/**
* Iterator for debugging.
*/
class Iterator
{
/**
* Stores the tests that we are to run.
*
* @var array
*/
protected $tests = [];
/**
* Stores the results of each of the tests.
*
* @var array
*/
protected $results = [];
/**
* Adds a test to run.
*
* Tests are simply closures that the user can define any sequence of
* things to happen during the test.
*
* @return $this
*/
public function add(string $name, Closure $closure)
{
$name = strtolower($name);
$this->tests[$name] = $closure;
return $this;
}
/**
* Runs through all of the tests that have been added, recording
* time to execute the desired number of iterations, and the approximate
* memory usage used during those iterations.
*
* @return string|null
*/
public function run(int $iterations = 1000, bool $output = true)
{
foreach ($this->tests as $name => $test) {
// clear memory before start
gc_collect_cycles();
$start = microtime(true);
$startMem = $maxMemory = memory_get_usage(true);
for ($i = 0; $i < $iterations; $i++) {
$result = $test();
$maxMemory = max($maxMemory, memory_get_usage(true));
unset($result);
}
$this->results[$name] = [
'time' => microtime(true) - $start,
'memory' => $maxMemory - $startMem,
'n' => $iterations,
];
}
if ($output) {
return $this->getReport();
}
return null;
}
/**
* Get results.
*/
public function getReport(): string
{
if (empty($this->results)) {
return 'No results to display.';
}
helper('number');
// Template
$tpl = '<table>
<thead>
<tr>
<td>Test</td>
<td>Time</td>
<td>Memory</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>';
$rows = '';
foreach ($this->results as $name => $result) {
$memory = number_to_size($result['memory'], 4);
$rows .= "<tr>
<td>{$name}</td>
<td>" . number_format($result['time'], 4) . "</td>
<td>{$memory}</td>
</tr>";
}
$tpl = str_replace('{rows}', $rows, $tpl);
return $tpl . '<br/>';
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use RuntimeException;
/**
* Class Timer
*
* Provides a simple way to measure the amount of time
* that elapses between two points.
*/
class Timer
{
/**
* List of all timers.
*
* @var array
*/
protected $timers = [];
/**
* Starts a timer running.
*
* Multiple calls can be made to this method so that several
* execution points can be measured.
*
* @param string $name The name of this timer.
* @param float $time Allows user to provide time.
*
* @return Timer
*/
public function start(string $name, ?float $time = null)
{
$this->timers[strtolower($name)] = [
'start' => ! empty($time) ? $time : microtime(true),
'end' => null,
];
return $this;
}
/**
* Stops a running timer.
*
* If the timer is not stopped before the timers() method is called,
* it will be automatically stopped at that point.
*
* @param string $name The name of this timer.
*
* @return Timer
*/
public function stop(string $name)
{
$name = strtolower($name);
if (empty($this->timers[$name])) {
throw new RuntimeException('Cannot stop timer: invalid name given.');
}
$this->timers[$name]['end'] = microtime(true);
return $this;
}
/**
* Returns the duration of a recorded timer.
*
* @param string $name The name of the timer.
* @param int $decimals Number of decimal places.
*
* @return float|null Returns null if timer does not exist by that name.
* Returns a float representing the number of
* seconds elapsed while that timer was running.
*/
public function getElapsedTime(string $name, int $decimals = 4)
{
$name = strtolower($name);
if (empty($this->timers[$name])) {
return null;
}
$timer = $this->timers[$name];
if (empty($timer['end'])) {
$timer['end'] = microtime(true);
}
return (float) number_format($timer['end'] - $timer['start'], $decimals, '.', '');
}
/**
* Returns the array of timers, with the duration pre-calculated for you.
*
* @param int $decimals Number of decimal places
*/
public function getTimers(int $decimals = 4): array
{
$timers = $this->timers;
foreach ($timers as &$timer) {
if (empty($timer['end'])) {
$timer['end'] = microtime(true);
}
$timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
}
return $timers;
}
/**
* Checks whether or not a timer with the specified name exists.
*/
public function has(string $name): bool
{
return array_key_exists(strtolower($name), $this->timers);
}
}
+531
View File
@@ -0,0 +1,531 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Debug\Toolbar\Collectors\BaseCollector;
use CodeIgniter\Debug\Toolbar\Collectors\Config;
use CodeIgniter\Debug\Toolbar\Collectors\History;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Config\Toolbar as ToolbarConfig;
use Kint\Kint;
/**
* Displays a toolbar with bits of stats to aid a developer in debugging.
*
* Inspiration: http://prophiler.fabfuel.de
*/
class Toolbar
{
/**
* Toolbar configuration settings.
*
* @var ToolbarConfig
*/
protected $config;
/**
* Collectors to be used and displayed.
*
* @var BaseCollector[]
*/
protected $collectors = [];
public function __construct(ToolbarConfig $config)
{
$this->config = $config;
foreach ($config->collectors as $collector) {
if (! class_exists($collector)) {
log_message(
'critical',
'Toolbar collector does not exist (' . $collector . ').'
. ' Please check $collectors in the app/Config/Toolbar.php file.'
);
continue;
}
$this->collectors[] = new $collector();
}
}
/**
* Returns all the data required by Debug Bar
*
* @param float $startTime App start time
* @param IncomingRequest $request
* @param Response $response
*
* @return string JSON encoded data
*/
public function run(float $startTime, float $totalTime, RequestInterface $request, ResponseInterface $response): string
{
// Data items used within the view.
$data['url'] = current_url();
$data['method'] = strtoupper($request->getMethod());
$data['isAJAX'] = $request->isAJAX();
$data['startTime'] = $startTime;
$data['totalTime'] = $totalTime * 1000;
$data['totalMemory'] = number_format((memory_get_peak_usage()) / 1024 / 1024, 3);
$data['segmentDuration'] = $this->roundTo($data['totalTime'] / 7);
$data['segmentCount'] = (int) ceil($data['totalTime'] / $data['segmentDuration']);
$data['CI_VERSION'] = CodeIgniter::CI_VERSION;
$data['collectors'] = [];
foreach ($this->collectors as $collector) {
$data['collectors'][] = $collector->getAsArray();
}
foreach ($this->collectVarData() as $heading => $items) {
$varData = [];
if (is_array($items)) {
foreach ($items as $key => $value) {
if (is_string($value)) {
$varData[esc($key)] = esc($value);
} else {
$oldKintMode = Kint::$mode_default;
$oldKintCalledFrom = Kint::$display_called_from;
Kint::$mode_default = Kint::MODE_RICH;
Kint::$display_called_from = false;
$kint = @Kint::dump($value);
$kint = substr($kint, strpos($kint, '</style>') + 8);
Kint::$mode_default = $oldKintMode;
Kint::$display_called_from = $oldKintCalledFrom;
$varData[esc($key)] = $kint;
}
}
}
$data['vars']['varData'][esc($heading)] = $varData;
}
if (! empty($_SESSION)) {
foreach ($_SESSION as $key => $value) {
// Replace the binary data with string to avoid json_encode failure.
if (is_string($value) && preg_match('~[^\x20-\x7E\t\r\n]~', $value)) {
$value = 'binary data';
}
$data['vars']['session'][esc($key)] = is_string($value) ? esc($value) : '<pre>' . esc(print_r($value, true)) . '</pre>';
}
}
foreach ($request->getGet() as $name => $value) {
$data['vars']['get'][esc($name)] = is_array($value) ? '<pre>' . esc(print_r($value, true)) . '</pre>' : esc($value);
}
foreach ($request->getPost() as $name => $value) {
$data['vars']['post'][esc($name)] = is_array($value) ? '<pre>' . esc(print_r($value, true)) . '</pre>' : esc($value);
}
foreach ($request->headers() as $header) {
$data['vars']['headers'][esc($header->getName())] = esc($header->getValueLine());
}
foreach ($request->getCookie() as $name => $value) {
$data['vars']['cookies'][esc($name)] = esc($value);
}
$data['vars']['request'] = ($request->isSecure() ? 'HTTPS' : 'HTTP') . '/' . $request->getProtocolVersion();
$data['vars']['response'] = [
'statusCode' => $response->getStatusCode(),
'reason' => esc($response->getReasonPhrase()),
'contentType' => esc($response->getHeaderLine('content-type')),
'headers' => [],
];
foreach ($response->headers() as $header) {
$data['vars']['response']['headers'][esc($header->getName())] = esc($header->getValueLine());
}
$data['config'] = Config::display();
if ($response->CSP !== null) {
$response->CSP->addImageSrc('data:');
}
return json_encode($data);
}
/**
* Called within the view to display the timeline itself.
*/
protected function renderTimeline(array $collectors, float $startTime, int $segmentCount, int $segmentDuration, array &$styles): string
{
$rows = $this->collectTimelineData($collectors);
$styleCount = 0;
// Use recursive render function
return $this->renderTimelineRecursive($rows, $startTime, $segmentCount, $segmentDuration, $styles, $styleCount);
}
/**
* Recursively renders timeline elements and their children.
*/
protected function renderTimelineRecursive(array $rows, float $startTime, int $segmentCount, int $segmentDuration, array &$styles, int &$styleCount, int $level = 0, bool $isChild = false): string
{
$displayTime = $segmentCount * $segmentDuration;
$output = '';
foreach ($rows as $row) {
$hasChildren = isset($row['children']) && ! empty($row['children']);
$isQuery = isset($row['query']) && ! empty($row['query']);
// Open controller timeline by default
$open = $row['name'] === 'Controller';
if ($hasChildren || $isQuery) {
$output .= '<tr class="timeline-parent' . ($open ? ' timeline-parent-open' : '') . '" id="timeline-' . $styleCount . '_parent" onclick="ciDebugBar.toggleChildRows(\'timeline-' . $styleCount . '\');">';
} else {
$output .= '<tr>';
}
$output .= '<td class="' . ($isChild ? 'debug-bar-width30' : '') . '" style="--level: ' . $level . ';">' . ($hasChildren || $isQuery ? '<nav></nav>' : '') . $row['name'] . '</td>';
$output .= '<td class="' . ($isChild ? 'debug-bar-width10' : '') . '">' . $row['component'] . '</td>';
$output .= '<td class="' . ($isChild ? 'debug-bar-width10 ' : '') . 'debug-bar-alignRight">' . number_format($row['duration'] * 1000, 2) . ' ms</td>';
$output .= "<td class='debug-bar-noverflow' colspan='{$segmentCount}'>";
$offset = ((((float) $row['start'] - $startTime) * 1000) / $displayTime) * 100;
$length = (((float) $row['duration'] * 1000) / $displayTime) * 100;
$styles['debug-bar-timeline-' . $styleCount] = "left: {$offset}%; width: {$length}%;";
$output .= "<span class='timer debug-bar-timeline-{$styleCount}' title='" . number_format($length, 2) . "%'></span>";
$output .= '</td>';
$output .= '</tr>';
$styleCount++;
// Add children if any
if ($hasChildren || $isQuery) {
$output .= '<tr class="child-row" id="timeline-' . ($styleCount - 1) . '_children" style="' . ($open ? '' : 'display: none;') . '">';
$output .= '<td colspan="' . ($segmentCount + 3) . '" class="child-container">';
$output .= '<table class="timeline">';
$output .= '<tbody>';
if ($isQuery) {
// Output query string if query
$output .= '<tr>';
$output .= '<td class="query-container" style="--level: ' . ($level + 1) . ';">' . $row['query'] . '</td>';
$output .= '</tr>';
} else {
// Recursively render children
$output .= $this->renderTimelineRecursive($row['children'], $startTime, $segmentCount, $segmentDuration, $styles, $styleCount, $level + 1, true);
}
$output .= '</tbody>';
$output .= '</table>';
$output .= '</td>';
$output .= '</tr>';
}
}
return $output;
}
/**
* Returns a sorted array of timeline data arrays from the collectors.
*
* @param array $collectors
*/
protected function collectTimelineData($collectors): array
{
$data = [];
// Collect it
foreach ($collectors as $collector) {
if (! $collector['hasTimelineData']) {
continue;
}
$data = array_merge($data, $collector['timelineData']);
}
// Sort it
$sortArray = [
array_column($data, 'start'), SORT_NUMERIC, SORT_ASC,
array_column($data, 'duration'), SORT_NUMERIC, SORT_DESC,
&$data,
];
array_multisort(...$sortArray);
// Add end time to each element
array_walk($data, static function (&$row) {
$row['end'] = $row['start'] + $row['duration'];
});
// Group it
$data = $this->structureTimelineData($data);
return $data;
}
/**
* Arranges the already sorted timeline data into a parent => child structure.
*/
protected function structureTimelineData(array $elements): array
{
// We define ourselves as the first element of the array
$element = array_shift($elements);
// If we have children behind us, collect and attach them to us
while (! empty($elements) && $elements[array_key_first($elements)]['end'] <= $element['end']) {
$element['children'][] = array_shift($elements);
}
// Make sure our children know whether they have children, too
if (isset($element['children'])) {
$element['children'] = $this->structureTimelineData($element['children']);
}
// If we have no younger siblings, we can return
if (empty($elements)) {
return [$element];
}
// Make sure our younger siblings know their relatives, too
return array_merge([$element], $this->structureTimelineData($elements));
}
/**
* Returns an array of data from all of the modules
* that should be displayed in the 'Vars' tab.
*/
protected function collectVarData(): array
{
if (! ($this->config->collectVarData ?? true)) {
return [];
}
$data = [];
foreach ($this->collectors as $collector) {
if (! $collector->hasVarData()) {
continue;
}
$data = array_merge($data, $collector->getVarData());
}
return $data;
}
/**
* Rounds a number to the nearest incremental value.
*/
protected function roundTo(float $number, int $increments = 5): float
{
$increments = 1 / $increments;
return ceil($number * $increments) / $increments;
}
/**
* Prepare for debugging..
*
* @param RequestInterface $request
* @param ResponseInterface $response
*/
public function prepare(?RequestInterface $request = null, ?ResponseInterface $response = null)
{
/**
* @var IncomingRequest|null $request
* @var Response|null $response
*/
if (CI_DEBUG && ! is_cli()) {
$app = Services::codeigniter();
$request ??= Services::request();
$response ??= Services::response();
// Disable the toolbar for downloads
if ($response instanceof DownloadResponse) {
return;
}
$toolbar = Services::toolbar(config(self::class));
$stats = $app->getPerformanceStats();
$data = $toolbar->run(
$stats['startTime'],
$stats['totalTime'],
$request,
$response
);
helper('filesystem');
// Updated to microtime() so we can get history
$time = sprintf('%.6f', microtime(true));
if (! is_dir(WRITEPATH . 'debugbar')) {
mkdir(WRITEPATH . 'debugbar', 0777);
}
write_file(WRITEPATH . 'debugbar/debugbar_' . $time . '.json', $data, 'w+');
$format = $response->getHeaderLine('content-type');
// Non-HTML formats should not include the debugbar
// then we send headers saying where to find the debug data
// for this response
if ($request->isAJAX() || strpos($format, 'html') === false) {
$response->setHeader('Debugbar-Time', "{$time}")
->setHeader('Debugbar-Link', site_url("?debugbar_time={$time}"));
return;
}
$oldKintMode = Kint::$mode_default;
Kint::$mode_default = Kint::MODE_RICH;
$kintScript = @Kint::dump('');
Kint::$mode_default = $oldKintMode;
$kintScript = substr($kintScript, 0, strpos($kintScript, '</style>') + 8);
$kintScript = ($kintScript === '0') ? '' : $kintScript;
$script = PHP_EOL
. '<script type="text/javascript" ' . csp_script_nonce() . ' id="debugbar_loader" '
. 'data-time="' . $time . '" '
. 'src="' . site_url() . '?debugbar"></script>'
. '<script type="text/javascript" ' . csp_script_nonce() . ' id="debugbar_dynamic_script"></script>'
. '<style type="text/css" ' . csp_style_nonce() . ' id="debugbar_dynamic_style"></style>'
. $kintScript
. PHP_EOL;
if (strpos($response->getBody(), '<head>') !== false) {
$response->setBody(
preg_replace(
'/<head>/',
'<head>' . $script,
$response->getBody(),
1
)
);
return;
}
$response->appendBody($script);
}
}
/**
* Inject debug toolbar into the response.
*
* @codeCoverageIgnore
*/
public function respond()
{
if (ENVIRONMENT === 'testing') {
return;
}
$request = Services::request();
// If the request contains '?debugbar then we're
// simply returning the loading script
if ($request->getGet('debugbar') !== null) {
header('Content-Type: application/javascript');
ob_start();
include $this->config->viewsPath . 'toolbarloader.js';
$output = ob_get_clean();
$output = str_replace('{url}', rtrim(site_url(), '/'), $output);
echo $output;
exit;
}
// Otherwise, if it includes ?debugbar_time, then
// we should return the entire debugbar.
if ($request->getGet('debugbar_time')) {
helper('security');
// Negotiate the content-type to format the output
$format = $request->negotiate('media', ['text/html', 'application/json', 'application/xml']);
$format = explode('/', $format)[1];
$filename = sanitize_filename('debugbar_' . $request->getGet('debugbar_time'));
$filename = WRITEPATH . 'debugbar/' . $filename . '.json';
if (is_file($filename)) {
// Show the toolbar if it exists
echo $this->format(file_get_contents($filename), $format);
exit;
}
// Filename not found
http_response_code(404);
exit; // Exit here is needed to avoid loading the index page
}
}
/**
* Format output
*/
protected function format(string $data, string $format = 'html'): string
{
$data = json_decode($data, true);
if ($this->config->maxHistory !== 0 && preg_match('/\d+\.\d{6}/s', (string) Services::request()->getGet('debugbar_time'), $debugbarTime)) {
$history = new History();
$history->setFiles(
$debugbarTime[0],
$this->config->maxHistory
);
$data['collectors'][] = $history->getAsArray();
}
$output = '';
switch ($format) {
case 'html':
$data['styles'] = [];
extract($data);
$parser = Services::parser($this->config->viewsPath, null, false);
ob_start();
include $this->config->viewsPath . 'toolbar.tpl.php';
$output = ob_get_clean();
break;
case 'json':
$formatter = new JSONFormatter();
$output = $formatter->format($data);
break;
case 'xml':
$formatter = new XMLFormatter();
$output = $formatter->format($data);
break;
}
return $output;
}
}
@@ -0,0 +1,232 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
/**
* Base Toolbar collector
*/
class BaseCollector
{
/**
* Whether this collector has data that can
* be displayed in the Timeline.
*
* @var bool
*/
protected $hasTimeline = false;
/**
* Whether this collector needs to display
* content in a tab or not.
*
* @var bool
*/
protected $hasTabContent = false;
/**
* Whether this collector needs to display
* a label or not.
*
* @var bool
*/
protected $hasLabel = false;
/**
* Whether this collector has data that
* should be shown in the Vars tab.
*
* @var bool
*/
protected $hasVarData = false;
/**
* The 'title' of this Collector.
* Used to name things in the toolbar HTML.
*
* @var string
*/
protected $title = '';
/**
* Gets the Collector's title.
*/
public function getTitle(bool $safe = false): string
{
if ($safe) {
return str_replace(' ', '-', strtolower($this->title));
}
return $this->title;
}
/**
* Returns any information that should be shown next to the title.
*/
public function getTitleDetails(): string
{
return '';
}
/**
* Does this collector need it's own tab?
*/
public function hasTabContent(): bool
{
return (bool) $this->hasTabContent;
}
/**
* Does this collector have a label?
*/
public function hasLabel(): bool
{
return (bool) $this->hasLabel;
}
/**
* Does this collector have information for the timeline?
*/
public function hasTimelineData(): bool
{
return (bool) $this->hasTimeline;
}
/**
* Grabs the data for the timeline, properly formatted,
* or returns an empty array.
*/
public function timelineData(): array
{
if (! $this->hasTimeline) {
return [];
}
return $this->formatTimelineData();
}
/**
* Does this Collector have data that should be shown in the
* 'Vars' tab?
*/
public function hasVarData(): bool
{
return (bool) $this->hasVarData;
}
/**
* Gets a collection of data that should be shown in the 'Vars' tab.
* The format is an array of sections, each with their own array
* of key/value pairs:
*
* $data = [
* 'section 1' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* 'section 2' => [
* 'foo' => 'bar,
* 'bar' => 'baz'
* ],
* ];
*/
public function getVarData()
{
return null;
}
/**
* Child classes should implement this to return the timeline data
* formatted for correct usage.
*
* Timeline data should be formatted into arrays that look like:
*
* [
* 'name' => 'Database::Query',
* 'component' => 'Database',
* 'start' => 10 // milliseconds
* 'duration' => 15 // milliseconds
* ]
*/
protected function formatTimelineData(): array
{
return [];
}
/**
* Returns the data of this collector to be formatted in the toolbar
*
* @return array|string
*/
public function display()
{
return [];
}
/**
* This makes nicer looking paths for the error output.
*
* @deprecated Use the dedicated `clean_path()` function.
*/
public function cleanPath(string $file): string
{
return clean_path($file);
}
/**
* Gets the "badge" value for the button.
*/
public function getBadgeValue()
{
return null;
}
/**
* Does this collector have any data collected?
*
* If not, then the toolbar button won't get shown.
*/
public function isEmpty(): bool
{
return false;
}
/**
* Returns the HTML to display the icon. Should either
* be SVG, or a base-64 encoded.
*
* Recommended dimensions are 24px x 24px
*/
public function icon(): string
{
return '';
}
/**
* Return settings as an array.
*/
public function getAsArray(): array
{
return [
'title' => $this->getTitle(),
'titleSafe' => $this->getTitle(true),
'titleDetails' => $this->getTitleDetails(),
'display' => $this->display(),
'badgeValue' => $this->getBadgeValue(),
'isEmpty' => $this->isEmpty(),
'hasTabContent' => $this->hasTabContent(),
'hasLabel' => $this->hasLabel(),
'icon' => $this->icon(),
'hasTimelineData' => $this->hasTimelineData(),
'timelineData' => $this->timelineData(),
];
}
}
@@ -0,0 +1,41 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\CodeIgniter;
use Config\App;
use Config\Services;
/**
* Debug toolbar configuration
*/
class Config
{
/**
* Return toolbar config values as an array.
*/
public static function display(): array
{
$config = config(App::class);
return [
'ciVersion' => CodeIgniter::CI_VERSION,
'phpVersion' => PHP_VERSION,
'phpSAPI' => PHP_SAPI,
'environment' => ENVIRONMENT,
'baseURL' => $config->baseURL,
'timezone' => app_timezone(),
'locale' => Services::request()->getLocale(),
'cspEnabled' => $config->CSPEnabled,
];
}
}
@@ -0,0 +1,251 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug\Toolbar\Collectors;
use CodeIgniter\Database\Query;
/**
* Collector for the Database tab of the Debug Toolbar.
*/
class Database extends BaseCollector
{
/**
* Whether this collector has timeline data.
*
* @var bool
*/
protected $hasTimeline = true;
/**
* Whether this collector should display its own tab.
*
* @var bool
*/
protected $hasTabContent = true;
/**
* Whether this collector has data for the Vars tab.
*
* @var bool
*/
protected $hasVarData = false;
/**
* The name used to reference this collector in the toolbar.
*
* @var string
*/
protected $title = 'Database';
/**
* Array of database connections.
*
* @var array
*/
protected $connections;
/**
* The query instances that have been collected
* through the DBQuery Event.
*
* @var array
*/
protected static $queries = [];
/**
* Constructor
*/
public function __construct()
{
$this->getConnections();
}
/**
* The static method used during Events to collect
* data.
*
* @internal param $ array \CodeIgniter\Database\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) {
$queryString = $query->getQuery();
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
if (! is_cli()) {
// when called in the browser, the first two trace arrays
// are from the DB event trigger, which are unneeded
$backtrace = array_slice($backtrace, 2);
}
static::$queries[] = [
'query' => $query,
'string' => $queryString,
'duplicate' => in_array($queryString, array_column(static::$queries, 'string', null), true),
'trace' => $backtrace,
];
}
}
/**
* Returns timeline data formatted for the toolbar.
*
* @return array The formatted data or an empty array.
*/
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['query']->getStartTime(true),
'duration' => $query['query']->getDuration(),
'query' => $query['query']->debugToolbarDisplay(),
];
}
return $data;
}
/**
* Returns the data of this collector to be formatted in the toolbar
*/
public function display(): array
{
$data['queries'] = array_map(static function (array $query) {
$isDuplicate = $query['duplicate'] === true;
$firstNonSystemLine = '';
foreach ($query['trace'] as $index => &$line) {
// simplify file and line
if (isset($line['file'])) {
$line['file'] = clean_path($line['file']) . ':' . $line['line'];
unset($line['line']);
} else {
$line['file'] = '[internal function]';
}
// find the first trace line that does not originate from `system/`
if ($firstNonSystemLine === '' && strpos($line['file'], 'SYSTEMPATH') === false) {
$firstNonSystemLine = $line['file'];
}
// simplify function call
if (isset($line['class'])) {
$line['function'] = $line['class'] . $line['type'] . $line['function'];
unset($line['class'], $line['type']);
}
if (strrpos($line['function'], '{closure}') === false) {
$line['function'] .= '()';
}
$line['function'] = str_repeat(chr(0xC2) . chr(0xA0), 8) . $line['function'];
// add index numbering padded with nonbreaking space
$indexPadded = str_pad(sprintf('%d', $index + 1), 3, ' ', STR_PAD_LEFT);
$indexPadded = preg_replace('/\s/', chr(0xC2) . chr(0xA0), $indexPadded);
$line['index'] = $indexPadded . str_repeat(chr(0xC2) . chr(0xA0), 4);
}
return [
'hover' => $isDuplicate ? 'This query was called more than once.' : '',
'class' => $isDuplicate ? 'duplicate' : '',
'duration' => ((float) $query['query']->getDuration(5) * 1000) . ' ms',
'sql' => $query['query']->debugToolbarDisplay(),
'trace' => $query['trace'],
'trace-file' => $firstNonSystemLine,
'qid' => md5($query['query'] . microtime()),
];
}, static::$queries);
return $data;
}
/**
* Gets the "badge" value for the button.
*/
public function getBadgeValue(): int
{
return count(static::$queries);
}
/**
* Information to be displayed next to the title.
*
* @return string The number of queries (in parentheses) or an empty string.
*/
public function getTitleDetails(): string
{
$this->getConnections();
$queryCount = count(static::$queries);
$uniqueCount = count(array_filter(static::$queries, static fn ($query) => $query['duplicate'] === false));
$connectionCount = count($this->connections);
return sprintf(
'(%d total Quer%s, %d %s unique across %d Connection%s)',
$queryCount,
$queryCount > 1 ? 'ies' : 'y',
$uniqueCount,
$uniqueCount > 1 ? 'of them' : '',
$connectionCount,
$connectionCount > 1 ? 's' : ''
);
}
/**
* Does this collector have any data collected?
*/
public function isEmpty(): bool
{
return empty(static::$queries);
}
/**
* Display the icon.
*
* Icon from https://icons8.com - 1em package
*/
public function icon(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADMSURBVEhLY6A3YExLSwsA4nIycQDIDIhRWEBqamo/UNF/SjDQjF6ocZgAKPkRiFeEhoYyQ4WIBiA9QAuWAPEHqBAmgLqgHcolGQD1V4DMgHIxwbCxYD+QBqcKINseKo6eWrBioPrtQBq/BcgY5ht0cUIYbBg2AJKkRxCNWkDQgtFUNJwtABr+F6igE8olGQD114HMgHIxAVDyAhA/AlpSA8RYUwoeXAPVex5qHCbIyMgwBCkAuQJIY00huDBUz/mUlBQDqHGjgBjAwAAACexpph6oHSQAAAAASUVORK5CYII=';
}
/**
* Gets the connections from the database config
*/
private function getConnections()
{
$this->connections = \Config\Database::getConnections();
}
}

Some files were not shown because too many files have changed in this diff Show More