diff --git a/application/Config/App.php b/application/Config/App.php index d25b84c31b1c..ef0ebee97507 100644 --- a/application/Config/App.php +++ b/application/Config/App.php @@ -204,10 +204,10 @@ class App extends BaseConfig | 'cookie_httponly') will also affect sessions. | */ - public $cookiePrefix = ''; - public $cookieDomain = ''; - public $cookiePath = '/'; - public $cookieSecure = false; + public $cookiePrefix = ''; + public $cookieDomain = ''; + public $cookiePath = '/'; + public $cookieSecure = false; public $cookieHTTPOnly = false; /* @@ -242,11 +242,11 @@ class App extends BaseConfig | CSRFRegenerate = Regenerate token on every submission | CSRFRedirect = Redirect to previous page with error on failure */ - public $CSRFTokenName = 'csrf_test_name'; - public $CSRFCookieName = 'csrf_cookie_name'; - public $CSRFExpire = 7200; - public $CSRFRegenerate = true; - public $CSRFRedirect = true; + public $CSRFTokenName = 'csrf_test_name'; + public $CSRFCookieName = 'csrf_cookie_name'; + public $CSRFExpire = 7200; + public $CSRFRegenerate = true; + public $CSRFRedirect = true; /* |-------------------------------------------------------------------------- @@ -281,7 +281,7 @@ class App extends BaseConfig 'CodeIgniter\Debug\Toolbar\Collectors\Database', 'CodeIgniter\Debug\Toolbar\Collectors\Logs', 'CodeIgniter\Debug\Toolbar\Collectors\Views', -// 'CodeIgniter\Debug\Toolbar\Collectors\Cache', + // 'CodeIgniter\Debug\Toolbar\Collectors\Cache', 'CodeIgniter\Debug\Toolbar\Collectors\Files', 'CodeIgniter\Debug\Toolbar\Collectors\Routes', 'CodeIgniter\Debug\Toolbar\Collectors\Events', @@ -303,5 +303,4 @@ class App extends BaseConfig //-------------------------------------------------------------------- - } diff --git a/application/Config/Cache.php b/application/Config/Cache.php index 781432aae7ab..15038399a43e 100644 --- a/application/Config/Cache.php +++ b/application/Config/Cache.php @@ -36,7 +36,7 @@ class Cache extends BaseConfig | system. | */ - public $storePath = WRITEPATH.'cache/'; + public $storePath = WRITEPATH . 'cache/'; /* |-------------------------------------------------------------------------- diff --git a/application/Config/Constants.php b/application/Config/Constants.php index a5c63d4b9901..3f7cef1b8c6f 100644 --- a/application/Config/Constants.php +++ b/application/Config/Constants.php @@ -21,7 +21,7 @@ | The path that Composer's autoload file is expected to live. By default, | the vendor folder is in the Root directory, but you can customize that here. */ -define('COMPOSER_PATH', ROOTPATH.'vendor/autoload.php'); +define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php'); /* |-------------------------------------------------------------------------- @@ -31,14 +31,14 @@ | Provide simple ways to work with the myriad of PHP functions that | require information to be in seconds. */ -defined('SECOND') || define('SECOND', 1); -defined('MINUTE') || define('MINUTE', 60); -defined('HOUR') || define('HOUR', 3600); -defined('DAY') || define('DAY', 86400); -defined('WEEK') || define('WEEK', 604800); -defined('MONTH') || define('MONTH', 2592000); -defined('YEAR') || define('YEAR', 31536000); -defined('DECADE') || define('DECADE', 315360000); +defined('SECOND') || define('SECOND', 1); +defined('MINUTE') || define('MINUTE', 60); +defined('HOUR') || define('HOUR', 3600); +defined('DAY') || define('DAY', 86400); +defined('WEEK') || define('WEEK', 604800); +defined('MONTH') || define('MONTH', 2592000); +defined('YEAR') || define('YEAR', 31536000); +defined('DECADE') || define('DECADE', 315360000); /* |-------------------------------------------------------------------------- @@ -65,13 +65,13 @@ | http://tldp.org/LDP/abs/html/exitcodes.html | */ -defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors -defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error -defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error -defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found -defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class +defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors +defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error +defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error +defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found +defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member -defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input -defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error -defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code -defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code +defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input +defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error +defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code +defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code diff --git a/application/Config/ContentSecurityPolicy.php b/application/Config/ContentSecurityPolicy.php index 2cd502925820..d0147f081995 100644 --- a/application/Config/ContentSecurityPolicy.php +++ b/application/Config/ContentSecurityPolicy.php @@ -38,7 +38,7 @@ class ContentSecurityPolicy extends BaseConfig public $mediaSrc = null; public $objectSrc = null; - + public $manifestSrc = null; public $pluginTypes = null; diff --git a/application/Config/Database.php b/application/Config/Database.php index f6c867c878c8..f3fe66c7048c 100644 --- a/application/Config/Database.php +++ b/application/Config/Database.php @@ -5,14 +5,16 @@ * * @package Config */ + class Database extends \CodeIgniter\Database\Config { /** * The directory that holds the Migrations * and Seeds directories. + * * @var string */ - public $filesPath = APPPATH.'Database/'; + public $filesPath = APPPATH . 'Database/'; /** * Lets you choose which connection group to @@ -28,25 +30,25 @@ class Database extends \CodeIgniter\Database\Config * @var array */ public $default = [ - 'DSN' => '', - 'hostname' => 'localhost', - 'username' => '', - 'password' => '', - 'database' => '', - 'DBDriver' => 'MySQLi', - 'DBPrefix' => '', - 'pConnect' => false, - 'DBDebug' => (ENVIRONMENT !== 'production'), - 'cacheOn' => false, - 'cacheDir' => '', - 'charset' => 'utf8', - 'DBCollat' => 'utf8_general_ci', - 'swapPre' => '', - 'encrypt' => false, - 'compress' => false, - 'strictOn' => false, - 'failover' => [], - 'port' => 3306 + 'DSN' => '', + 'hostname' => 'localhost', + 'username' => '', + 'password' => '', + 'database' => '', + 'DBDriver' => 'MySQLi', + 'DBPrefix' => '', + 'pConnect' => false, + 'DBDebug' => (ENVIRONMENT !== 'production'), + 'cacheOn' => false, + 'cacheDir' => '', + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + 'swapPre' => '', + 'encrypt' => false, + 'compress' => false, + 'strictOn' => false, + 'failover' => [], + 'port' => 3306, ]; /** @@ -56,37 +58,37 @@ class Database extends \CodeIgniter\Database\Config * @var array */ public $tests = [ - 'DSN' => '', - 'hostname' => '127.0.0.1', - 'username' => '', - 'password' => '', - 'database' => '', - 'DBDriver' => '', - 'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE. - 'pConnect' => false, - 'DBDebug' => (ENVIRONMENT !== 'production'), - 'cacheOn' => false, - 'cacheDir' => '', - 'charset' => 'utf8', - 'DBCollat' => 'utf8_general_ci', - 'swapPre' => '', - 'encrypt' => false, - 'compress' => false, - 'strictOn' => false, - 'failover' => [], - 'port' => 3306 + 'DSN' => '', + 'hostname' => '127.0.0.1', + 'username' => '', + 'password' => '', + 'database' => '', + 'DBDriver' => '', + 'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE. + 'pConnect' => false, + 'DBDebug' => (ENVIRONMENT !== 'production'), + 'cacheOn' => false, + 'cacheDir' => '', + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + 'swapPre' => '', + 'encrypt' => false, + 'compress' => false, + 'strictOn' => false, + 'failover' => [], + 'port' => 3306, ]; //-------------------------------------------------------------------- public function __construct() { - parent::__construct(); + parent::__construct(); // Ensure that we always set the database group to 'tests' if // we are currently running an automated test suite, so that // we don't overwrite live data on accident. - if (ENVIRONMENT == 'testing') + if (ENVIRONMENT === 'testing') { $this->defaultGroup = 'tests'; @@ -94,11 +96,11 @@ public function __construct() // so that we can test against multiple databases. if ($group = getenv('DB')) { - if (is_file(TESTPATH.'travis/Database.php')) + if (is_file(TESTPATH . 'travis/Database.php')) { - require TESTPATH.'travis/Database.php'; + require TESTPATH . 'travis/Database.php'; - if ( ! empty($dbconfig) && array_key_exists($group, $dbconfig)) + if (! empty($dbconfig) && array_key_exists($group, $dbconfig)) { $this->tests = $dbconfig[$group]; } @@ -109,5 +111,4 @@ public function __construct() //-------------------------------------------------------------------- - } diff --git a/application/Config/DocTypes.php b/application/Config/DocTypes.php index 38ceaedfc905..67d5dd208e3e 100755 --- a/application/Config/DocTypes.php +++ b/application/Config/DocTypes.php @@ -8,26 +8,26 @@ class DocTypes { - public $list = + public $list = [ - 'xhtml11' => '', - 'xhtml1-strict' => '', - 'xhtml1-trans' => '', - 'xhtml1-frame' => '', - 'xhtml-basic11' => '', - 'html5' => '', - 'html4-strict' => '', - 'html4-trans' => '', - 'html4-frame' => '', - 'mathml1' => '', - 'mathml2' => '', - 'svg10' => '', - 'svg11' => '', - 'svg11-basic' => '', - 'svg11-tiny' => '', + 'xhtml11' => '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'xhtml-basic11' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => '', + 'mathml1' => '', + 'mathml2' => '', + 'svg10' => '', + 'svg11' => '', + 'svg11-basic' => '', + 'svg11-tiny' => '', 'xhtml-math-svg-xh' => '', 'xhtml-math-svg-sh' => '', - 'xhtml-rdfa-1' => '', - 'xhtml-rdfa-2' => '' + 'xhtml-rdfa-1' => '', + 'xhtml-rdfa-2' => '', ]; -} \ No newline at end of file +} diff --git a/application/Config/Email.php b/application/Config/Email.php index c5dfd13ae70e..45661240a11e 100644 --- a/application/Config/Email.php +++ b/application/Config/Email.php @@ -14,127 +14,148 @@ class Email /** * The "user agent" + * * @var string */ public $userAgent = 'CodeIgniter'; /** * The mail sending protocol: mail, sendmail, smtp + * * @var string */ public $protocol = 'mail'; /** * The server path to Sendmail. + * * @var string */ public $mailPath = '/usr/sbin/sendmail'; /** * SMTP Server Address + * * @var string */ public $SMTPHost; /** * SMTP Username + * * @var string */ public $SMTPUser; /** * SMTP Password + * * @var string */ public $SMTPPass; /** * SMTP Port - * @var int + * + * @var integer */ public $SMTPPort = 25; /** * SMTP Timeout (in seconds) - * @var int + * + * @var integer */ public $SMTPTimeout = 5; /** * Enable persistent SMTP connections - * @var bool + * + * @var boolean */ public $SMTPKeepAlive = false; /** * SMTP Encryption. Either tls or ssl + * * @var string */ public $SMTPCrypto = 'tls'; /** * Enable word-wrap - * @var bool + * + * @var boolean */ public $wordWrap = true; /** * Character count to wrap at - * @var int + * + * @var integer */ public $wrapChars = 76; /** * Type of mail, either 'text' or 'html' + * * @var string */ public $mailType = 'text'; /** * Character set (utf-8, iso-8859-1, etc.) + * * @var string */ public $charset = 'UTF-8'; /** * Whether to validate the email address - * @var bool + * + * @var boolean */ public $validate = false; /** * Email Priority. 1 = highest. 5 = lowest. 3 = normal - * @var int + * + * @var integer */ public $priority = 3; /** * Newline character. (Use ā€œ\r\nā€ to comply with RFC 822) + * * @var string */ public $CRLF = "\r\n"; /** * Newline character. (Use ā€œ\r\nā€ to comply with RFC 822) + * * @var string */ public $newline = "\r\n"; /** * Enable BCC Batch Mode. - * @var bool + * + * @var boolean */ public $BCCBatchMode = false; /** * Number of emails in each BCC batch - * @var int + * + * @var integer */ public $BCCBatchSize = 200; /** * Enable notify message from server - * @var bool + * + * @var boolean */ public $DSN = false; } diff --git a/application/Config/Events.php b/application/Config/Events.php index 47781585a450..7ea37d329934 100644 --- a/application/Config/Events.php +++ b/application/Config/Events.php @@ -19,15 +19,13 @@ * Events::on('create', [$myInstance, 'myMethod']); */ - - /* * -------------------------------------------------------------------- * Debug Toolbar Listeners. * -------------------------------------------------------------------- * If you delete, they will no longer be collected. */ -if (ENVIRONMENT != 'production') +if (ENVIRONMENT !== 'production') { Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect'); diff --git a/application/Config/Exceptions.php b/application/Config/Exceptions.php index 3b3fa2779169..c0245b2a606b 100644 --- a/application/Config/Exceptions.php +++ b/application/Config/Exceptions.php @@ -5,6 +5,7 @@ * * @package Config */ + class Exceptions { /* @@ -36,5 +37,5 @@ class Exceptions | | Default: APPPATH.'Views/errors' */ - public $errorViewPath = APPPATH.'Views/errors'; + public $errorViewPath = APPPATH . 'Views/errors'; } diff --git a/application/Config/Filters.php b/application/Config/Filters.php index a3ed0861b9d7..a6c8a2143aac 100644 --- a/application/Config/Filters.php +++ b/application/Config/Filters.php @@ -7,9 +7,9 @@ class Filters extends BaseConfig // Makes reading things below nicer, // and simpler to change out script that's used. public $aliases = [ - 'csrf' => \App\Filters\CSRF::class, - 'toolbar' => \App\Filters\DebugToolbar::class, - 'honeypot' => \App\Filters\Honeypot::class + 'csrf' => \App\Filters\CSRF::class, + 'toolbar' => \App\Filters\DebugToolbar::class, + 'honeypot' => \App\Filters\Honeypot::class, ]; // Always applied before every request @@ -21,7 +21,7 @@ class Filters extends BaseConfig 'after' => [ 'toolbar', //'honeypot' - ] + ], ]; // Works on all of a particular HTTP method diff --git a/application/Config/Format.php b/application/Config/Format.php index 57cb81ed82c0..5f64b702f424 100644 --- a/application/Config/Format.php +++ b/application/Config/Format.php @@ -20,8 +20,8 @@ class Format extends BaseConfig */ public $supportedResponseFormats = [ 'application/json', - 'application/xml', // machine-readable XML - 'text/xml' // human-readable XML + 'application/xml', // machine-readable XML + 'text/xml', // human-readable XML ]; /* @@ -37,7 +37,7 @@ class Format extends BaseConfig public $formatters = [ 'application/json' => \CodeIgniter\Format\JSONFormatter::class, 'application/xml' => \CodeIgniter\Format\XMLFormatter::class, - 'text/xml' => \CodeIgniter\Format\XMLFormatter::class, + 'text/xml' => \CodeIgniter\Format\XMLFormatter::class, ]; //-------------------------------------------------------------------- @@ -53,14 +53,14 @@ public function getFormatter(string $mime) { if (! array_key_exists($mime, $this->formatters)) { - throw new \InvalidArgumentException('No Formatter defined for mime type: '. $mime); + throw new \InvalidArgumentException('No Formatter defined for mime type: ' . $mime); } $class = $this->formatters[$mime]; if (! class_exists($class)) { - throw new \BadMethodCallException($class.' is not a valid Formatter.'); + throw new \BadMethodCallException($class . ' is not a valid Formatter.'); } return new $class(); diff --git a/application/Config/Honeypot.php b/application/Config/Honeypot.php index d35b0c7ee861..f4444a5d6c08 100644 --- a/application/Config/Honeypot.php +++ b/application/Config/Honeypot.php @@ -7,25 +7,28 @@ class Honeypot extends BaseConfig /** * Makes Honeypot visible or not to human - * + * * @var boolean */ public $hidden = true; - /** + /** * Honeypot Label Content - * @var String + * + * @var string */ - public $label = 'Fill This Field'; + public $label = 'Fill This Field'; - /** - * Honeypot Field Name - * @var String + /** + * Honeypot Field Name + * + * @var string */ - public $name = 'honeypot'; + public $name = 'honeypot'; - /** - * Honeypot HTML Template - * @var String + /** + * Honeypot HTML Template + * + * @var string */ - public $template = ''; -} \ No newline at end of file + public $template = ''; +} diff --git a/application/Config/Images.php b/application/Config/Images.php index c819ba29c205..730ddee759b3 100644 --- a/application/Config/Images.php +++ b/application/Config/Images.php @@ -25,7 +25,7 @@ class Images extends BaseConfig * @var array */ public $handlers = [ - 'gd' => \CodeIgniter\Images\Handlers\GDHandler::class, - 'imagick' => \CodeIgniter\Images\Handlers\ImageMagickHandler::class, + 'gd' => \CodeIgniter\Images\Handlers\GDHandler::class, + 'imagick' => \CodeIgniter\Images\Handlers\ImageMagickHandler::class, ]; } diff --git a/application/Config/Logger.php b/application/Config/Logger.php index 8b64f88b586b..d32e195fe3c6 100644 --- a/application/Config/Logger.php +++ b/application/Config/Logger.php @@ -44,7 +44,6 @@ class Logger extends BaseConfig */ public $path = ''; - /* |-------------------------------------------------------------------------- | Date Format for Logs @@ -91,43 +90,51 @@ class Logger extends BaseConfig /* * The log levels that this handler will handle. */ - 'handles' => ['critical', 'alert', 'emergency', 'debug', - 'error', 'info', 'notice', 'warning'], + 'handles' => [ + 'critical', + 'alert', + 'emergency', + 'debug', + 'error', + 'info', + 'notice', + 'warning', + ], /* * Leave this BLANK unless you would like to set something other than the default * writeable/logs/ directory. Use a full getServer path with trailing slash. */ - 'path' => WRITEPATH.'logs/', + 'path' => WRITEPATH . 'logs/', - /* - * The default filename extension for log files. The default 'php' allows for - * protecting the log files via basic scripting, when they are to be stored - * under a publicly accessible directory. - * - * Note: Leaving it blank will default to 'php'. - */ - 'fileExtension' => 'php', + /* + * The default filename extension for log files. The default 'php' allows for + * protecting the log files via basic scripting, when they are to be stored + * under a publicly accessible directory. + * + * Note: Leaving it blank will default to 'php'. + */ + 'fileExtension' => 'php', - /* - * The file system permissions to be applied on newly created log files. - * - * IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal - * integer notation (i.e. 0700, 0644, etc.) - */ - 'filePermissions' => 0644 + /* + * The file system permissions to be applied on newly created log files. + * + * IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal + * integer notation (i.e. 0700, 0644, etc.) + */ + 'filePermissions' => 0644, ], /** * The ChromeLoggerHandler requires the use of the Chrome web browser * and the ChromeLogger extension. Uncomment this block to use it. */ -// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [ -// /* -// * The log levels that this handler will handle. -// */ -// 'handles' => ['critical', 'alert', 'emergency', 'debug', -// 'error', 'info', 'notice', 'warning'], -// ] + // 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [ + // /* + // * The log levels that this handler will handle. + // */ + // 'handles' => ['critical', 'alert', 'emergency', 'debug', + // 'error', 'info', 'notice', 'warning'], + // ] ]; } diff --git a/application/Config/Mimes.php b/application/Config/Mimes.php index bcb232181d92..d828e7dba413 100644 --- a/application/Config/Mimes.php +++ b/application/Config/Mimes.php @@ -51,15 +51,29 @@ class Mimes 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', - 'exe' => ['application/octet-stream', 'application/x-msdownload'], + 'exe' => [ + 'application/octet-stream', + 'application/x-msdownload', + ], 'class' => 'application/octet-stream', - 'psd' => ['application/x-photoshop', 'image/vnd.adobe.photoshop'], + 'psd' => [ + 'application/x-photoshop', + 'image/vnd.adobe.photoshop', + ], 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', - 'pdf' => ['application/pdf', 'application/force-download', 'application/x-download', 'binary/octet-stream'], - 'ai' => ['application/pdf', 'application/postscript'], + 'pdf' => [ + 'application/pdf', + 'application/force-download', + 'application/x-download', + 'binary/octet-stream', + ], + 'ai' => [ + 'application/pdf', + 'application/postscript', + ], 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', @@ -111,11 +125,17 @@ class Mimes 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', - 'js' => ['application/x-javascript', 'text/plain'], + 'js' => [ + 'application/x-javascript', + 'text/plain', + ], 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', - 'tgz' => ['application/x-tar', 'application/x-gzip-compressed'], + 'tgz' => [ + 'application/x-tar', + 'application/x-gzip-compressed', + ], 'z' => 'application/x-compress', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', @@ -126,21 +146,40 @@ class Mimes 'application/s-compressed', 'multipart/x-zip', ], - 'rar' => ['application/x-rar', 'application/rar', 'application/x-rar-compressed'], + 'rar' => [ + 'application/x-rar', + 'application/rar', + 'application/x-rar-compressed', + ], 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', - 'mp3' => ['audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'], - 'aif' => ['audio/x-aiff', 'audio/aiff'], - 'aiff' => ['audio/x-aiff', 'audio/aiff'], + 'mp3' => [ + 'audio/mpeg', + 'audio/mpg', + 'audio/mpeg3', + 'audio/mp3', + ], + 'aif' => [ + 'audio/x-aiff', + 'audio/aiff', + ], + 'aiff' => [ + 'audio/x-aiff', + 'audio/aiff', + ], 'aifc' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', - 'wav' => ['audio/x-wav', 'audio/wave', 'audio/wav'], + 'wav' => [ + 'audio/x-wav', + 'audio/wave', + 'audio/wav', + ], 'bmp' => [ 'image/bmp', 'image/x-bmp', @@ -155,46 +194,132 @@ class Mimes 'application/x-win-bitmap', ], 'gif' => 'image/gif', - 'jpg' => ['image/jpeg', 'image/pjpeg'], - 'jpeg' => ['image/jpeg', 'image/pjpeg'], - 'jpe' => ['image/jpeg', 'image/pjpeg'], - 'jp2' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'j2k' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'jpf' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'jpg2' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'jpx' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'jpm' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'mj2' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'mjp2' => ['image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'], - 'png' => ['image/png', 'image/x-png'], + 'jpg' => [ + 'image/jpeg', + 'image/pjpeg', + ], + 'jpeg' => [ + 'image/jpeg', + 'image/pjpeg', + ], + 'jpe' => [ + 'image/jpeg', + 'image/pjpeg', + ], + 'jp2' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'j2k' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'jpf' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'jpg2' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'jpx' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'jpm' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'mj2' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'mjp2' => [ + 'image/jp2', + 'video/mj2', + 'image/jpx', + 'image/jpm', + ], + 'png' => [ + 'image/png', + 'image/x-png', + ], 'tif' => 'image/tiff', 'tiff' => 'image/tiff', - 'css' => ['text/css', 'text/plain'], - 'html' => ['text/html', 'text/plain'], - 'htm' => ['text/html', 'text/plain'], - 'shtml' => ['text/html', 'text/plain'], + 'css' => [ + 'text/css', + 'text/plain', + ], + 'html' => [ + 'text/html', + 'text/plain', + ], + 'htm' => [ + 'text/html', + 'text/plain', + ], + 'shtml' => [ + 'text/html', + 'text/plain', + ], 'txt' => 'text/plain', 'text' => 'text/plain', - 'log' => ['text/plain', 'text/x-log'], + 'log' => [ + 'text/plain', + 'text/x-log', + ], 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', - 'xml' => ['application/xml', 'text/xml', 'text/plain'], - 'xsl' => ['application/xml', 'text/xsl', 'text/xml'], + 'xml' => [ + 'application/xml', + 'text/xml', + 'text/plain', + ], + 'xsl' => [ + 'application/xml', + 'text/xsl', + 'text/xml', + ], 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', - 'avi' => ['video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'], + 'avi' => [ + 'video/x-msvideo', + 'video/msvideo', + 'video/avi', + 'application/x-troff-msvideo', + ], 'movie' => 'video/x-sgi-movie', - 'doc' => ['application/msword', 'application/vnd.ms-office'], + 'doc' => [ + 'application/msword', + 'application/vnd.ms-office', + ], 'docx' => [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip', ], - 'dot' => ['application/msword', 'application/vnd.ms-office'], + 'dot' => [ + 'application/msword', + 'application/vnd.ms-office', + ], 'dotx' => [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', @@ -207,20 +332,46 @@ class Mimes 'application/msword', 'application/x-zip', ], - 'word' => ['application/msword', 'application/octet-stream'], + 'word' => [ + 'application/msword', + 'application/octet-stream', + ], 'xl' => 'application/excel', 'eml' => 'message/rfc822', - 'json' => ['application/json', 'text/json'], - 'pem' => ['application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'], - 'p10' => ['application/x-pkcs10', 'application/pkcs10'], + 'json' => [ + 'application/json', + 'text/json', + ], + 'pem' => [ + 'application/x-x509-user-cert', + 'application/x-pem-file', + 'application/octet-stream', + ], + 'p10' => [ + 'application/x-pkcs10', + 'application/pkcs10', + ], 'p12' => 'application/x-pkcs12', 'p7a' => 'application/x-pkcs7-signature', - 'p7c' => ['application/pkcs7-mime', 'application/x-pkcs7-mime'], - 'p7m' => ['application/pkcs7-mime', 'application/x-pkcs7-mime'], + 'p7c' => [ + 'application/pkcs7-mime', + 'application/x-pkcs7-mime', + ], + 'p7m' => [ + 'application/pkcs7-mime', + 'application/x-pkcs7-mime', + ], 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', - 'crt' => ['application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'], - 'crl' => ['application/pkix-crl', 'application/pkcs-crl'], + 'crt' => [ + 'application/x-x509-ca-cert', + 'application/x-x509-user-cert', + 'application/pkix-cert', + ], + 'crl' => [ + 'application/pkix-crl', + 'application/pkcs-crl', + ], 'der' => 'application/x-x509-ca-cert', 'kdb' => 'application/octet-stream', 'pgp' => 'application/pgp', @@ -228,12 +379,21 @@ class Mimes 'sst' => 'application/octet-stream', 'csr' => 'application/octet-stream', 'rsa' => 'application/x-pkcs7', - 'cer' => ['application/pkix-cert', 'application/x-x509-ca-cert'], + 'cer' => [ + 'application/pkix-cert', + 'application/x-x509-ca-cert', + ], '3g2' => 'video/3gpp2', - '3gp' => ['video/3gp', 'video/3gpp'], + '3gp' => [ + 'video/3gp', + 'video/3gpp', + ], 'mp4' => 'video/mp4', 'm4a' => 'audio/x-m4a', - 'f4v' => ['video/mp4', 'video/x-f4v'], + 'f4v' => [ + 'video/mp4', + 'video/x-f4v', + ], 'flv' => 'video/x-flv', 'webm' => 'video/webm', 'aac' => 'audio/x-acc', @@ -241,17 +401,37 @@ class Mimes 'm3u' => 'text/plain', 'xspf' => 'application/xspf+xml', 'vlc' => 'application/videolan', - 'wmv' => ['video/x-ms-wmv', 'video/x-ms-asf'], + 'wmv' => [ + 'video/x-ms-wmv', + 'video/x-ms-asf', + ], 'au' => 'audio/x-au', 'ac3' => 'audio/ac3', 'flac' => 'audio/x-flac', - 'ogg' => ['audio/ogg', 'video/ogg', 'application/ogg'], - 'kmz' => ['application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'], - 'kml' => ['application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'], + 'ogg' => [ + 'audio/ogg', + 'video/ogg', + 'application/ogg', + ], + 'kmz' => [ + 'application/vnd.google-earth.kmz', + 'application/zip', + 'application/x-zip', + ], + 'kml' => [ + 'application/vnd.google-earth.kml+xml', + 'application/xml', + 'text/xml', + ], 'ics' => 'text/calendar', 'ical' => 'text/calendar', 'zsh' => 'text/x-scriptzsh', - '7zip' => ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'], + '7zip' => [ + 'application/x-compressed', + 'application/x-zip-compressed', + 'application/zip', + 'multipart/x-zip', + ], 'cdr' => [ 'application/cdr', 'application/coreldraw', @@ -261,18 +441,35 @@ class Mimes 'image/x-cdr', 'zz-application/zz-winassoc-cdr', ], - 'wma' => ['audio/x-ms-wma', 'video/x-ms-asf'], + 'wma' => [ + 'audio/x-ms-wma', + 'video/x-ms-asf', + ], 'jar' => [ 'application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed', ], - 'svg' => ['image/svg+xml', 'application/xml', 'text/xml'], + 'svg' => [ + 'image/svg+xml', + 'application/xml', + 'text/xml', + ], 'vcf' => 'text/x-vcard', - 'srt' => ['text/srt', 'text/plain'], - 'vtt' => ['text/vtt', 'text/plain'], - 'ico' => ['image/x-icon', 'image/x-ico', 'image/vnd.microsoft.icon'], + 'srt' => [ + 'text/srt', + 'text/plain', + ], + 'vtt' => [ + 'text/vtt', + 'text/plain', + ], + 'ico' => [ + 'image/x-icon', + 'image/x-ico', + 'image/vnd.microsoft.icon', + ], ]; //-------------------------------------------------------------------- @@ -308,19 +505,18 @@ public static function guessTypeFromExtension(string $extension) */ public static function guessExtensionFromType(string $type, ?string $proposed_extension = null) { - $type = trim(strtolower($type), '. '); $proposed_extension = trim(strtolower($proposed_extension)); - if(!is_null($proposed_extension) && array_key_exists($proposed_extension, self::$mimes) && in_array($type, self::$mimes[$proposed_extension])) + if (! is_null($proposed_extension) && array_key_exists($proposed_extension, self::$mimes) && in_array($type, self::$mimes[$proposed_extension])) { return $proposed_extension; } foreach (self::$mimes as $ext => $types) { - if (is_string($types) && $types == $type) + if (is_string($types) && $types === $type) { return $ext; } @@ -333,8 +529,6 @@ public static function guessExtensionFromType(string $type, ?string $proposed_ex return null; } - //-------------------------------------------------------------------- - } diff --git a/application/Config/Modules.php b/application/Config/Modules.php index 62069b34f91a..2dcd22be3c7e 100644 --- a/application/Config/Modules.php +++ b/application/Config/Modules.php @@ -41,11 +41,14 @@ class Modules * * @param string $alias * - * @return bool + * @return boolean */ public function shouldDiscover(string $alias) { - if (! $this->enabled) return false; + if (! $this->enabled) + { + return false; + } $alias = strtolower($alias); diff --git a/application/Config/Pager.php b/application/Config/Pager.php index bfb8ec554e4b..70862c355564 100644 --- a/application/Config/Pager.php +++ b/application/Config/Pager.php @@ -19,7 +19,7 @@ class Pager extends BaseConfig */ public $templates = [ 'default_full' => 'CodeIgniter\Pager\Views\default_full', - 'default_simple' => 'CodeIgniter\Pager\Views\default_simple' + 'default_simple' => 'CodeIgniter\Pager\Views\default_simple', ]; /* diff --git a/application/Config/Paths.php b/application/Config/Paths.php index 09bb87c1b9d6..a9b78b197459 100644 --- a/application/Config/Paths.php +++ b/application/Config/Paths.php @@ -8,6 +8,7 @@ * * All paths are relative to the project's root folder. */ + class Paths { /* diff --git a/application/Config/Routes.php b/application/Config/Routes.php index b016ab2a4df7..0925c3c344cc 100644 --- a/application/Config/Routes.php +++ b/application/Config/Routes.php @@ -15,7 +15,6 @@ * In some instances, however, you may want to remap this relationship * so that a different class/function is called than the one * corresponding to the URL. - * */ // Create a new instance of our RouteCollection class. @@ -23,9 +22,9 @@ // Load the system's routing file first, so that the app and ENVIRONMENT // can override as needed. -if (file_exists(BASEPATH.'Config/Routes.php')) +if (file_exists(BASEPATH . 'Config/Routes.php')) { - require BASEPATH.'Config/Routes.php'; + require BASEPATH . 'Config/Routes.php'; } /** @@ -88,7 +87,7 @@ * You will have access to the $routes object within that file without * needing to reload it. */ -if (file_exists(APPPATH.'Config/'.ENVIRONMENT.'/Routes.php')) +if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) { - require APPPATH.'Config/'.ENVIRONMENT.'/Routes.php'; + require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'; } diff --git a/application/Config/Services.php b/application/Config/Services.php index 58a93a0a4e5e..eb9776585cb4 100644 --- a/application/Config/Services.php +++ b/application/Config/Services.php @@ -3,7 +3,7 @@ use CodeIgniter\Config\Services as CoreServices; use CodeIgniter\Config\BaseConfig; -require_once BASEPATH.'Config/Services.php'; +require_once BASEPATH . 'Config/Services.php'; /** * Services Configuration file. @@ -21,30 +21,29 @@ class Services extends CoreServices { -// public static function example($getShared = true) -// { -// if ($getShared) -// { -// return self::getSharedInstance('example'); -// } -// -// return new \CodeIgniter\Example(); -// } - - public static function honeypot(BaseConfig $config = null, $getShared = true) - { - if ($getShared) - { - return self::getSharedInstance('honeypot', $config); - } - - if (is_null($config)) - { - $config = new \Config\Honeypot(); - } - - return new \CodeIgniter\Honeypot\Honeypot($config); - } - + // public static function example($getShared = true) + // { + // if ($getShared) + // { + // return self::getSharedInstance('example'); + // } + // + // return new \CodeIgniter\Example(); + // } + + public static function honeypot(BaseConfig $config = null, $getShared = true) + { + if ($getShared) + { + return self::getSharedInstance('honeypot', $config); + } + + if (is_null($config)) + { + $config = new \Config\Honeypot(); + } + + return new \CodeIgniter\Honeypot\Honeypot($config); + } } diff --git a/application/Config/UserAgents.php b/application/Config/UserAgents.php index f016a6e374d3..326a5d8a60f1 100644 --- a/application/Config/UserAgents.php +++ b/application/Config/UserAgents.php @@ -58,7 +58,6 @@ class UserAgents extends BaseConfig 'symbian' => 'Symbian OS', ]; - // The order of this array should NOT be changed. Many browsers return // multiple browser types so we want to identify the sub-type first. public $browsers = [ @@ -97,19 +96,19 @@ class UserAgents extends BaseConfig public $mobiles = [ // legacy array, old values commented out 'mobileexplorer' => 'Mobile Explorer', - // 'openwave' => 'Open Wave', - // 'opera mini' => 'Opera Mini', - // 'operamini' => 'Opera Mini', - // 'elaine' => 'Palm', + // 'openwave' => 'Open Wave', + // 'opera mini' => 'Opera Mini', + // 'operamini' => 'Opera Mini', + // 'elaine' => 'Palm', 'palmsource' => 'Palm', - // 'digital paths' => 'Palm', - // 'avantgo' => 'Avantgo', - // 'xiino' => 'Xiino', + // 'digital paths' => 'Palm', + // 'avantgo' => 'Avantgo', + // 'xiino' => 'Xiino', 'palmscape' => 'Palmscape', - // 'nokia' => 'Nokia', - // 'ericsson' => 'Ericsson', - // 'blackberry' => 'BlackBerry', - // 'motorola' => 'Motorola' + // 'nokia' => 'Nokia', + // 'ericsson' => 'Ericsson', + // 'blackberry' => 'BlackBerry', + // 'motorola' => 'Motorola' // Phones and Manufacturers 'motorola' => 'Motorola', diff --git a/application/Config/Validation.php b/application/Config/Validation.php index 1b45f4e90624..97f08c752671 100644 --- a/application/Config/Validation.php +++ b/application/Config/Validation.php @@ -27,7 +27,7 @@ class Validation */ public $templates = [ 'list' => 'CodeIgniter\Validation\Views\list', - 'single' => 'CodeIgniter\Validation\Views\single' + 'single' => 'CodeIgniter\Validation\Views\single', ]; //-------------------------------------------------------------------- diff --git a/application/Config/View.php b/application/Config/View.php index cacb57a97704..f66b2532f0f7 100644 --- a/application/Config/View.php +++ b/application/Config/View.php @@ -25,10 +25,10 @@ class View extends \CodeIgniter\Config\View */ 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. - */ + /** + * 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 = []; } diff --git a/application/Filters/CSRF.php b/application/Filters/CSRF.php index 221ae1316497..a5355556ca4a 100644 --- a/application/Filters/CSRF.php +++ b/application/Filters/CSRF.php @@ -52,7 +52,7 @@ public function before(RequestInterface $request) * We don't have anything to do here. * * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response * * @return mixed */ diff --git a/application/Filters/DebugToolbar.php b/application/Filters/DebugToolbar.php index d28b45554a19..145f97dfda0f 100644 --- a/application/Filters/DebugToolbar.php +++ b/application/Filters/DebugToolbar.php @@ -17,7 +17,6 @@ class DebugToolbar implements FilterInterface */ public function before(RequestInterface $request) { - } //-------------------------------------------------------------------- @@ -27,13 +26,13 @@ public function before(RequestInterface $request) * and debug information and display it in a toolbar. * * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response * * @return mixed */ public function after(RequestInterface $request, ResponseInterface $response) { - if ( ! is_cli() && CI_DEBUG) + if (! is_cli() && CI_DEBUG) { global $app; @@ -51,12 +50,12 @@ public function after(RequestInterface $request, ResponseInterface $response) // Updated to time() so we can get history $time = time(); - if (! is_dir(WRITEPATH.'debugbar')) + if (! is_dir(WRITEPATH . 'debugbar')) { - mkdir(WRITEPATH.'debugbar', 0777); + mkdir(WRITEPATH . 'debugbar', 0777); } - write_file(WRITEPATH .'debugbar/'.'debugbar_' . $time, $data, 'w+'); + write_file(WRITEPATH . 'debugbar/' . 'debugbar_' . $time, $data, 'w+'); $format = $response->getHeaderLine('content-type'); diff --git a/application/Filters/Honeypot.php b/application/Filters/Honeypot.php index 42ae06d970bb..a16a55c02a44 100644 --- a/application/Filters/Honeypot.php +++ b/application/Filters/Honeypot.php @@ -31,8 +31,8 @@ public function before(RequestInterface $request) /** * Attach a honypot to the current response. * - * @param CodeIgniter\HTTP\RequestInterface $request - * @param CodeIgniter\HTTP\ResponseInterface $response + * @param CodeIgniter\HTTP\RequestInterface $request + * @param CodeIgniter\HTTP\ResponseInterface $response * @return mixed */ public function after(RequestInterface $request, ResponseInterface $response) diff --git a/application/Filters/Throttle.php b/application/Filters/Throttle.php index 02dda6032495..b2659e549eb5 100644 --- a/application/Filters/Throttle.php +++ b/application/Filters/Throttle.php @@ -34,7 +34,7 @@ public function before(RequestInterface $request) * We don't have anything to do here. * * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response * * @return mixed */ diff --git a/spark b/spark index c2e97ea0c6e5..5b265d76a07a 100755 --- a/spark +++ b/spark @@ -22,7 +22,7 @@ */ // Refuse to run when called from php-cgi -if (substr(php_sapi_name(), 0, 3) == 'cgi') +if (substr(php_sapi_name(), 0, 3) === 'cgi') { die("The cli tool is not supported when running php-cgi. It needs php-cli to function!\n\n"); } @@ -37,12 +37,12 @@ $paths = new Config\Paths(); $public = trim($paths->publicDirectory, '/'); // Path to the front controller -define('FCPATH', realpath($public).DIRECTORY_SEPARATOR); +define('FCPATH', realpath($public) . DIRECTORY_SEPARATOR); // Ensure the current directory is pointing to the front controller's directory chdir($public); -$app = require rtrim($paths->systemDirectory,'/ ').'/bootstrap.php'; +$app = require rtrim($paths->systemDirectory, '/ ') . '/bootstrap.php'; // Grab our Console $console = new \CodeIgniter\CLI\Console($app); diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 85c7e0821b7f..55bfc1f483cb 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\Format; use CodeIgniter\HTTP\Response; @@ -60,32 +61,32 @@ trait ResponseTrait * @var array */ protected $codes = [ - 'created' => 201, - 'deleted' => 200, - '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, + 'created' => 201, + 'deleted' => 200, + '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, ]; //-------------------------------------------------------------------- @@ -94,9 +95,9 @@ trait ResponseTrait * Provides a single, simple method to return an API response, formatted * to match the requested format, with proper content-type and status code. * - * @param null $data - * @param int $status - * @param string $message + * @param null $data + * @param integer $status + * @param string $message * * @return mixed */ @@ -130,23 +131,23 @@ public function respond($data = null, int $status = null, string $message = '') * Used for generic failures that no custom methods exist for. * * @param string|array $messages - * @param int|null $status HTTP status code - * @param string|null $code Custom, API-specific, error code + * @param integer|null $status HTTP status code + * @param string|null $code Custom, API-specific, error code * @param string $customMessage * * @return mixed */ public function fail($messages, int $status = 400, string $code = null, string $customMessage = '') { - if ( ! is_array($messages)) + if (! is_array($messages)) { $messages = ['error' => $messages]; } $response = [ - 'status' => $status, - 'error' => $code === null ? $status : $code, - 'messages' => $messages, + 'status' => $status, + 'error' => $code === null ? $status : $code, + 'messages' => $messages, ]; return $this->respond($response, $status, $customMessage); @@ -351,7 +352,7 @@ protected function format($data = null) $this->response->setContentType($format); // if we don't have a formatter, make one - if ( ! isset($this->formatter)) + if (! isset($this->formatter)) { // if no formatter, use the default $this->formatter = $config->getFormatter($format); diff --git a/system/Autoloader/Autoloader.php b/system/Autoloader/Autoloader.php index 7c060e10b30a..7f31aef04cd9 100644 --- a/system/Autoloader/Autoloader.php +++ b/system/Autoloader/Autoloader.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -144,7 +144,7 @@ public function register() $config = is_array($this->classmap) ? $this->classmap : []; spl_autoload_register(function ($class) use ($config) { - if ( ! array_key_exists($class, $config)) + if (! array_key_exists($class, $config)) { return false; } @@ -181,7 +181,6 @@ public function addNamespace(string $namespace, string $path) $this->prefixes[$namespace] = [$path]; } - return $this; } @@ -220,7 +219,7 @@ public function loadClass(string $class) // Nothing? One last chance by looking // in common CodeIgniter folders. - if ( ! $mapped_file) + if (! $mapped_file) { $mapped_file = $this->loadLegacy($class); } @@ -321,7 +320,7 @@ protected function loadLegacy(string $class) * * @param string $file * - * @return bool + * @return boolean */ protected function requireFile(string $file) { diff --git a/system/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php index cb69d9f941c2..f846e4a68efe 100644 --- a/system/Autoloader/FileLocator.php +++ b/system/Autoloader/FileLocator.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\Autoload; /** @@ -43,7 +44,6 @@ * Allows loading non-class files in a namespaced manner. * Works with Helpers, Views, etc. * - * * @package CodeIgniter */ class FileLocator @@ -91,7 +91,7 @@ public function locateFile(string $file, string $folder = null, string $ext = 'p $file = strpos($file, '.' . $ext) !== false ? $file : $file . '.' . $ext; // Clean the folder name from the filename - if ( ! empty($folder)) + if (! empty($folder)) { $file = str_replace($folder . '/', '', $file); } @@ -109,22 +109,24 @@ public function locateFile(string $file, string $folder = null, string $ext = 'p // The first segment will be empty if a slash started the filename. if (empty($segments[0])) + { unset($segments[0]); + } - $path = ''; - $prefix = ''; + $path = ''; + $prefix = ''; $filename = ''; - while ( ! empty($segments)) + while (! empty($segments)) { $prefix .= empty($prefix) ? ucfirst(array_shift($segments)) : '\\' . ucfirst(array_shift($segments)); - if ( ! array_key_exists($prefix, $this->namespaces)) + if (! array_key_exists($prefix, $this->namespaces)) { continue; } - $path = $this->namespaces[$prefix] . '/'; + $path = $this->namespaces[$prefix] . '/'; $filename = implode('/', $segments); break; } @@ -132,14 +134,14 @@ public function locateFile(string $file, string $folder = null, string $ext = 'p // 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($filename, $folder) === false) + if (! empty($folder) && strpos($filename, $folder) === false) { $filename = $folder . '/' . $filename; } $path .= $filename; - if ( ! $this->requireFile($path)) + if (! $this->requireFile($path)) { $path = ''; } @@ -158,16 +160,16 @@ public function locateFile(string $file, string $folder = null, string $ext = 'p */ public function getClassname(string $file) : string { - $php = file_get_contents($file); - $tokens = token_get_all($php); - $count = count($tokens); - $dlm = false; - $namespace = ''; + $php = file_get_contents($file); + $tokens = token_get_all($php); + $count = count($tokens); + $dlm = false; + $namespace = ''; $class_name = ''; for ($i = 2; $i < $count; $i++) { - if ((isset($tokens[$i-2][1]) && ($tokens[$i-2][1] == "phpnamespace" || $tokens[$i-2][1] == "namespace")) || ($dlm && $tokens[$i-1][0] == T_NS_SEPARATOR && $tokens[$i][0] == T_STRING)) + if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $tokens[$i][0] === T_STRING)) { if (! $dlm) { @@ -175,26 +177,29 @@ public function getClassname(string $file) : string } if (isset($tokens[$i][1])) { - $namespace = $namespace ? $namespace."\\".$tokens[$i][1] : $tokens[$i][1]; + $namespace = $namespace ? $namespace . '\\' . $tokens[$i][1] : $tokens[$i][1]; $dlm = true; } } - elseif ($dlm && ($tokens[$i][0] != T_NS_SEPARATOR) && ($tokens[$i][0] != T_STRING)) + elseif ($dlm && ($tokens[$i][0] !== T_NS_SEPARATOR) && ($tokens[$i][0] !== T_STRING)) { $dlm = false; } - if (($tokens[$i-2][0] == T_CLASS || (isset($tokens[$i-2][1]) && $tokens[$i-2][1] == "phpclass")) - && $tokens[$i-1][0] == T_WHITESPACE - && $tokens[$i][0] == T_STRING) + if (($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass')) + && $tokens[$i - 1][0] === T_WHITESPACE + && $tokens[$i][0] === T_STRING) { $class_name = $tokens[$i][1]; break; } } - if( empty( $class_name ) ) return ""; + if (empty( $class_name )) + { + return ''; + } - return $namespace .'\\'. $class_name; + return $namespace . '\\' . $class_name; } //-------------------------------------------------------------------- @@ -255,7 +260,7 @@ public function findQualifiedNameFromPath(string $path) { $path = realpath($path); - if ( ! $path) + if (! $path) { return; } @@ -264,7 +269,9 @@ public function findQualifiedNameFromPath(string $path) { $nsPath = realpath($nsPath); if (is_numeric($namespace) || empty($nsPath)) + { continue; + } if (mb_strpos($path, $nsPath) === 0) { @@ -291,7 +298,9 @@ public function findQualifiedNameFromPath(string $path) public function listFiles(string $path): array { if (empty($path)) + { return []; + } $files = []; helper('filesystem'); @@ -300,14 +309,18 @@ public function listFiles(string $path): array { $fullPath = realpath(rtrim($nsPath, '/') . '/' . $path); - if ( ! is_dir($fullPath)) + if (! is_dir($fullPath)) + { continue; + } $tempFiles = get_filenames($fullPath, true); //CLI::newLine($tempFiles); if (! empty($tempFiles)) + { $files = array_merge($files, $tempFiles); + } } return $files; @@ -320,13 +333,15 @@ public function listFiles(string $path): array * @param string $file * @param string|null $folder * - * @return string + * @return string * @internal param string $ext - * */ protected function legacyLocate(string $file, string $folder = null): string { - $paths = [APPPATH, BASEPATH]; + $paths = [ + APPPATH, + BASEPATH, + ]; foreach ($paths as $path) { @@ -348,9 +363,9 @@ protected function legacyLocate(string $file, string $folder = null): string * out to it's own method to make testing simpler. * * @codeCoverageIgnore - * @param string $path + * @param string $path * - * @return bool + * @return boolean */ protected function requireFile(string $path): bool { diff --git a/system/CLI/BaseCommand.php b/system/CLI/BaseCommand.php index 0526b414be0d..eceabb4ea109 100644 --- a/system/CLI/BaseCommand.php +++ b/system/CLI/BaseCommand.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Psr\Log\LoggerInterface; /** @@ -107,7 +108,6 @@ abstract class BaseCommand //-------------------------------------------------------------------- - /** * BaseCommand constructor. * @@ -116,7 +116,7 @@ abstract class BaseCommand */ public function __construct(LoggerInterface $logger, CommandRunner $commands) { - $this->logger = $logger; + $this->logger = $logger; $this->commands = $commands; } @@ -130,7 +130,7 @@ abstract public function run(array $params); * Can be used by a command to run other commands. * * @param string $command - * @param array $params + * @param array $params * * @return mixed */ @@ -184,19 +184,19 @@ public function __get(string $key) public function showHelp() { // 4 spaces insted of tab - $tab = " "; + $tab = ' '; CLI::write(lang('CLI.helpDescription'), 'yellow'); CLI::write($tab . $this->description); CLI::newLine(); CLI::write(lang('CLI.helpUsage'), 'yellow'); - $usage = empty($this->usage) ? $this->name . " [arguments]" : $this->usage; + $usage = empty($this->usage) ? $this->name . ' [arguments]' : $this->usage; CLI::write($tab . $usage); CLI::newLine(); $pad = max($this->getPad($this->options, 6), $this->getPad($this->arguments, 6)); - if ( ! empty($this->arguments)) + if (! empty($this->arguments)) { CLI::write(lang('CLI.helpArguments'), 'yellow'); foreach ($this->arguments as $argument => $description) @@ -206,7 +206,7 @@ public function showHelp() CLI::newLine(); } - if ( ! empty($this->options)) + if (! empty($this->options)) { CLI::write(lang('CLI.helpOptions'), 'yellow'); foreach ($this->options as $option => $description) @@ -222,10 +222,10 @@ public function showHelp() /** * Get pad for $key => $value array output * - * @param array $array - * @param int $pad + * @param array $array + * @param integer $pad * - * @return int + * @return integer */ public function getPad($array, int $pad) { diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 4a79bd877f7f..16d7aa2a84d8 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\Exceptions\CLIException; /** @@ -66,7 +67,7 @@ class CLI /** * Is the readline library on the system? * - * @var bool + * @var boolean */ public static $readline_support = false; @@ -80,51 +81,54 @@ class CLI /** * Has the class already been initialized? * - * @var bool + * @var boolean */ protected static $initialized = false; /** * Foreground color list + * * @var array */ protected static $foreground_colors = [ - 'black' => '0;30', - 'dark_gray' => '1;30', - 'blue' => '0;34', - 'dark_blue' => '1;34', - 'light_blue' => '1;34', - 'green' => '0;32', - 'light_green' => '1;32', - 'cyan' => '0;36', - 'light_cyan' => '1;36', - 'red' => '0;31', - 'light_red' => '1;31', - 'purple' => '0;35', - 'light_purple' => '1;35', - 'light_yellow' => '0;33', - 'yellow' => '1;33', - 'light_gray' => '0;37', - 'white' => '1;37', + 'black' => '0;30', + 'dark_gray' => '1;30', + 'blue' => '0;34', + 'dark_blue' => '1;34', + 'light_blue' => '1;34', + 'green' => '0;32', + 'light_green' => '1;32', + 'cyan' => '0;36', + 'light_cyan' => '1;36', + 'red' => '0;31', + 'light_red' => '1;31', + 'purple' => '0;35', + 'light_purple' => '1;35', + 'light_yellow' => '0;33', + 'yellow' => '1;33', + 'light_gray' => '0;37', + 'white' => '1;37', ]; /** * Background color list + * * @var array */ protected static $background_colors = [ - 'black' => '40', - 'red' => '41', - 'green' => '42', - 'yellow' => '43', - 'blue' => '44', - 'magenta' => '45', - 'cyan' => '46', + 'black' => '40', + 'red' => '41', + 'green' => '42', + 'yellow' => '43', + 'blue' => '44', + 'magenta' => '45', + 'cyan' => '46', 'light_gray' => '47', ]; /** * List of array segments. + * * @var array */ protected static $segments = []; @@ -148,7 +152,7 @@ public static function init() // clear segments & options to keep testing clean static::$segments = []; - static::$options = []; + static::$options = []; static::parseCommandLine(); @@ -163,8 +167,8 @@ public static function init() * Named options must be in the following formats: * php index.php user -v --v -name=John --name=John * - * @param string $prefix - * @return string + * @param string $prefix + * @return string * * @codeCoverageIgnore */ @@ -199,27 +203,27 @@ public static function input(string $prefix = null): string * // Do not provide options but requires a valid email * $email = CLI::prompt('What is your email?', null, 'required|valid_email'); * - * @param string $field Output "field" question - * @param string|array $options String to a defaul value, array to a list of options (the first option will be the default value) - * @param string $validation Validation rules + * @param string $field Output "field" question + * @param string|array $options String to a defaul value, array to a list of options (the first option will be the default value) + * @param string $validation Validation rules * - * @return string The user input + * @return string The user input * @codeCoverageIgnore */ public static function prompt($field, $options = null, $validation = null): string { $extra_output = ''; - $default = ''; + $default = ''; if (is_string($options)) { $extra_output = ' [' . static::color($options, 'white') . ']'; - $default = $options; + $default = $options; } if (is_array($options) && $options) { - $opts = $options; + $opts = $options; $extra_output_default = static::color($opts[0], 'white'); unset($opts[0]); @@ -231,8 +235,8 @@ public static function prompt($field, $options = null, $validation = null): stri else { $extra_output = ' [' . $extra_output_default . ', ' . implode(', ', $opts) . ']'; - $validation .= '|in_list[' . implode(',', $options) . ']'; - $validation = trim($validation, '|'); + $validation .= '|in_list[' . implode(',', $options) . ']'; + $validation = trim($validation, '|'); } $default = $options[0]; @@ -245,7 +249,7 @@ public static function prompt($field, $options = null, $validation = null): stri if (isset($validation)) { - while ( ! static::validate($field, $input, $validation)) + while (! static::validate($field, $input, $validation)) { $input = static::prompt($field, $options, $validation); } @@ -259,11 +263,11 @@ public static function prompt($field, $options = null, $validation = null): stri /** * Validate one prompt "field" at a time * - * @param string $field Prompt "field" output - * @param string $value Input value - * @param string $rules Validation rules + * @param string $field Prompt "field" output + * @param string $value Input value + * @param string $rules Validation rules * - * @return boolean + * @return boolean * @codeCoverageIgnore */ protected static function validate($field, $value, $rules) @@ -287,7 +291,7 @@ protected static function validate($field, $value, $rules) /** * Outputs a string to the cli. * - * @param string $text The text to output + * @param string $text The text to output * @param string $foreground * @param string $background */ @@ -306,9 +310,9 @@ public static function write(string $text = '', string $foreground = null, strin /** * Outputs an error to the CLI using STDERR instead of STDOUT * - * @param string|array $text The text to output, or array of errors - * @param string $foreground - * @param string $background + * @param string|array $text The text to output, or array of errors + * @param string $foreground + * @param string $background */ public static function error(string $text, string $foreground = 'light_red', string $background = null) { @@ -325,7 +329,7 @@ public static function error(string $text, string $foreground = 'light_red', str /** * Beeps a certain number of times. * - * @param int $num The number of times to beep + * @param integer $num The number of times to beep */ public static function beep(int $num = 1) { @@ -338,8 +342,8 @@ public static function beep(int $num = 1) * Waits a certain number of seconds, optionally showing a wait message and * waiting for a key press. * - * @param int $seconds Number of seconds - * @param bool $countdown Show a countdown or not + * @param integer $seconds Number of seconds + * @param boolean $countdown Show a countdown or not */ public static function wait(int $seconds, bool $countdown = false) { @@ -379,7 +383,7 @@ public static function wait(int $seconds, bool $countdown = false) */ public static function isWindows() { - return stripos(PHP_OS, 'WIN') === 0; + return stripos(PHP_OS, 'WIN') === 0; } //-------------------------------------------------------------------- @@ -387,9 +391,9 @@ public static function isWindows() /** * Enter a number of empty lines * - * @param int $num Number of lines to output + * @param integer $num Number of lines to output * - * @return void + * @return void */ public static function newLine(int $num = 1) { @@ -405,7 +409,7 @@ public static function newLine(int $num = 1) /** * Clears the screen of output * - * @return void + * @return void * @codeCoverageIgnore */ public static function clearScreen() @@ -416,7 +420,7 @@ public static function clearScreen() ? static::newLine(40) // Anything with a flair of Unix will handle these magic characters - : fwrite(STDOUT, chr(27) . "[H" . chr(27) . "[2J"); + : fwrite(STDOUT, chr(27) . '[H' . chr(27) . '[2J'); } //-------------------------------------------------------------------- @@ -425,12 +429,12 @@ public static function clearScreen() * Returns the given text with the correct color codes for a foreground and * optionally a background color. * - * @param string $text The text to color - * @param string $foreground The foreground color - * @param string $background The background color - * @param string $format Other formatting to apply. Currently only 'underline' is understood + * @param string $text The text to color + * @param string $foreground The foreground color + * @param string $background The background color + * @param string $format Other formatting to apply. Currently only 'underline' is understood * - * @return string The color coded string + * @return string The color coded string */ public static function color(string $text, string $foreground, string $background = null, string $format = null) { @@ -441,7 +445,7 @@ public static function color(string $text, string $foreground, string $backgroun // @codeCoverageIgnoreEnd } - if ( ! array_key_exists($foreground, static::$foreground_colors)) + if (! array_key_exists($foreground, static::$foreground_colors)) { throw CLIException::forInvalidColor('foreground', $foreground); } @@ -451,11 +455,11 @@ public static function color(string $text, string $foreground, string $backgroun throw CLIException::forInvalidColor('background', $background); } - $string = "\033[" . static::$foreground_colors[$foreground] . "m"; + $string = "\033[" . static::$foreground_colors[$foreground] . 'm'; if ($background !== null) { - $string .= "\033[" . static::$background_colors[$background] . "m"; + $string .= "\033[" . static::$background_colors[$background] . 'm'; } if ($format === 'underline') @@ -475,13 +479,13 @@ public static function color(string $text, string $foreground, string $backgroun * This only works on *nix-based systems, so return a sane default * for Windows environments. * - * @param int $default + * @param integer $default * - * @return int + * @return integer */ public static function getWidth(int $default = 80): int { - if (static::isWindows() || (int) shell_exec('tput cols') == 0) + if (static::isWindows() || (int) shell_exec('tput cols') === 0) { // @codeCoverageIgnoreStart return $default; @@ -498,9 +502,9 @@ public static function getWidth(int $default = 80): int * This only works on *nix-based systems, so return a sane default * for Windows environments. * - * @param int $default + * @param integer $default * - * @return int + * @return integer */ public static function getHeight(int $default = 32): int { @@ -520,8 +524,8 @@ public static function getHeight(int $default = 32): int * Displays a progress bar on the CLI. You must call it repeatedly * to update it. Set $thisStep = false to erase the progress bar. * - * @param int $thisStep - * @param int $totalSteps + * @param integer $thisStep + * @param integer $totalSteps */ public static function showProgress($thisStep = 1, int $totalSteps = 10) { @@ -537,16 +541,16 @@ public static function showProgress($thisStep = 1, int $totalSteps = 10) if ($thisStep !== false) { // Don't allow div by zero or negative numbers.... - $thisStep = abs($thisStep); + $thisStep = abs($thisStep); $totalSteps = $totalSteps < 1 ? 1 : $totalSteps; $percent = intval(($thisStep / $totalSteps) * 100); - $step = (int) round($percent / 10); + $step = (int) round($percent / 10); // Write the progress bar fwrite(STDOUT, "[\033[32m" . str_repeat('#', $step) . str_repeat('.', 10 - $step) . "\033[0m]"); // Textual representation... - fwrite(STDOUT, sprintf(" %3d%% Complete", $percent) . PHP_EOL); + fwrite(STDOUT, sprintf(' %3d%% Complete', $percent) . PHP_EOL); } else { @@ -565,9 +569,9 @@ public static function showProgress($thisStep = 1, int $totalSteps = 10) * will padded with that many spaces to the left. Useful when printing * short descriptions that need to start on an existing line. * - * @param string $string - * @param int $max - * @param int $pad_left + * @param string $string + * @param integer $max + * @param integer $pad_left * * @return string */ @@ -578,7 +582,7 @@ public static function wrap(string $string = null, int $max = 0, int $pad_left = return ''; } - if ($max == 0) + if ($max === 0) { $max = CLI::getWidth(); } @@ -599,9 +603,9 @@ public static function wrap(string $string = null, int $max = 0, int $pad_left = $first = true; array_walk($lines, function (&$line, $index) use ($pad_left, &$first) { - if ( ! $first) + if (! $first) { - $line = str_repeat(" ", $pad_left) . $line; + $line = str_repeat(' ', $pad_left) . $line; } else { @@ -637,7 +641,7 @@ protected static function parseCommandLine() { // If there's no '-' at the beginning of the argument // then add it to our segments. - if ( ! $optionsFound && mb_strpos($_SERVER['argv'][$i], '-') === false) + if (! $optionsFound && mb_strpos($_SERVER['argv'][$i], '-') === false) { static::$segments[] = $_SERVER['argv'][$i]; continue; @@ -648,7 +652,7 @@ protected static function parseCommandLine() // value belonging to this option. $optionsFound = true; - $arg = str_replace('-', '', $_SERVER['argv'][$i]); + $arg = str_replace('-', '', $_SERVER['argv'][$i]); $value = null; // if there is a following segment, and it doesn't start with a dash, it's a value. @@ -691,13 +695,13 @@ public static function getURI() * // segment(3) is 'three', not '-f' or 'anOption' * > php spark one two -f anOption three * - * @param int $index + * @param integer $index * * @return mixed|null */ public static function getSegment(int $index) { - if ( ! isset(static::$segments[$index - 1])) + if (! isset(static::$segments[$index - 1])) { return null; } @@ -725,11 +729,11 @@ public static function getSegments() * * @param string $name * - * @return bool|mixed|null + * @return boolean|mixed|null */ public static function getOption(string $name) { - if ( ! array_key_exists($name, static::$options)) + if (! array_key_exists($name, static::$options)) { return null; } @@ -790,8 +794,8 @@ public static function getOptionString(): string /** * Returns a well formated table * - * @param array $tbody List of rows - * @param array $thead List of columns + * @param array $tbody List of rows + * @param array $thead List of columns * * @return string */ @@ -801,7 +805,7 @@ public static function table(array $tbody, array $thead = []) $table_rows = []; // We need only indexes and not keys - if ( ! empty($thead)) + if (! empty($thead)) { $table_rows[] = array_values($thead); } @@ -823,7 +827,7 @@ public static function table(array $tbody, array $thead = []) $max_cols_lengths = []; // Read row by row and define the longest columns - for ($row = 0; $row < $total_rows; $row ++ ) + for ($row = 0; $row < $total_rows; $row ++) { $column = 0; // Current column index foreach ($table_rows[$row] as $col) @@ -834,7 +838,7 @@ public static function table(array $tbody, array $thead = []) // If the current column does not have a value among the larger ones // or the value of this is greater than the existing one // then, now, this assumes the maximum length - if ( ! isset($max_cols_lengths[$column]) || $all_cols_lengths[$row][$column] > $max_cols_lengths[$column]) + if (! isset($max_cols_lengths[$column]) || $all_cols_lengths[$row][$column] > $max_cols_lengths[$column]) { $max_cols_lengths[$column] = $all_cols_lengths[$row][$column]; } @@ -846,7 +850,7 @@ public static function table(array $tbody, array $thead = []) // Read row by row and add spaces at the end of the columns // to match the exact column length - for ($row = 0; $row < $total_rows; $row ++ ) + for ($row = 0; $row < $total_rows; $row ++) { $column = 0; foreach ($table_rows[$row] as $col) @@ -863,7 +867,7 @@ public static function table(array $tbody, array $thead = []) $table = ''; // Joins columns and append the well formatted rows to the table - for ($row = 0; $row < $total_rows; $row ++ ) + for ($row = 0; $row < $total_rows; $row ++) { // Set the table border-top if ($row === 0) diff --git a/system/CLI/CommandRunner.php b/system/CLI/CommandRunner.php index 29ddbffe8e0c..7585aa9fd97f 100644 --- a/system/CLI/CommandRunner.php +++ b/system/CLI/CommandRunner.php @@ -28,14 +28,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Controller; class CommandRunner extends Controller @@ -106,7 +107,7 @@ public function index(array $params) */ protected function runCommand(string $command, array $params) { - if ( ! isset($this->commands[$command])) + if (! isset($this->commands[$command])) { CLI::error('Command \'' . $command . '\' not found'); CLI::newLine(); @@ -116,7 +117,7 @@ protected function runCommand(string $command, array $params) // The file would have already been loaded during the // createCommandList function... $className = $this->commands[$command]['class']; - $class = new $className($this->logger, $this); + $class = new $className($this->logger, $this); return $class->run($params); } @@ -131,7 +132,7 @@ protected function runCommand(string $command, array $params) */ protected function createCommandList() { - $files = service('locator')->listFiles("Commands/"); + $files = service('locator')->listFiles('Commands/'); // If no matching command files were found, bail if (empty($files)) @@ -151,7 +152,7 @@ protected function createCommandList() $class = new \ReflectionClass($className); - if ( ! $class->isInstantiable() || ! $class->isSubclassOf(BaseCommand::class)) + if (! $class->isInstantiable() || ! $class->isSubclassOf(BaseCommand::class)) { continue; } @@ -162,10 +163,10 @@ protected function createCommandList() if ($class->group !== null) { $this->commands[$class->name] = [ - 'class' => $className, - 'file' => $file, - 'group' => $class->group, - 'description' => $class->description + 'class' => $className, + 'file' => $file, + 'group' => $class->group, + 'description' => $class->description, ]; } diff --git a/system/CLI/Console.php b/system/CLI/Console.php index 7daccf9b0137..1b7f54658330 100644 --- a/system/CLI/Console.php +++ b/system/CLI/Console.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CodeIgniter; class Console @@ -42,13 +43,13 @@ class Console /** * Main CodeIgniter instance. + * * @var CodeIgniter */ protected $app; //-------------------------------------------------------------------- - /** * Console constructor. * @@ -64,7 +65,7 @@ public function __construct(CodeIgniter $app) /** * Runs the current command discovered on the CLI. * - * @param bool $useSafeOutput + * @param boolean $useSafeOutput * * @return \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed * @throws \CodeIgniter\HTTP\RedirectException diff --git a/system/Cache/CacheFactory.php b/system/Cache/CacheFactory.php index 51a644cfcc07..9a5563fbbd9c 100644 --- a/system/Cache/CacheFactory.php +++ b/system/Cache/CacheFactory.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -50,7 +50,7 @@ class CacheFactory /** * Attempts to create the desired cache handler, based upon the * - * @param $config + * @param $config * @param string $handler * @param string $backup * @@ -58,20 +58,20 @@ class CacheFactory */ public static function getHandler($config, string $handler = null, string $backup = null) { - if ( ! isset($config->validHandlers) || ! is_array($config->validHandlers)) + if (! isset($config->validHandlers) || ! is_array($config->validHandlers)) { throw CacheException::forInvalidHandlers(); } - if ( ! isset($config->handler) || ! isset($config->backupHandler)) + if (! isset($config->handler) || ! isset($config->backupHandler)) { throw CacheException::forNoBackup(); } $handler = ! empty($handler) ? $handler : $config->handler; - $backup = ! empty($backup) ? $backup : $config->backupHandler; + $backup = ! empty($backup) ? $backup : $config->backupHandler; - if ( ! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) + if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) { throw CacheException::forHandlerNotFound(); } @@ -79,11 +79,11 @@ public static function getHandler($config, string $handler = null, string $backu // Get an instance of our handler. $adapter = new $config->validHandlers[$handler]($config); - if ( ! $adapter->isSupported()) + if (! $adapter->isSupported()) { $adapter = new $config->validHandlers[$backup]($config); - if ( ! $adapter->isSupported()) + if (! $adapter->isSupported()) { // Log stuff here, don't throw exception. No need to raise a fuss. // Fall back to the dummy adapter. diff --git a/system/Cache/CacheInterface.php b/system/Cache/CacheInterface.php index d5b5e6624c5a..82e1cf600c4c 100644 --- a/system/Cache/CacheInterface.php +++ b/system/Cache/CacheInterface.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + interface CacheInterface { @@ -48,7 +49,7 @@ public function initialize(); /** * Attempts to fetch an item from the cache store. * - * @param string $key Cache item name + * @param string $key Cache item name * * @return mixed */ @@ -59,9 +60,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -72,7 +73,7 @@ public function save(string $key, $value, int $ttl = 60); /** * Deletes a specific item from the cache store. * - * @param string $key Cache item name + * @param string $key Cache item name * * @return mixed */ @@ -83,8 +84,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -95,8 +96,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -128,7 +129,7 @@ public function getCacheInfo(); /** * Returns detailed information about the specific item in the cache. * - * @param string $key Cache item name. + * @param string $key Cache item name. * * @return mixed */ diff --git a/system/Cache/Exceptions/ExceptionInterface.php b/system/Cache/Exceptions/ExceptionInterface.php index ea72e7dafbd8..4bfaddb16639 100644 --- a/system/Cache/Exceptions/ExceptionInterface.php +++ b/system/Cache/Exceptions/ExceptionInterface.php @@ -6,6 +6,7 @@ * * catch (\CodeIgniter\Cache\Exceptions\ExceptionInterface) { ... } */ + interface ExceptionInterface { } diff --git a/system/Cache/Handlers/DummyHandler.php b/system/Cache/Handlers/DummyHandler.php index 388b10f3f986..282e752b10c8 100644 --- a/system/Cache/Handlers/DummyHandler.php +++ b/system/Cache/Handlers/DummyHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Cache\CacheInterface; class DummyHandler implements CacheInterface @@ -53,7 +54,7 @@ public function initialize() /** * Attempts to fetch an item from the cache store. * - * @param string $key Cache item name + * @param string $key Cache item name * * @return mixed */ @@ -67,9 +68,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -83,7 +84,7 @@ public function save(string $key, $value, int $ttl = 60) /** * Deletes a specific item from the cache store. * - * @param string $key Cache item name + * @param string $key Cache item name * * @return mixed */ @@ -97,8 +98,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -112,8 +113,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -154,7 +155,7 @@ public function getCacheInfo() /** * Returns detailed information about the specific item in the cache. * - * @param string $key Cache item name. + * @param string $key Cache item name. * * @return mixed */ diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index 50bd14ca242d..3a94238e9940 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Cache\CacheInterface; class FileHandler implements CacheInterface @@ -59,7 +60,7 @@ class FileHandler implements CacheInterface public function __construct($config) { $this->prefix = $config->prefix ?: ''; - $this->path = ! empty($config->storePath) ? $config->storePath : WRITEPATH . 'cache'; + $this->path = ! empty($config->storePath) ? $config->storePath : WRITEPATH . 'cache'; $this->path = rtrim($this->path, '/') . '/'; } @@ -97,9 +98,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -108,9 +109,9 @@ public function save(string $key, $value, int $ttl = 60) $key = $this->prefix . $key; $contents = [ - 'time' => time(), - 'ttl' => $ttl, - 'data' => $value, + 'time' => time(), + 'ttl' => $ttl, + 'data' => $value, ]; if ($this->writeFile($this->path . $key, serialize($contents))) @@ -144,8 +145,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -157,9 +158,12 @@ public function increment(string $key, int $offset = 1) if ($data === false) { - $data = ['data' => 0, 'ttl' => 60]; + $data = [ + 'data' => 0, + 'ttl' => 60, + ]; } - elseif ( ! is_int($data['data'])) + elseif (! is_int($data['data'])) { return false; } @@ -174,8 +178,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -187,9 +191,12 @@ public function decrement(string $key, int $offset = 1) if ($data === false) { - $data = ['data' => 0, 'ttl' => 60]; + $data = [ + 'data' => 0, + 'ttl' => 60, + ]; } - elseif ( ! is_int($data['data'])) + elseif (! is_int($data['data'])) { return false; } @@ -239,9 +246,9 @@ public function getMetaData(string $key) { $key = $this->prefix . $key; - if ( ! file_exists($this->path . $key)) + if (! file_exists($this->path . $key)) { - return FALSE; + return false; } $data = @unserialize(file_get_contents($this->path . $key)); @@ -250,19 +257,19 @@ public function getMetaData(string $key) { $mtime = filemtime($this->path . $key); - if ( ! isset($data['ttl'])) + if (! isset($data['ttl'])) { - return FALSE; + return false; } return [ 'expire' => $mtime + $data['ttl'], - 'mtime' => $mtime, - 'data' => $data['data'], + 'mtime' => $mtime, + 'data' => $data['data'], ]; } - return FALSE; + return false; } //-------------------------------------------------------------------- @@ -285,11 +292,11 @@ public function isSupported(): bool * * @param string $key * - * @return bool|mixed + * @return boolean|mixed */ protected function getItem(string $key) { - if ( ! is_file($this->path . $key)) + if (! is_file($this->path . $key)) { return false; } @@ -314,11 +321,11 @@ protected function getItem(string $key) /** * Writes a file to disk, or returns false if not successful. * - * @param $path - * @param $data + * @param $path + * @param $data * @param string $mode * - * @return bool + * @return boolean */ protected function writeFile($path, $data, $mode = 'wb') { @@ -360,19 +367,19 @@ protected function writeFile($path, $data, $mode = 'wb') * 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 $del_dir 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) + * @param string $path File path + * @param boolean $del_dir Whether to delete any directories found in the path + * @param boolean $htdocs Whether to skip deleting .htaccess and index page files + * @param integer $_level Current directory depth level (default: 0; internal use only) * - * @return bool + * @return boolean */ protected function deleteFiles($path, $del_dir = false, $htdocs = false, $_level = 0) { // Trim the trailing slash $path = rtrim($path, '/\\'); - if ( ! $current_dir = @opendir($path)) + if (! $current_dir = @opendir($path)) { return false; } @@ -407,23 +414,23 @@ protected function deleteFiles($path, $del_dir = false, $htdocs = false, $_level * * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param bool $top_level_only Look only at the top level directory specified? - * @param bool $_recursion Internal variable to determine recursion status - do not use in calls + * @param string $source_dir Path to source + * @param boolean $top_level_only Look only at the top level directory specified? + * @param boolean $_recursion Internal variable to determine recursion status - do not use in calls * - * @return array|false + * @return array|false */ protected function getDirFileInfo($source_dir, $top_level_only = true, $_recursion = false) { static $_filedata = []; - $relative_path = $source_dir; + $relative_path = $source_dir; if ($fp = @opendir($source_dir)) { // reset the array and make sure $source_dir has a trailing slash on the initial call if ($_recursion === false) { - $_filedata = []; + $_filedata = []; $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } @@ -436,7 +443,7 @@ protected function getDirFileInfo($source_dir, $top_level_only = true, $_recursi } elseif ($file[0] !== '.') { - $_filedata[$file] = $this->getFileInfo($source_dir . $file); + $_filedata[$file] = $this->getFileInfo($source_dir . $file); $_filedata[$file]['relative_path'] = $relative_path; } } @@ -459,14 +466,14 @@ protected function getDirFileInfo($source_dir, $top_level_only = true, $_recursi * 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 $returned_values Array or comma separated string of information returned + * @param string $file Path to file + * @param mixed $returned_values Array or comma separated string of information returned * - * @return array|false + * @return array|false */ protected function getFileInfo(string $file, array $returned_values = ['name', 'server_path', 'size', 'date']) { - if ( ! file_exists($file)) + if (! file_exists($file)) { return false; } diff --git a/system/Cache/Handlers/MemcachedHandler.php b/system/Cache/Handlers/MemcachedHandler.php index 498d93f82773..94e58753801d 100644 --- a/system/Cache/Handlers/MemcachedHandler.php +++ b/system/Cache/Handlers/MemcachedHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Cache\CacheInterface; class MemcachedHandler implements CacheInterface @@ -60,20 +61,20 @@ class MemcachedHandler implements CacheInterface * @var array */ protected $config = [ - 'host' => '127.0.0.1', - 'port' => 11211, + 'host' => '127.0.0.1', + 'port' => 11211, 'weight' => 1, - 'raw' => false, + 'raw' => false, ]; //-------------------------------------------------------------------- public function __construct($config) { - $config = (array)$config; + $config = (array)$config; $this->prefix = $config['prefix'] ?? ''; - if ( ! empty($config)) + if (! empty($config)) { $this->config = array_merge($this->config, $config['memcached']); } @@ -158,9 +159,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -168,9 +169,13 @@ public function save(string $key, $value, int $ttl = 60) { $key = $this->prefix . $key; - if ( ! $this->config['raw']) + if (! $this->config['raw']) { - $value = [$value, time(), $ttl]; + $value = [ + $value, + time(), + $ttl, + ]; } if ($this->memcached instanceof \Memcached) @@ -206,14 +211,14 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ public function increment(string $key, int $offset = 1) { - if ( ! $this->config['raw']) + if (! $this->config['raw']) { return false; } @@ -228,14 +233,14 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ public function decrement(string $key, int $offset = 1) { - if ( ! $this->config['raw']) + if (! $this->config['raw']) { return false; } @@ -288,18 +293,18 @@ public function getMetaData(string $key) $stored = $this->memcached->get($key); - // if not an array, don't try to count for PHP7.2 + // if not an array, don't try to count for PHP7.2 if (! is_array($stored) || count($stored) !== 3) { - return FALSE; + return false; } list($data, $time, $ttl) = $stored; return [ 'expire' => $time + $ttl, - 'mtime' => $time, - 'data' => $data + 'mtime' => $time, + 'data' => $data, ]; } diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index f0c09b4fbe4a..dd20efb897fa 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Cache\CacheInterface; use CodeIgniter\CriticalError; @@ -55,17 +56,17 @@ class PredisHandler implements CacheInterface * @var array */ protected $config = [ - 'scheme' => 'tcp', - 'host' => '127.0.0.1', - 'password' => null, - 'port' => 6379, - 'timeout' => 0, + 'scheme' => 'tcp', + 'host' => '127.0.0.1', + 'password' => null, + 'port' => 6379, + 'timeout' => 0, ]; /** * Predis connection * - * @var Predis + * @var Predis */ protected $redis; @@ -95,7 +96,8 @@ public function initialize() // Check if the connection is valid by trying to get the time. $this->redis->time(); - } catch (\Exception $e) + } + catch (\Exception $e) { // thrown if can't connect to redis server. throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ')'); @@ -113,11 +115,13 @@ public function initialize() */ public function get(string $key) { - $data = array_combine( - ['__ci_type', '__ci_value'], $this->redis->hmget($key, ['__ci_type', '__ci_value']) + $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) + if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) { return false; } @@ -144,9 +148,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -169,7 +173,7 @@ public function save(string $key, $value, int $ttl = 60) return false; } - if ( ! $this->redis->hmset($key, ['__ci_type' => $data_type, '__ci_value' => $value])) + if (! $this->redis->hmset($key, ['__ci_type' => $data_type, '__ci_value' => $value])) { return false; } @@ -198,8 +202,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -213,8 +217,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -267,11 +271,11 @@ public function getMetaData(string $key) { return [ 'expire' => time() + $this->redis->ttl($key), - 'data' => $data['__ci_value'] + 'data' => $data['__ci_value'], ]; } - return FALSE; + return false; } //-------------------------------------------------------------------- diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index c4a5984942db..0498de821bef 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Exceptions\CriticalError; use CodeIgniter\Cache\CacheInterface; @@ -55,16 +56,16 @@ class RedisHandler implements CacheInterface * @var array */ protected $config = [ - 'host' => '127.0.0.1', - 'password' => null, - 'port' => 6379, - 'timeout' => 0, + 'host' => '127.0.0.1', + 'password' => null, + 'port' => 6379, + 'timeout' => 0, ]; /** * Redis connection * - * @var Redis + * @var Redis */ protected $redis; @@ -72,10 +73,10 @@ class RedisHandler implements CacheInterface public function __construct($config) { - $config = (array)$config; + $config = (array)$config; $this->prefix = $config['prefix'] ?? ''; - if ( ! empty($config)) + if (! empty($config)) { $this->config = array_merge($this->config, $config['redis']); } @@ -107,17 +108,18 @@ public function initialize() try { - if ( ! $this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout']) + if (! $this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout']) ) { -// log_message('error', 'Cache: Redis connection failed. Check your configuration.'); + // log_message('error', 'Cache: Redis connection failed. Check your configuration.'); } if (isset($config['password']) && ! $this->redis->auth($config['password'])) { -// log_message('error', 'Cache: Redis authentication failed.'); + // log_message('error', 'Cache: Redis authentication failed.'); } - } catch (\RedisException $e) + } + catch (\RedisException $e) { throw new CriticalError('Cache: Redis connection refused (' . $e->getMessage() . ')'); } @@ -138,7 +140,7 @@ public function get(string $key) $data = $this->redis->hMGet($key, ['__ci_type', '__ci_value']); - if ( ! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) + if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) { return false; } @@ -165,9 +167,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -192,7 +194,7 @@ public function save(string $key, $value, int $ttl = 60) return false; } - if ( ! $this->redis->hMSet($key, ['__ci_type' => $data_type, '__ci_value' => $value])) + if (! $this->redis->hMSet($key, ['__ci_type' => $data_type, '__ci_value' => $value])) { return false; } @@ -225,8 +227,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -242,8 +244,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -296,17 +298,17 @@ public function getMetaData(string $key) $value = $this->get($key); - if ($value !== FALSE) + if ($value !== false) { $time = time(); return [ 'expire' => $time + $this->redis->ttl($key), - 'mtime' => $time, - 'data' => $value + 'mtime' => $time, + 'data' => $value, ]; } - return FALSE; + return false; } //-------------------------------------------------------------------- diff --git a/system/Cache/Handlers/WincacheHandler.php b/system/Cache/Handlers/WincacheHandler.php index 466f90ea0f91..cbeda5ff0e71 100644 --- a/system/Cache/Handlers/WincacheHandler.php +++ b/system/Cache/Handlers/WincacheHandler.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Cache\CacheInterface; class WincacheHandler implements CacheInterface @@ -78,7 +79,7 @@ public function get(string $key) $key = $this->prefix . $key; $success = false; - $data = wincache_ucache_get($key, $success); + $data = wincache_ucache_get($key, $success); // Success returned by reference from wincache_ucache_get() return ($success) ? $data : false; @@ -89,9 +90,9 @@ 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) + * @param string $key Cache item name + * @param mixed $value The data to save + * @param integer $ttl Time To Live, in seconds (default 60) * * @return mixed */ @@ -123,8 +124,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -133,7 +134,7 @@ public function increment(string $key, int $offset = 1) $key = $this->prefix . $key; $success = false; - $value = wincache_ucache_inc($key, $offset, $success); + $value = wincache_ucache_inc($key, $offset, $success); return ($success === true) ? $value : false; } @@ -143,8 +144,8 @@ 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 + * @param string $key Cache ID + * @param integer $offset Step/value to increase by * * @return mixed */ @@ -153,7 +154,7 @@ public function decrement(string $key, int $offset = 1) $key = $this->prefix . $key; $success = false; - $value = wincache_ucache_dec($key, $offset, $success); + $value = wincache_ucache_dec($key, $offset, $success); return ($success === true) ? $value : false; } @@ -200,15 +201,15 @@ public function getMetaData(string $key) if ($stored = wincache_ucache_info(false, $key)) { - $age = $stored['ucache_entries'][1]['age_seconds']; - $ttl = $stored['ucache_entries'][1]['ttl_seconds']; + $age = $stored['ucache_entries'][1]['age_seconds']; + $ttl = $stored['ucache_entries'][1]['ttl_seconds']; $hitcount = $stored['ucache_entries'][1]['hitcount']; return [ - 'expire' => $ttl - $age, - 'hitcount' => $hitcount, - 'age' => $age, - 'ttl' => $ttl, + 'expire' => $ttl - $age, + 'hitcount' => $hitcount, + 'age' => $age, + 'ttl' => $ttl, ]; } diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index 153f55e796ef..9595d3baa048 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\Request; @@ -64,72 +65,84 @@ class CodeIgniter /** * App startup time. + * * @var mixed */ protected $startTime; /** * Total app execution time + * * @var float */ protected $totalTime; /** * Main application configuration + * * @var \Config\App */ protected $config; /** * Timer instance. + * * @var Timer */ protected $benchmark; /** * Current request. + * * @var HTTP\Request|HTTP\IncomingRequest|CLIRequest */ protected $request; /** * Current response. + * * @var HTTP\ResponseInterface */ protected $response; /** * Router to use. + * * @var Router\Router */ protected $router; /** * Controller to use. + * * @var string|\Closure */ protected $controller; /** * Controller method to invoke. + * * @var string */ protected $method; /** * Output handler to use. + * * @var string */ protected $output; /** * Cache expiration time - * @var int + * + * @var integer */ protected static $cacheTTL = 0; /** * Request path to use. + * * @var string */ protected $path; @@ -137,7 +150,8 @@ class CodeIgniter /** * Should the Response instance "pretend" * to keep from setting headers/cookies/etc - * @var bool + * + * @var boolean */ protected $useSafeOutput = false; @@ -146,7 +160,7 @@ class CodeIgniter public function __construct($config) { $this->startTime = microtime(true); - $this->config = $config; + $this->config = $config; } //-------------------------------------------------------------------- @@ -183,7 +197,7 @@ public function initialize() * makes all of the pieces work together. * * @param \CodeIgniter\Router\RouteCollectionInterface $routes - * @param bool $returnResponse + * @param boolean $returnResponse * * @throws \CodeIgniter\HTTP\RedirectException * @throws \Exception @@ -204,7 +218,7 @@ public function run(RouteCollectionInterface $routes = null, bool $returnRespons // Check for a cached page. Execution will stop // if the page has been cached. $cacheConfig = new Cache(); - $response = $this->displayCache($cacheConfig); + $response = $this->displayCache($cacheConfig); if ($response instanceof ResponseInterface) { if ($returnResponse) @@ -243,7 +257,7 @@ public function run(RouteCollectionInterface $routes = null, bool $returnRespons * cookies and headers are not actually sent, allowing PHP 7.2+ to * not complain when ini_set() function is used. * - * @param bool $safe + * @param boolean $safe * * @return $this */ @@ -260,8 +274,8 @@ public function useSafeOutput(bool $safe = true) * Handles the main request logic and fires the controller. * * @param \CodeIgniter\Router\RouteCollectionInterface $routes - * @param $cacheConfig - * @param bool $returnResponse + * @param $cacheConfig + * @param boolean $returnResponse * * @return \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed * @throws \CodeIgniter\Filters\Exceptions\FilterException @@ -278,18 +292,18 @@ protected function handleRequest(RouteCollectionInterface $routes = null, $cache if (! is_null($routeFilter)) { $filters->enableFilter($routeFilter, 'before'); - $filters->enableFilter($routeFilter, 'after'); + $filters->enableFilter($routeFilter, 'after'); } $uri = $this->request instanceof CLIRequest ? $this->request->getPath() : $this->request->uri->getPath(); $possibleRedirect = $filters->run($uri, 'before'); - if($possibleRedirect instanceof RedirectResponse) + if ($possibleRedirect instanceof RedirectResponse) { return $possibleRedirect; } // If a Response instance is returned, the Response will be sent back to the client and script execution will stop - if($possibleRedirect instanceof ResponseInterface) + if ($possibleRedirect instanceof ResponseInterface) { return $possibleRedirect->send(); } @@ -297,7 +311,7 @@ protected function handleRequest(RouteCollectionInterface $routes = null, $cache $returned = $this->startController(); // Closure controller has run in startController(). - if ( ! is_callable($this->controller)) + if (! is_callable($this->controller)) { $controller = $this->createController(); @@ -456,7 +470,7 @@ protected function getRequestObject() return; } - if (is_cli() && ! (ENVIRONMENT == 'testing')) + if (is_cli() && ! (ENVIRONMENT === 'testing')) { $this->request = Services::clirequest($this->config); } @@ -478,7 +492,7 @@ protected function getResponseObject() { $this->response = Services::response($this->config); - if ( ! is_cli() || ENVIRONMENT == 'testing') + if (! is_cli() || ENVIRONMENT === 'testing') { $this->response->setProtocolVersion($this->request->getProtocolVersion()); } @@ -496,8 +510,8 @@ protected function getResponseObject() * as set the HTTP Strict Transport Security header for those browsers * that support it. * - * @param int $duration How long the Strict Transport Security - * should be enforced for this URL. + * @param integer $duration How long the Strict Transport Security + * should be enforced for this URL. */ protected function forceSecureAccess($duration = 31536000) { @@ -518,20 +532,20 @@ protected function forceSecureAccess($duration = 31536000) * * @throws \Exception * - * @return bool + * @return boolean */ public function displayCache($config) { if ($cachedResponse = cache()->get($this->generateCacheName($config))) { $cachedResponse = unserialize($cachedResponse); - if ( ! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) + if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) { - throw new \Exception("Error unserializing page cache"); + throw new \Exception('Error unserializing page cache'); } $headers = $cachedResponse['headers']; - $output = $cachedResponse['output']; + $output = $cachedResponse['output']; // Clear all default headers foreach ($this->response->getHeaders() as $key => $val) @@ -557,7 +571,7 @@ public function displayCache($config) /** * Tells the app that the final output should be cached. * - * @param int $time + * @param integer $time * * @return $this */ @@ -599,8 +613,8 @@ public function cachePage(Cache $config) public function getPerformanceStats() { return [ - 'startTime' => $this->startTime, - 'totalTime' => $this->totalTime, + 'startTime' => $this->startTime, + 'totalTime' => $this->totalTime, ]; } @@ -615,7 +629,7 @@ public function getPerformanceStats() */ protected function generateCacheName($config): string { - if (is_cli() && ! (ENVIRONMENT == 'testing')) + if (is_cli() && ! (ENVIRONMENT === 'testing')) { return md5($this->request->getPath()); } @@ -663,8 +677,8 @@ public function displayPerformanceMetrics(string $output): string * match a route against the current URI. If the route is a * "redirect route", will also handle the redirect. * - * @param RouteCollectionInterface $routes An collection interface to use in place - * of the config file. + * @param RouteCollectionInterface $routes An collection interface to use in place + * of the config file. * * @return array */ @@ -686,7 +700,7 @@ protected function tryToRouteIt(RouteCollectionInterface $routes = null) ob_start(); $this->controller = $this->router->handle($path); - $this->method = $this->router->methodName(); + $this->method = $this->router->methodName(); // If a {locale} segment was matched in the final route, // then we need to set the correct locale on our Request. @@ -708,12 +722,12 @@ protected function tryToRouteIt(RouteCollectionInterface $routes = null) */ protected function determinePath() { - if ( ! empty($this->path)) + if (! empty($this->path)) { return $this->path; } - return (is_cli() && ! (ENVIRONMENT == 'testing')) ? $this->request->getPath() : $this->request->uri->getPath(); + return (is_cli() && ! (ENVIRONMENT === 'testing')) ? $this->request->getPath() : $this->request->uri->getPath(); } //-------------------------------------------------------------------- @@ -748,7 +762,7 @@ protected function startController() $this->benchmark->start('controller_constructor'); // Is it routed to a Closure? - if (is_object($this->controller) && (get_class($this->controller) == 'Closure')) + if (is_object($this->controller) && (get_class($this->controller) === 'Closure')) { $controller = $this->controller; return $controller(...$this->router->params()); @@ -761,11 +775,11 @@ protected function startController() } // Try to autoload the class - if ( ! class_exists($this->controller, true) || $this->method[0] === '_') + if (! class_exists($this->controller, true) || $this->method[0] === '_') { throw PageNotFoundException::forControllerNotFound($this->controller, $this->method); } - else if ( ! method_exists($this->controller, '_remap') && + else if (! method_exists($this->controller, '_remap') && ! is_callable([$this->controller, $this->method], false) ) { @@ -838,7 +852,7 @@ protected function display404errors(PageNotFoundException $e) $this->benchmark->start('controller_constructor'); $this->controller = $override[0]; - $this->method = $override[1]; + $this->method = $override[1]; unset($override); @@ -893,7 +907,8 @@ protected function gatherOutput($cacheConfig = null, $returned = null) ob_end_clean(); } - if ($returned instanceof DownloadResponse) { + if ($returned instanceof DownloadResponse) + { $this->response = $returned; return; } @@ -906,7 +921,7 @@ protected function gatherOutput($cacheConfig = null, $returned = null) if ($returned instanceof Response) { $this->response = $returned; - $returned = $returned->getBody(); + $returned = $returned->getBody(); } if (is_string($returned)) @@ -962,16 +977,22 @@ public function storePreviousURL($uri) public function spoofRequestMethod() { if (is_cli()) + { return; + } // Only works with POSTED forms if ($this->request->getMethod() !== 'post') + { return; + } $method = $this->request->getPost('_method'); if (empty($method)) + { return; + } $this->request = $this->request->setMethod($method); } diff --git a/system/Commands/Database/MigrateRefresh.php b/system/Commands/Database/MigrateRefresh.php index 18ce467fbd3f..d6ab6c86458b 100644 --- a/system/Commands/Database/MigrateRefresh.php +++ b/system/Commands/Database/MigrateRefresh.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; /** @@ -88,9 +89,9 @@ class MigrateRefresh extends BaseCommand * @var array */ protected $options = [ - '-n' => 'Set migration namespace', - '-g' => 'Set database group', - '-all' => 'Set latest for all namespace, will ignore (-n) option' + '-n' => 'Set migration namespace', + '-g' => 'Set database group', + '-all' => 'Set latest for all namespace, will ignore (-n) option', ]; /** diff --git a/system/Commands/Database/Seed.php b/system/Commands/Database/Seed.php index c6b39566f14a..6e8d16f27bea 100644 --- a/system/Commands/Database/Seed.php +++ b/system/Commands/Database/Seed.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Database\Seeder; @@ -83,7 +84,7 @@ class Seed extends BaseCommand * @var array */ protected $arguments = [ - 'seeder_name' => 'The seeder name to run' + 'seeder_name' => 'The seeder name to run', ]; /** @@ -119,7 +120,8 @@ public function run(array $params = []) try { $seeder->call($seedName); - } catch (\Exception $e) + } + catch (\Exception $e) { $this->showError($e); } diff --git a/system/Commands/Help.php b/system/Commands/Help.php index 2e39bb18561c..fd774db3429d 100644 --- a/system/Commands/Help.php +++ b/system/Commands/Help.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; @@ -84,7 +85,7 @@ class Help extends BaseCommand * @var array */ protected $arguments = [ - 'command_name' => 'The command name [default: "help"]' + 'command_name' => 'The command name [default: "help"]', ]; /** @@ -110,7 +111,7 @@ public function run(array $params) } $commands = $this->commands->getCommands(); - $class = new $commands[$command]['class']($this->logger, $this->commands); + $class = new $commands[$command]['class']($this->logger, $this->commands); $class->showHelp(); } diff --git a/system/Commands/ListCommands.php b/system/Commands/ListCommands.php index d17c349cfe00..831bc54040ee 100644 --- a/system/Commands/ListCommands.php +++ b/system/Commands/ListCommands.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; @@ -96,7 +97,7 @@ class ListCommands extends BaseCommand * The length of the longest command name. * Used during display in columns. * - * @var int + * @var integer */ protected $maxFirstLength = 0; @@ -128,7 +129,7 @@ protected function describeCommands(array $commands = []) ksort($commands); // Sort into buckets by group - $sorted = []; + $sorted = []; $maxTitleLength = 0; foreach ($commands as $title => $command) @@ -172,10 +173,10 @@ protected function describeCommands(array $commands = []) /** * Pads our string out so that all titles are the same length to nicely line up descriptions. * - * @param string $item - * @param $max - * @param int $extra // How many extra spaces to add at the end - * @param int $indent + * @param string $item + * @param $max + * @param integer $extra // How many extra spaces to add at the end + * @param integer $indent * * @return array */ diff --git a/system/Commands/Server/Serve.php b/system/Commands/Server/Serve.php index e1cf2705dbf9..0cd23f7a5811 100644 --- a/system/Commands/Server/Serve.php +++ b/system/Commands/Server/Serve.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -43,21 +43,22 @@ * Launch the PHP development server * * Not testable, as it throws phpunit for a loop :-/ + * * @codeCoverageIgnore */ class Serve extends BaseCommand { protected $minPHPVersion = '7.1'; - protected $group = 'CodeIgniter'; - protected $name = 'serve'; + protected $group = 'CodeIgniter'; + protected $name = 'serve'; protected $description = 'Launchs the CodeIgniter PHP-Development Server.'; - protected $usage = 'serve'; - protected $arguments = []; - protected $options = [ - '-php' => 'The PHP Binary [default: "PHP_BINARY"]', - '-host' => 'The HTTP Host [default: "localhost"]', - '-port' => 'The HTTP Host Port [default: "8080"]', + protected $usage = 'serve'; + protected $arguments = []; + protected $options = [ + '-php' => 'The PHP Binary [default: "PHP_BINARY"]', + '-host' => 'The HTTP Host [default: "localhost"]', + '-port' => 'The HTTP Host Port [default: "8080"]', ]; public function run(array $params) @@ -65,11 +66,11 @@ public function run(array $params) // Valid PHP Version? if (phpversion() < $this->minPHPVersion) { - die("You PHP version must be {$this->minPHPVersion} or higher to run CodeIgniter. Current version: ". phpversion()); + die("You PHP version must be {$this->minPHPVersion} or higher to run CodeIgniter. Current version: " . phpversion()); } // Collect any user-supplied options and apply them - $php = CLI::getOption('php') ?? PHP_BINARY; + $php = CLI::getOption('php') ?? PHP_BINARY; $host = CLI::getOption('host') ?? 'localhost'; $port = CLI::getOption('port') ?? '8080'; diff --git a/system/Commands/Server/rewrite.php b/system/Commands/Server/rewrite.php index aedc5deef350..f3c0dd7fd3d3 100644 --- a/system/Commands/Server/rewrite.php +++ b/system/Commands/Server/rewrite.php @@ -6,8 +6,8 @@ * 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_name() === 'cli') diff --git a/system/Commands/Sessions/CreateMigration.php b/system/Commands/Sessions/CreateMigration.php index cfc83f85b85e..54a5397de439 100644 --- a/system/Commands/Sessions/CreateMigration.php +++ b/system/Commands/Sessions/CreateMigration.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\App; @@ -109,10 +110,10 @@ public function run(array $params = []) $path = APPPATH . 'Database/Migrations/' . date('YmdHis_') . 'create_' . $tableName . '_table' . '.php'; $data = [ - 'namespace' => CLI::getOption('n') ?? APP_NAMESPACE ?? 'App', - 'DBGroup' => CLI::getOption('g'), - 'tableName' => $tableName, - 'matchIP' => $config->sessionMatchIP ?? false, + 'namespace' => CLI::getOption('n') ?? APP_NAMESPACE ?? 'App', + 'DBGroup' => CLI::getOption('g'), + 'tableName' => $tableName, + 'matchIP' => $config->sessionMatchIP ?? false, ]; $template = view('\CodeIgniter\Commands\Sessions\Views\migration.tpl.php', $data, ['debug' => false]); @@ -120,7 +121,7 @@ public function run(array $params = []) // Write the file out. helper('filesystem'); - if ( ! write_file($path, $template)) + if (! write_file($path, $template)) { CLI::error(lang('Migrations.migWriteError')); return; diff --git a/system/Commands/Utilities/Namespaces.php b/system/Commands/Utilities/Namespaces.php index 8210ead6dce6..1db06b91d6a1 100644 --- a/system/Commands/Utilities/Namespaces.php +++ b/system/Commands/Utilities/Namespaces.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\Autoload; @@ -111,11 +112,15 @@ public function run(array $params) $tbody[] = [ $ns, realpath($path) ?? $path, - is_dir($path) ? "Yes" : "MISSING" + is_dir($path) ? 'Yes' : 'MISSING', ]; } - $thead = ['Namespace', 'Path', 'Found?']; + $thead = [ + 'Namespace', + 'Path', + 'Found?', + ]; CLI::table($tbody, $thead); } diff --git a/system/Commands/Utilities/Routes.php b/system/Commands/Utilities/Routes.php index 2de935ece651..517d85a85c50 100644 --- a/system/Commands/Utilities/Routes.php +++ b/system/Commands/Utilities/Routes.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\Services; @@ -102,7 +103,17 @@ class Routes extends BaseCommand public function run(array $params) { $collection = Services::routes(true); - $methods = ['get', 'head', 'post', 'put', 'delete', 'options', 'trace', 'connect', 'cli']; + $methods = [ + 'get', + 'head', + 'post', + 'put', + 'delete', + 'options', + 'trace', + 'connect', + 'cli', + ]; $tbody = []; foreach ($methods as $method) @@ -110,14 +121,20 @@ public function run(array $params) $routes = $collection->getRoutes($method); foreach ($routes as $from => $to) - $tbody[] = [ - $from, - $method, - $to - ]; + { + $tbody[] = [ + $from, + $method, + $to, + ]; + } } - $thead = ['Route', 'Method', 'Command']; + $thead = [ + 'Route', + 'Method', + 'Command', + ]; CLI::table($tbody, $thead); } diff --git a/system/Common.php b/system/Common.php index b3cf1bb3a260..fec2685e7f2b 100644 --- a/system/Common.php +++ b/system/Common.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Services; @@ -51,9 +52,8 @@ // Services Convenience Functions //-------------------------------------------------------------------- -if ( ! function_exists('cache')) +if (! function_exists('cache')) { - /** * A convenience method that provides access to the Cache * object. If no parameter is provided, will return the object, @@ -80,18 +80,17 @@ function cache(string $key = null) // Still here? Retrieve the value. return $cache->get($key); } - } //-------------------------------------------------------------------- -if ( ! function_exists('config')) +if (! function_exists('config')) { /** * More simple way of getting config instances * - * @param string $name - * @param bool $getShared + * @param string $name + * @param boolean $getShared * * @return mixed */ @@ -103,9 +102,8 @@ function config(string $name, bool $getShared = true) //-------------------------------------------------------------------- -if ( ! function_exists('view')) +if (! function_exists('view')) { - /** * Grabs the current RendererInterface-compatible class * and tells it to render the specified view. Simply provides @@ -138,21 +136,19 @@ function view(string $name, array $data = [], array $options = []) return $renderer->setData($data, 'raw') ->render($name, $options, $saveData); } - } //-------------------------------------------------------------------- -if ( ! function_exists('view_cell')) +if (! function_exists('view_cell')) { - /** * View cells are used within views to insert HTML chunks that are managed * by other classes. * * @param string $library * @param null $params - * @param int $ttl + * @param integer $ttl * @param string|null $cacheName * * @return string @@ -162,14 +158,12 @@ function view_cell(string $library, $params = null, int $ttl = 0, string $cacheN return Services::viewcell() ->render($library, $params, $ttl, $cacheName); } - } //-------------------------------------------------------------------- -if ( ! function_exists('env')) +if (! function_exists('env')) { - /** * Allows user to retrieve values from the environment * variables that have been set. Especially useful for @@ -210,14 +204,12 @@ function env(string $key, $default = null) return $value; } - } //-------------------------------------------------------------------- -if ( ! function_exists('esc')) +if (! function_exists('esc')) { - /** * Performs simple auto-escaping of data for security reasons. * Might consider making this more complex at a later date. @@ -251,17 +243,17 @@ function esc($data, $context = 'html', $encoding = null) // Provide a way to NOT escape data since // this could be called automatically by // the View library. - if (empty($context) || $context == 'raw') + if (empty($context) || $context === 'raw') { return $data; } - if ( ! in_array($context, ['html', 'js', 'css', 'url', 'attr'])) + if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'])) { throw new \InvalidArgumentException('Invalid escape context provided.'); } - if ($context == 'attr') + if ($context === 'attr') { $method = 'escapeHtmlAttr'; } @@ -270,30 +262,28 @@ function esc($data, $context = 'html', $encoding = null) $method = 'escape' . ucfirst($context); } - static $escaper; - if (! $escaper) - { - $escaper = new \Zend\Escaper\Escaper($encoding); - } + static $escaper; + if (! $escaper) + { + $escaper = new \Zend\Escaper\Escaper($encoding); + } - if ($encoding && $escaper->getEncoding() !== $encoding) - { - $escaper = new \Zend\Escaper\Escaper($encoding); - } + if ($encoding && $escaper->getEncoding() !== $encoding) + { + $escaper = new \Zend\Escaper\Escaper($encoding); + } $data = $escaper->$method($data); } return $data; } - } //-------------------------------------------------------------------- -if ( ! function_exists('session')) +if (! function_exists('session')) { - /** * A convenience method for accessing the session instance, * or an item that has been set in the session. @@ -318,14 +308,12 @@ function session($val = null) return $session; } - } //-------------------------------------------------------------------- -if ( ! function_exists('timer')) +if (! function_exists('timer')) { - /** * A convenience method for working with the timer. * If no parameter is passed, it will return the timer instance, @@ -351,14 +339,12 @@ function timer(string $name = null) return $timer->start($name); } - } //-------------------------------------------------------------------- -if ( ! function_exists('service')) +if (! function_exists('service')) { - /** * Allows cleaner access to the Services Config file. * Always returns a SHARED instance of the class, so @@ -378,14 +364,12 @@ function service(string $name, ...$params) { return Services::$name(...$params); } - } //-------------------------------------------------------------------- -if ( ! function_exists('single_service')) +if (! function_exists('single_service')) { - /** * Allow cleaner access to a Service. * Always returns a new instance of the class. @@ -402,14 +386,12 @@ function single_service(string $name, ...$params) return Services::$name(...$params); } - } //-------------------------------------------------------------------- -if ( ! function_exists('lang')) +if (! function_exists('lang')) { - /** * A convenience method to translate a string and format it * with the intl extension's MessageFormatter object. @@ -425,15 +407,12 @@ function lang(string $line, array $args = [], string $locale = null) return Services::language($locale) ->getLine($line, $args); } - } //-------------------------------------------------------------------- - -if ( ! function_exists('log_message')) +if (! function_exists('log_message')) { - /** * A convenience/compatibility method for logging events through * the Log system. @@ -459,7 +438,7 @@ function log_message(string $level, string $message, array $context = []) // When running tests, we want to always ensure that the // TestLogger is running, which provides utilities for // for asserting that logs were called in the test code. - if (ENVIRONMENT == 'testing') + if (ENVIRONMENT === 'testing') { $logger = new \Tests\Support\Log\TestLogger(new \Config\Logger()); @@ -471,33 +450,29 @@ function log_message(string $level, string $message, array $context = []) ->log($level, $message, $context); // @codeCoverageIgnoreEnd } - } //-------------------------------------------------------------------- -if ( ! function_exists('is_cli')) +if (! function_exists('is_cli')) { - /** * Is CLI? * * Test to see if a request was made from the command line. * - * @return bool + * @return boolean */ function is_cli() { return (PHP_SAPI === 'cli' || defined('STDIN')); } - } //-------------------------------------------------------------------- -if ( ! function_exists('route_to')) +if (! function_exists('route_to')) { - /** * Given a controller/method string and any params, * will attempt to build the relative URL to the @@ -507,7 +482,7 @@ function is_cli() * have a route defined in the routes Config file. * * @param string $method - * @param array ...$params + * @param array ...$params * * @return false|string */ @@ -517,24 +492,22 @@ function route_to(string $method, ...$params): string return $routes->reverseRoute($method, ...$params); } - } //-------------------------------------------------------------------- -if ( ! function_exists('remove_invisible_characters')) +if (! function_exists('remove_invisible_characters')) { - /** * Remove Invisible Characters * * This prevents sandwiching null characters * between ascii characters, like Java\0script. * - * @param string $str - * @param bool $url_encoded + * @param string $str + * @param boolean $url_encoded * - * @return string + * @return string */ function remove_invisible_characters($str, $url_encoded = true) { @@ -553,18 +526,17 @@ function remove_invisible_characters($str, $url_encoded = true) do { $str = preg_replace($non_displayables, '', $str, -1, $count); - } while ($count); + } + while ($count); return $str; } - } //-------------------------------------------------------------------- -if ( ! function_exists('helper')) +if (! function_exists('helper')) { - /** * Loads a helper file into memory. Supports namespaced helpers, * both in and out of the 'helpers' directory of a namespaced directory. @@ -580,7 +552,7 @@ function helper($filenames) { $loader = Services::locator(true); - if ( ! is_array($filenames)) + if (! is_array($filenames)) { $filenames = [$filenames]; } @@ -592,8 +564,8 @@ function helper($filenames) { // Store our system and application helper // versions so that we can control the load ordering. - $systemHelper = null; - $appHelper = null; + $systemHelper = null; + $appHelper = null; $localIncludes = []; if (strpos($filename, '_helper') === false) @@ -601,9 +573,9 @@ function helper($filenames) $filename .= '_helper'; } - $paths = $loader->search('Helpers/'.$filename); + $paths = $loader->search('Helpers/' . $filename); - if ( ! empty($paths)) + if (! empty($paths)) { foreach ($paths as $path) { @@ -647,14 +619,12 @@ function helper($filenames) } } } - } //-------------------------------------------------------------------- -if ( ! function_exists('app_timezone')) +if (! function_exists('app_timezone')) { - /** * Returns the timezone the application has been set to display * dates in. This might be different than the timezone set @@ -669,14 +639,12 @@ function app_timezone() return $config->appTimezone; } - } //-------------------------------------------------------------------- -if ( ! function_exists('csrf_token')) +if (! function_exists('csrf_token')) { - /** * Returns the CSRF token name. * Can be used in Views when building hidden inputs manually, @@ -690,14 +658,12 @@ function csrf_token() return $config->CSRFTokenName; } - } //-------------------------------------------------------------------- -if ( ! function_exists('csrf_hash')) +if (! function_exists('csrf_hash')) { - /** * Returns the current hash value for the CSRF protection. * Can be used in Views when building hidden inputs manually, @@ -711,14 +677,12 @@ function csrf_hash() return $security->getCSRFHash(); } - } //-------------------------------------------------------------------- -if ( ! function_exists('csrf_field')) +if (! function_exists('csrf_field')) { - /** * Generates a hidden input field for use within manually generated forms. * @@ -728,14 +692,12 @@ function csrf_field() { return ''; } - } //-------------------------------------------------------------------- -if ( ! function_exists('force_https')) +if (! function_exists('force_https')) { - /** * Used to force a page to be accessed in via HTTPS. * Uses a standard redirect, plus will set the HSTS header @@ -744,14 +706,14 @@ function csrf_field() * * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security * - * @param int $duration How long should the SSL header be set for? (in seconds) + * @param integer $duration How long should the SSL header be set for? (in seconds) * Defaults to 1 year. * @param RequestInterface $request * @param ResponseInterface $response * * Not testable, as it will exit! * - * @throws \CodeIgniter\HTTP\RedirectException + * @throws \CodeIgniter\HTTP\RedirectException * @codeCoverageIgnore */ function force_https(int $duration = 31536000, RequestInterface $request = null, ResponseInterface $response = null) @@ -791,7 +753,6 @@ function force_https(int $duration = 31536000, RequestInterface $request = null, $response->redirect($uri); exit(); } - } //-------------------------------------------------------------------- @@ -802,9 +763,9 @@ function force_https(int $duration = 31536000, RequestInterface $request = null, * Provides access to "old input" that was set in the session * during a redirect()->withInput(). * - * @param string $key - * @param null $default - * @param string|bool $escape + * @param string $key + * @param null $default + * @param string|boolean $escape * * @return mixed|null */ @@ -833,9 +794,8 @@ function old(string $key, $default = null, $escape = 'html') //-------------------------------------------------------------------- -if ( ! function_exists('redirect')) +if (! function_exists('redirect')) { - /** * Convenience method that works with the current global $request and * $router instances to redirect using named/reverse-routed routes @@ -849,7 +809,7 @@ function old(string $key, $default = null, $escape = 'html') * * @return \CodeIgniter\HTTP\RedirectResponse */ - function redirect(string $uri=null) + function redirect(string $uri = null) { $response = Services::redirectResponse(null, true); @@ -860,24 +820,22 @@ function redirect(string $uri=null) return $response; } - } //-------------------------------------------------------------------- -if ( ! function_exists('stringify_attributes')) +if (! function_exists('stringify_attributes')) { - /** * Stringify attributes for use in HTML tags. * * Helper function used to convert a string, array, or object * of attributes to a string. * - * @param mixed $attributes string, array, object - * @param bool $js + * @param mixed $attributes string, array, object + * @param boolean $js * - * @return string + * @return string */ function stringify_attributes($attributes, $js = false): string { @@ -902,14 +860,12 @@ function stringify_attributes($attributes, $js = false): string return rtrim($atts, ','); } - } //-------------------------------------------------------------------- -if ( ! function_exists('is_really_writable')) +if (! function_exists('is_really_writable')) { - /** * Tests for file writability * @@ -917,13 +873,13 @@ function stringify_attributes($attributes, $js = false): string * the file, based on the read-only attribute. is_writable() is also unreliable * on Unix servers if safe_mode is on. * - * @link https://bugs.php.net/bug.php?id=54709 + * @link https://bugs.php.net/bug.php?id=54709 * - * @param string $file + * @param string $file * - * @return bool + * @return boolean * - * @codeCoverageIgnore Not practical to test, as travis runs on linux + * @codeCoverageIgnore Not practical to test, as travis runs on linux */ function is_really_writable($file) { @@ -950,7 +906,7 @@ function is_really_writable($file) return true; } - elseif ( ! is_file($file) || ( $fp = @fopen($file, 'ab')) === false) + elseif (! is_file($file) || ( $fp = @fopen($file, 'ab')) === false) { return false; } @@ -959,43 +915,39 @@ function is_really_writable($file) return true; } - } //-------------------------------------------------------------------- -if ( ! function_exists('slash_item')) +if (! function_exists('slash_item')) { - //Unlike CI3, this function is placed here because //it's not a config, or part of a config. /** * Fetch a config file item with slash appended (if not empty) * - * @param string $item Config item name + * @param string $item Config item name * - * @return string|null The configuration item or NULL if + * @return string|null The configuration item or NULL if * the item doesn't exist */ function slash_item($item) { - $config = config(\Config\App::class); + $config = config(\Config\App::class); $configItem = $config->{$item}; - if ( ! isset($configItem) || empty(trim($configItem))) + if (! isset($configItem) || empty(trim($configItem))) { return $configItem; } return rtrim($configItem, '/') . '/'; } - } //-------------------------------------------------------------------- -if ( ! function_exists('function_usable')) +if (! function_exists('function_usable')) { - /** * Function usable * @@ -1014,12 +966,12 @@ function slash_item($item) * that version is yet to be released. This function will therefore * be just temporary, but would probably be kept for a few years. * - * @link http://www.hardened-php.net/suhosin/ - * @param string $function_name Function to check for - * @return bool TRUE if the function exists and is safe to call, - * FALSE otherwise. + * @link http://www.hardened-php.net/suhosin/ + * @param string $function_name Function to check for + * @return boolean TRUE if the function exists and is safe to call, + * FALSE otherwise. * - * @codeCoverageIgnore This is too exotic + * @codeCoverageIgnore This is too exotic */ function function_usable($function_name) { @@ -1027,17 +979,16 @@ function function_usable($function_name) if (function_exists($function_name)) { - if ( ! isset($_suhosin_func_blacklist)) + if (! isset($_suhosin_func_blacklist)) { $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : []; } - return ! in_array($function_name, $_suhosin_func_blacklist, TRUE); + return ! in_array($function_name, $_suhosin_func_blacklist, true); } - return FALSE; + return false; } - } //-------------------------------------------------------------------- @@ -1049,7 +1000,7 @@ function function_usable($function_name) * * @param array ...$vars * - * @codeCoverageIgnore Can't be tested ... exits + * @codeCoverageIgnore Can't be tested ... exits */ function dd(...$vars) { diff --git a/system/ComposerScripts.php b/system/ComposerScripts.php index 77629ab9d334..515d04ea3188 100644 --- a/system/ComposerScripts.php +++ b/system/ComposerScripts.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -45,7 +45,7 @@ * download * * @codeCoverageIgnore - * @package CodeIgniter + * @package CodeIgniter */ class ComposerScripts { @@ -119,15 +119,15 @@ protected static function removeDir($dir) $objects = scandir($dir); foreach ($objects as $object) { - if ($object != "." && $object != "..") + if ($object !== '.' && $object !== '..') { - if (filetype($dir."/".$object) == "dir") + if (filetype($dir . '/' . $object) === 'dir') { - static::removeDir($dir."/".$object); + static::removeDir($dir . '/' . $object); } else { - unlink($dir."/".$object); + unlink($dir . '/' . $object); } } } @@ -144,9 +144,9 @@ public static function moveEscaper() { if (class_exists('\\Zend\\Escaper\\Escaper') && file_exists(self::getClassFilePath('\\Zend\\Escaper\\Escaper'))) { - $base = static::$basePath.'ZendEscaper'; + $base = static::$basePath . 'ZendEscaper'; - foreach ([$base, $base.'/Exception'] as $path) + foreach ([$base, $base . '/Exception'] as $path) { if (! is_dir($path)) { @@ -155,17 +155,17 @@ public static function moveEscaper() } $files = [ - self::getClassFilePath('\\Zend\\Escaper\\Exception\\ExceptionInterface') => $base.'/Exception/ExceptionInterface.php', - self::getClassFilePath('\\Zend\\Escaper\\Exception\\InvalidArgumentException') => $base.'/Exception/InvalidArgumentException.php', - self::getClassFilePath('\\Zend\\Escaper\\Exception\\RuntimeException') => $base.'/Exception/RuntimeException.php', - self::getClassFilePath('\\Zend\\Escaper\\Escaper') => $base.'/Escaper.php', + self::getClassFilePath('\\Zend\\Escaper\\Exception\\ExceptionInterface') => $base . '/Exception/ExceptionInterface.php', + self::getClassFilePath('\\Zend\\Escaper\\Exception\\InvalidArgumentException') => $base . '/Exception/InvalidArgumentException.php', + self::getClassFilePath('\\Zend\\Escaper\\Exception\\RuntimeException') => $base . '/Exception/RuntimeException.php', + self::getClassFilePath('\\Zend\\Escaper\\Escaper') => $base . '/Escaper.php', ]; foreach ($files as $source => $dest) { if (! self::moveFile($source, $dest)) { - die('Error moving: '.$source); + die('Error moving: ' . $source); } } } @@ -183,7 +183,7 @@ public static function moveKint() if (file_exists($filename)) { - $base = static::$basePath.'Kint'; + $base = static::$basePath . 'Kint'; // Remove the contents of the previous Kint folder, if any. if (is_dir($base)) @@ -197,9 +197,9 @@ public static function moveKint() mkdir($base, 0755); } - if (! self::moveFile($filename, $base.'/kint.php')) + if (! self::moveFile($filename, $base . '/kint.php')) { - die('Error moving: '.$filename); + die('Error moving: ' . $filename); } } } diff --git a/system/Config/BaseConfig.php b/system/Config/BaseConfig.php index 1f43f232f2d5..a21ce4469d73 100644 --- a/system/Config/BaseConfig.php +++ b/system/Config/BaseConfig.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -70,10 +70,10 @@ public function __construct() { static::$moduleConfig = config('Modules'); - $properties = array_keys(get_object_vars($this)); - $prefix = get_class($this); - $slashAt = strrpos($prefix, '\\'); - $shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt+1 )); + $properties = array_keys(get_object_vars($this)); + $prefix = get_class($this); + $slashAt = strrpos($prefix, '\\'); + $shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt + 1 )); foreach ($properties as $property) { @@ -126,7 +126,7 @@ public function __construct() } } - if (defined('ENVIRONMENT') && ENVIRONMENT != 'testing') + if (defined('ENVIRONMENT') && ENVIRONMENT !== 'testing') { $this->registerProperties(); } @@ -145,23 +145,23 @@ public function __construct() */ protected function getEnvValue(string $property, string $prefix, string $shortPrefix) { - $shortPrefix = ltrim( $shortPrefix, '\\' ); + $shortPrefix = ltrim($shortPrefix, '\\'); switch (true) { - case array_key_exists( "{$shortPrefix}.{$property}", $_ENV ): + case array_key_exists("{$shortPrefix}.{$property}", $_ENV): return $_ENV["{$shortPrefix}.{$property}"]; break; - case array_key_exists( "{$shortPrefix}.{$property}", $_SERVER ): + case array_key_exists("{$shortPrefix}.{$property}", $_SERVER): return $_SERVER["{$shortPrefix}.{$property}"]; break; - case array_key_exists( "{$prefix}.{$property}", $_ENV ): + case array_key_exists("{$prefix}.{$property}", $_ENV): return $_ENV["{$prefix}.{$property}"]; break; - case array_key_exists( "{$prefix}.{$property}", $_SERVER ): + case array_key_exists("{$prefix}.{$property}", $_SERVER): return $_SERVER["{$prefix}.{$property}"]; break; default: - $value = getenv( $property ); + $value = getenv($property); return $value === false ? null : $value; } } @@ -181,7 +181,7 @@ protected function registerProperties() if (! static::$didDiscovery) { - $locator = \Config\Services::locator(); + $locator = \Config\Services::locator(); static::$registrars = $locator->search('Config/Registrar.php'); } @@ -191,14 +191,14 @@ protected function registerProperties() foreach (static::$registrars as $callable) { // ignore non-applicable registrars - if ( ! method_exists($callable, $shortName)) + if (! method_exists($callable, $shortName)) { continue; } $properties = $callable::$shortName(); - if ( ! is_array($properties)) + if (! is_array($properties)) { throw new \RuntimeException('Registrars must return an array of properties and their values.'); } diff --git a/system/Config/BaseService.php b/system/Config/BaseService.php index 88ff74d29c5c..acd87a456098 100644 --- a/system/Config/BaseService.php +++ b/system/Config/BaseService.php @@ -27,16 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ - /** * Services Configuration file. * @@ -75,7 +74,7 @@ class BaseService /** * Have we already discovered other Services? * - * @var bool + * @var boolean */ static protected $discovered = false; @@ -124,7 +123,7 @@ protected static function getSharedInstance(string $key, ...$params) * within namespaced folders, as well as convenience methods for * loading 'helpers', and 'libraries'. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Autoloader\FileLocator */ @@ -179,7 +178,7 @@ public static function reset() * Inject mock object for testing. * * @param string $name - * @param $mock + * @param $mock */ public static function injectMock(string $name, $mock) { diff --git a/system/Config/Config.php b/system/Config/Config.php index 533123c01b2e..12167d0d0113 100644 --- a/system/Config/Config.php +++ b/system/Config/Config.php @@ -87,8 +87,8 @@ public static function get(string $name, bool $getShared = true) /** * Helper method for injecting mock instances while testing. * - * @param string $class - * @param $instance + * @param string $class + * @param $instance */ public static function injectMock(string $class, $instance) { diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index 950b2838e53e..74b7a49e6a32 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -69,19 +69,19 @@ public function __construct(string $path, string $file = '.env') * so that we end up with all settings in the PHP environment vars * (i.e. getenv(), $_ENV, and $_SERVER) * - * @return bool + * @return boolean */ public function load() { // We don't want to enforce the presence of a .env file, // they should be optional. - if ( ! is_file($this->path)) + if (! is_file($this->path)) { return false; } // Ensure file is readable - if ( ! is_readable($this->path)) + if (! is_readable($this->path)) { throw new \InvalidArgumentException("The .env file is not readable: {$this->path}"); } @@ -121,7 +121,7 @@ protected function setVariable(string $name, string $value = '') { list($name, $value) = $this->normaliseVariable($name, $value); - if ( ! getenv($name, true)) + if (! getenv($name, true)) { putenv("$name=$value"); } @@ -154,7 +154,7 @@ public function normaliseVariable(string $name, string $value = ''): array list($name, $value) = explode('=', $name, 2); } - $name = trim($name); + $name = trim($name); $value = trim($value); // Sanitize the name @@ -165,7 +165,10 @@ public function normaliseVariable(string $name, string $value = ''): array $value = $this->resolveNestedVariables($value); - return [$name, $value]; + return [ + $name, + $value, + ]; } //-------------------------------------------------------------------- @@ -183,7 +186,7 @@ public function normaliseVariable(string $name, string $value = ''): array */ protected function sanitizeValue(string $value): string { - if ( ! $value) + if (! $value) { return $value; } @@ -192,7 +195,7 @@ protected function sanitizeValue(string $value): string if (strpbrk($value[0], '"\'') !== false) { // value starts with a quote - $quote = $value[0]; + $quote = $value[0]; $regexPattern = sprintf( '/^ %1$s # match a quote at the start of the value @@ -207,9 +210,9 @@ protected function sanitizeValue(string $value): string .*$ # 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); + $value = preg_replace($regexPattern, '$1', $value); + $value = str_replace("\\$quote", $quote, $value); + $value = str_replace('\\\\', '\\', $value); } else { @@ -249,16 +252,18 @@ protected function resolveNestedVariables(string $value): string $loader = $this; $value = preg_replace_callback( - '/\${([a-zA-Z0-9_]+)}/', function ($matchedPatterns) use ($loader) { - $nestedVariable = $loader->getVariable($matchedPatterns[1]); - - if (is_null($nestedVariable)) - { - return $matchedPatterns[0]; - } - - return $nestedVariable; - }, $value + '/\${([a-zA-Z0-9_]+)}/', + function ($matchedPatterns) use ($loader) { + $nestedVariable = $loader->getVariable($matchedPatterns[1]); + + if (is_null($nestedVariable)) + { + return $matchedPatterns[0]; + } + + return $nestedVariable; + }, + $value ); } diff --git a/system/Config/ForeignCharacters.php b/system/Config/ForeignCharacters.php index e3fc5a599a8c..ace76ef8fd3f 100644 --- a/system/Config/ForeignCharacters.php +++ b/system/Config/ForeignCharacters.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + class ForeignCharacters { /* @@ -47,95 +48,95 @@ class ForeignCharacters */ 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' + '/Ƥ|Ʀ|Ē½/' => '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', ]; } diff --git a/system/Config/Routes.php b/system/Config/Routes.php index 8834db5a9225..2640fa1465fc 100644 --- a/system/Config/Routes.php +++ b/system/Config/Routes.php @@ -26,14 +26,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + /** * System URI Routing * @@ -50,4 +51,3 @@ // CLI Catchall - uses a _remap to $routes->cli('ci(:any)', '\CodeIgniter\CLI\CommandRunner::index/$1'); - diff --git a/system/Config/Services.php b/system/Config/Services.php index 163f92506b91..78b63285b606 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\App; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\MigrationRunner; @@ -63,9 +64,9 @@ class Services extends BaseService * The Autoloader class is the central class that handles our * spl_autoload_register method, and helper methods. * - * @param bool $getShared + * @param boolean $getShared * - * @return \CodeIgniter\Autoloader\Autoloader + * @return \CodeIgniter\Autoloader\Autoloader */ public static function autoloader(bool $getShared = true) { @@ -84,7 +85,7 @@ public static function autoloader(bool $getShared = true) * complex data for later. * * @param \Config\Cache $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Cache\CacheInterface */ @@ -110,7 +111,7 @@ public static function cache(\Config\Cache $config = null, bool $getShared = tru * a command line request. * * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\CLIRequest */ @@ -138,11 +139,12 @@ public static function clirequest(\Config\App $config = null, bool $getShared = * @param array $options * @param \CodeIgniter\HTTP\ResponseInterface $response * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\CURLRequest */ - public static function curlrequest(array $options = [], $response = null, \Config\App $config = null, bool $getShared = true) { + public static function curlrequest(array $options = [], $response = null, \Config\App $config = null, bool $getShared = true) + { if ($getShared === true) { return self::getSharedInstance('curlrequest', $options, $response, $config); @@ -171,8 +173,8 @@ public static function curlrequest(array $options = [], $response = null, \Confi /** * The Email class allows you to send email via mail, sendmail, SMTP. * - * @param null $config - * @param bool $getShared + * @param null $config + * @param boolean $getShared * * @return \CodeIgniter\Email\Email|mixed */ @@ -206,7 +208,7 @@ public static function email($config = null, bool $getShared = true) * @param \Config\Exceptions $config * @param \CodeIgniter\HTTP\IncomingRequest $request * @param \CodeIgniter\HTTP\Response $response - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Debug\Exceptions */ @@ -215,7 +217,8 @@ public static function exceptions( \CodeIgniter\HTTP\IncomingRequest $request = null, \CodeIgniter\HTTP\Response $response = null, $getShared = true - ) { + ) + { if ($getShared) { return self::getSharedInstance('exceptions', $config, $request, $response); @@ -247,8 +250,8 @@ public static function exceptions( * 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. * - * @param mixed $config - * @param bool $getShared + * @param mixed $config + * @param boolean $getShared * * @return \CodeIgniter\Filters\Filters */ @@ -273,9 +276,9 @@ public static function filters($config = null, bool $getShared = true) * Acts as a factory for ImageHandler classes and returns an instance * of the handler. Used like Services::image()->withFile($path)->rotate(90)->save(); * - * @param string $handler - * @param mixed $config - * @param bool $getShared + * @param string $handler + * @param mixed $config + * @param boolean $getShared * * @return \CodeIgniter\Images\Handlers\BaseHandler */ @@ -305,7 +308,7 @@ public static function image(string $handler = null, $config = null, bool $getSh * and timing the results and memory usage. Used when debugging and * optimizing applications. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Debug\Iterator */ @@ -324,8 +327,8 @@ public static function iterator($getShared = true) /** * Responsible for loading the language string translations. * - * @param string $locale - * @param bool $getShared + * @param string $locale + * @param boolean $getShared * * @return \CodeIgniter\Language\Language */ @@ -334,13 +337,13 @@ public static function language(string $locale = null, bool $getShared = true) if ($getShared) { return self::getSharedInstance('language', $locale) - ->setLocale($locale); + ->setLocale($locale); } $locale = ! empty($locale) ? $locale : self::request() - ->getLocale(); + ->getLocale(); return new \CodeIgniter\Language\Language($locale); } @@ -351,7 +354,7 @@ public static function language(string $locale = null, bool $getShared = true) * The Logger class is a PSR-3 compatible Logging class that supports * multiple handlers that process the actual logging. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Log\Logger */ @@ -370,7 +373,7 @@ public static function logger($getShared = true) /** * @param \CodeIgniter\Config\BaseConfig $config * @param \CodeIgniter\Database\ConnectionInterface $db - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Database\MigrationRunner */ @@ -394,7 +397,7 @@ public static function migrations(BaseConfig $config = null, ConnectionInterface * and more. * * @param \CodeIgniter\HTTP\RequestInterface $request - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\Negotiate */ @@ -415,11 +418,10 @@ public static function negotiator(\CodeIgniter\HTTP\RequestInterface $request = //-------------------------------------------------------------------- - /** * @param mixed $config * @param \CodeIgniter\View\RendererInterface $view - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Pager\Pager */ @@ -448,13 +450,13 @@ public static function pager($config = null, RendererInterface $view = null, boo /** * The Parser is a simple template parser. * - * @param string $viewPath - * @param mixed $config - * @param bool $getShared + * @param string $viewPath + * @param mixed $config + * @param boolean $getShared * * @return \CodeIgniter\View\Parser */ - public static function parser($viewPath = APPPATH.'Views/', $config = null, bool $getShared = true) + public static function parser($viewPath = APPPATH . 'Views/', $config = null, bool $getShared = true) { if ($getShared) { @@ -476,9 +478,9 @@ public static function parser($viewPath = APPPATH.'Views/', $config = null, bool * 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. * - * @param string $viewPath - * @param mixed $config - * @param bool $getShared + * @param string $viewPath + * @param mixed $config + * @param boolean $getShared * * @return \CodeIgniter\View\View */ @@ -510,7 +512,7 @@ public static function renderer($viewPath = null, $config = null, bool $getShare * The Request class models an HTTP request. * * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\IncomingRequest */ @@ -540,7 +542,7 @@ public static function request(\Config\App $config = null, bool $getShared = tru * The Response class models an HTTP response. * * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\Response */ @@ -565,7 +567,7 @@ public static function response(\Config\App $config = null, bool $getShared = tr * The Redirect class provides nice way of working with redirects. * * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\HTTP\Response */ @@ -583,7 +585,7 @@ public static function redirectResponse(\Config\App $config = null, bool $getSha $response = new \CodeIgniter\HTTP\RedirectResponse($config); $response->setProtocolVersion(self::request() - ->getProtocolVersion()); + ->getProtocolVersion()); return $response; } @@ -594,7 +596,7 @@ public static function redirectResponse(\Config\App $config = null, bool $getSha * The Routes service is a class that allows for easily building * a collection of routes. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Router\RouteCollection */ @@ -615,7 +617,7 @@ public static function routes($getShared = true) * the correct Controller and Method to execute. * * @param \CodeIgniter\Router\RouteCollectionInterface $routes - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Router\Router */ @@ -641,7 +643,7 @@ public static function router(\CodeIgniter\Router\RouteCollectionInterface $rout * secure, most notably the CSRF protection tools. * * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Security\Security */ @@ -664,7 +666,7 @@ public static function security(\Config\App $config = null, bool $getShared = tr /** * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Session\Session */ @@ -689,7 +691,7 @@ public static function session(\Config\App $config = null, bool $getShared = tru $session = new \CodeIgniter\Session\Session($driver, $config); $session->setLogger($logger); - if (session_status() == PHP_SESSION_NONE) + if (session_status() === PHP_SESSION_NONE) { $session->start(); } @@ -703,7 +705,7 @@ public static function session(\Config\App $config = null, bool $getShared = tru * The Throttler class provides a simple method for implementing * rate limiting in your applications. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Throttle\Throttler */ @@ -723,7 +725,7 @@ public static function throttler($getShared = true) * The Timer class provides a simple way to Benchmark portions of your * application. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Debug\Timer */ @@ -741,7 +743,7 @@ public static function timer($getShared = true) /** * @param \Config\App $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Debug\Toolbar */ @@ -765,8 +767,8 @@ public static function toolbar(\Config\App $config = null, bool $getShared = tru /** * The URI class provides a way to model and manipulate URIs. * - * @param string $uri - * @param bool $getShared + * @param string $uri + * @param boolean $getShared * * @return \CodeIgniter\HTTP\URI */ @@ -786,7 +788,7 @@ public static function uri($uri = null, bool $getShared = true) * The Validation class provides tools for validating input data. * * @param \Config\Validation $config - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Validation\Validation */ @@ -811,7 +813,7 @@ public static function validation(\Config\Validation $config = null, bool $getSh * View cells are intended to let you insert HTML into view * that has been generated by any callable in the system. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\View\Cell */ @@ -830,7 +832,7 @@ public static function viewcell($getShared = true) /** * The Typography class provides a way to format text in semantically relevant ways. * - * @param bool $getShared + * @param boolean $getShared * * @return \CodeIgniter\Typography\Typography */ diff --git a/system/Config/View.php b/system/Config/View.php index 17969643aa47..142bb02ab3c0 100644 --- a/system/Config/View.php +++ b/system/Config/View.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + class View extends BaseConfig { diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index 6e3df7955bcd..0033c41115f0 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use \CodeIgniter\Database\Exceptions\DatabaseException; /** @@ -45,7 +46,7 @@ * certain methods to make them work. * * @package CodeIgniter\Database - * @mixin \CodeIgniter\Model + * @mixin \CodeIgniter\Model */ class BaseBuilder { @@ -53,105 +54,105 @@ class BaseBuilder /** * Reset DELETE data flag * - * @var bool + * @var boolean */ protected $resetDeleteData = false; /** * QB SELECT data * - * @var array + * @var array */ protected $QBSelect = []; /** * QB DISTINCT flag * - * @var bool + * @var boolean */ protected $QBDistinct = false; /** * QB FROM data * - * @var array + * @var array */ protected $QBFrom = []; /** * QB JOIN data * - * @var array + * @var array */ protected $QBJoin = []; /** * QB WHERE data * - * @var array + * @var array */ protected $QBWhere = []; /** * QB GROUP BY data * - * @var array + * @var array */ protected $QBGroupBy = []; /** * QB HAVING data * - * @var array + * @var array */ protected $QBHaving = []; /** * QB keys * - * @var array + * @var array */ protected $QBKeys = []; /** * QB LIMIT data * - * @var int + * @var integer */ protected $QBLimit = false; /** * QB OFFSET data * - * @var int + * @var integer */ protected $QBOffset = false; /** * QB ORDER BY data * - * @var array + * @var array */ public $QBOrderBy = []; /** * QB data sets * - * @var array + * @var array */ protected $QBSet = []; /** * QB WHERE group started flag * - * @var bool + * @var boolean */ protected $QBWhereGroupStarted = false; /** * QB WHERE group count * - * @var int + * @var integer */ protected $QBWhereGroupCount = 0; @@ -165,17 +166,20 @@ class BaseBuilder /** * ORDER BY random keyword * - * @var array + * @var array */ - protected $randomKeyword = ['RAND()', 'RAND(%d)']; + protected $randomKeyword = [ + 'RAND()', + 'RAND(%d)', + ]; /** * COUNT string * - * @used-by CI_DB_driver::count_all() - * @used-by BaseBuilder::count_all_results() + * @used-by CI_DB_driver::count_all() + * @used-by BaseBuilder::count_all_results() * - * @var string + * @var string */ protected $countString = 'SELECT COUNT(*) AS '; @@ -192,14 +196,15 @@ class BaseBuilder * Some databases, like SQLite, do not by default * allow limiting of delete clauses. * - * @var bool + * @var boolean */ protected $canLimitDeletes = true; /** * Some databases do not by default * allow limit update queries with WHERE. - * @var bool + * + * @var boolean */ protected $canLimitWhereUpdates = true; @@ -208,9 +213,9 @@ class BaseBuilder /** * Constructor * - * @param string|array $tableName - * @param \CodeIgniter\Database\ConnectionInterface $db - * @param array $options + * @param string|array $tableName + * @param \CodeIgniter\Database\ConnectionInterface $db + * @param array $options * @throws DatabaseException */ public function __construct($tableName, ConnectionInterface &$db, array $options = null) @@ -253,10 +258,10 @@ public function getBinds(): array * * Generates the SELECT portion of the query * - * @param string|array $select - * @param mixed $escape + * @param string|array $select + * @param mixed $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function select($select = '*', $escape = null) { @@ -283,7 +288,7 @@ public function select($select = '*', $escape = null) * This prevents NULL being escaped * @see https://github.com/bcit-ci/CodeIgniter4/issues/1169 */ - if ( strtoupper(mb_substr(trim($val), 0, 4)) == 'NULL') + if (strtoupper(mb_substr(trim($val), 0, 4)) === 'NULL') { $escape = false; } @@ -302,10 +307,10 @@ public function select($select = '*', $escape = null) * * Generates a SELECT MAX(field) portion of a query * - * @param string $select The field - * @param string $alias An alias + * @param string $select The field + * @param string $alias An alias * - * @return BaseBuilder + * @return BaseBuilder */ public function selectMax($select = '', $alias = '') { @@ -319,10 +324,10 @@ public function selectMax($select = '', $alias = '') * * Generates a SELECT MIN(field) portion of a query * - * @param string $select The field - * @param string $alias An alias + * @param string $select The field + * @param string $alias An alias * - * @return BaseBuilder + * @return BaseBuilder */ public function selectMin($select = '', $alias = '') { @@ -336,10 +341,10 @@ public function selectMin($select = '', $alias = '') * * Generates a SELECT AVG(field) portion of a query * - * @param string $select The field - * @param string $alias An alias + * @param string $select The field + * @param string $alias An alias * - * @return BaseBuilder + * @return BaseBuilder */ public function selectAvg($select = '', $alias = '') { @@ -353,10 +358,10 @@ public function selectAvg($select = '', $alias = '') * * Generates a SELECT SUM(field) portion of a query * - * @param string $select The field - * @param string $alias An alias + * @param string $select The field + * @param string $alias An alias * - * @return BaseBuilder + * @return BaseBuilder */ public function selectSum($select = '', $alias = '') { @@ -368,28 +373,28 @@ public function selectSum($select = '', $alias = '') /** * SELECT [MAX|MIN|AVG|SUM]() * - * @used-by selectMax() - * @used-by selectMin() - * @used-by selectAvg() - * @used-by selectSum() + * @used-by selectMax() + * @used-by selectMin() + * @used-by selectAvg() + * @used-by selectSum() * - * @param string $select Field name - * @param string $alias - * @param string $type + * @param string $select Field name + * @param string $alias + * @param string $type * - * @return BaseBuilder + * @return BaseBuilder * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ protected function maxMinAvgSum($select = '', $alias = '', $type = 'MAX') { - if ( ! is_string($select) || $select === '') + if (! is_string($select) || $select === '') { throw new DatabaseException('The query you submitted is not valid.'); } $type = strtoupper($type); - if ( ! in_array($type, ['MAX', 'MIN', 'AVG', 'SUM'])) + if (! in_array($type, ['MAX', 'MIN', 'AVG', 'SUM'])) { throw new DatabaseException('Invalid function type: ' . $type); } @@ -401,7 +406,7 @@ protected function maxMinAvgSum($select = '', $alias = '', $type = 'MAX') $sql = $type . '(' . $this->db->protectIdentifiers(trim($select)) . ') AS ' . $this->db->escapeIdentifiers(trim($alias)); - $this->QBSelect[] = $sql; + $this->QBSelect[] = $sql; $this->QBNoEscape[] = null; return $this; @@ -412,9 +417,9 @@ protected function maxMinAvgSum($select = '', $alias = '', $type = 'MAX') /** * Determines the alias name based on the table * - * @param string $item + * @param string $item * - * @return string + * @return string */ protected function createAliasFromTable($item) { @@ -435,9 +440,9 @@ protected function createAliasFromTable($item) * * Sets a flag which tells the query string compiler to add DISTINCT * - * @param bool $val + * @param boolean $val * - * @return BaseBuilder + * @return BaseBuilder */ public function distinct($val = true) { @@ -453,10 +458,10 @@ public function distinct($val = true) * * Generates the FROM portion of the query * - * @param mixed $from can be a string or array - * @param bool $overwrite Should we remove the first table existing? + * @param mixed $from can be a string or array + * @param boolean $overwrite Should we remove the first table existing? * - * @return BaseBuilder + * @return BaseBuilder */ public function from($from, $overwrite = false) { @@ -500,12 +505,12 @@ public function from($from, $overwrite = false) * * Generates the JOIN portion of the query * - * @param string $table - * @param string $cond The join condition - * @param string $type The type of join - * @param string $escape Whether not to try to escape identifiers + * @param string $table + * @param string $cond The join condition + * @param string $type The type of join + * @param string $escape Whether not to try to escape identifiers * - * @return BaseBuilder + * @return BaseBuilder */ public function join($table, $cond, $type = '', $escape = null) { @@ -513,7 +518,7 @@ public function join($table, $cond, $type = '', $escape = null) { $type = strtoupper(trim($type)); - if ( ! in_array($type, ['LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'], true)) + if (! in_array($type, ['LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'], true)) { $type = ''; } @@ -529,7 +534,7 @@ public function join($table, $cond, $type = '', $escape = null) is_bool($escape) || $escape = $this->db->protectIdentifiers; - if ( ! $this->hasOperator($cond)) + if (! $this->hasOperator($cond)) { $cond = ' USING (' . ($escape ? $this->db->escapeIdentifiers($cond) : $cond) . ')'; } @@ -543,29 +548,29 @@ public function join($table, $cond, $type = '', $escape = null) if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE)) { $conditions = []; - $joints = $joints[0]; + $joints = $joints[0]; array_unshift($joints, ['', 0]); - for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i -- ) + for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i --) { $joints[$i][1] += strlen($joints[$i][0]); // offset $conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]); - $pos = $joints[$i][1] - strlen($joints[$i][0]); - $joints[$i] = $joints[$i][0]; + $pos = $joints[$i][1] - strlen($joints[$i][0]); + $joints[$i] = $joints[$i][0]; } } else { $conditions = [$cond]; - $joints = ['']; + $joints = ['']; } $cond = ' ON '; - for ($i = 0, $c = count($conditions); $i < $c; $i ++ ) + for ($i = 0, $c = count($conditions); $i < $c; $i ++) { $operator = $this->getOperator($conditions[$i]); - $cond .= $joints[$i]; - $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)" . preg_quote($operator) . "(.*)/i", $conditions[$i], $match) ? $match[1] . $this->db->protectIdentifiers($match[2]) . $operator . $this->db->protectIdentifiers($match[3]) : $conditions[$i]; + $cond .= $joints[$i]; + $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)" . preg_quote($operator) . '(.*)/i', $conditions[$i], $match) ? $match[1] . $this->db->protectIdentifiers($match[2]) . $operator . $this->db->protectIdentifiers($match[3]) : $conditions[$i]; } } @@ -589,11 +594,11 @@ public function join($table, $cond, $type = '', $escape = null) * Generates the WHERE portion of the query. * Separates multiple calls with 'AND'. * - * @param mixed $key - * @param mixed $value - * @param bool $escape + * @param mixed $key + * @param mixed $value + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function where($key, $value = null, $escape = null) { @@ -608,11 +613,11 @@ public function where($key, $value = null, $escape = null) * Generates the WHERE portion of the query. * Separates multiple calls with 'OR'. * - * @param mixed $key - * @param mixed $value - * @param bool $escape + * @param mixed $key + * @param mixed $value + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orWhere($key, $value = null, $escape = null) { @@ -624,22 +629,22 @@ public function orWhere($key, $value = null, $escape = null) /** * WHERE, HAVING * - * @used-by where() - * @used-by orWhere() - * @used-by having() - * @used-by orHaving() + * @used-by where() + * @used-by orWhere() + * @used-by having() + * @used-by orHaving() * - * @param string $qb_key 'QBWhere' or 'QBHaving' - * @param mixed $key - * @param mixed $value - * @param string $type - * @param bool $escape + * @param string $qb_key 'QBWhere' or 'QBHaving' + * @param mixed $key + * @param mixed $value + * @param string $type + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ protected function whereHaving($qb_key, $key, $value = null, $type = 'AND ', $escape = null) { - if ( ! is_array($key)) + if (! is_array($key)) { $key = [$key => $value]; } @@ -654,7 +659,7 @@ protected function whereHaving($qb_key, $key, $value = null, $type = 'AND ', $es if ($v !== null) { $op = $this->getOperator($k); - $k = trim(str_replace($op, '', $k)); + $k = trim(str_replace($op, '', $k)); $bind = $this->setBind($k, $v); @@ -667,7 +672,7 @@ protected function whereHaving($qb_key, $key, $value = null, $type = 'AND ', $es $k .= $op; } } - elseif ( ! $this->hasOperator($k)) + elseif (! $this->hasOperator($k)) { // value appears not to have been set, assign the test to IS NULL $k .= ' IS NULL'; @@ -679,7 +684,10 @@ protected function whereHaving($qb_key, $key, $value = null, $type = 'AND ', $es $v = ! is_null($v) ? " :$bind:" : $v; - $this->{$qb_key}[] = ['condition' => $prefix . $k . $v, 'escape' => $escape]; + $this->{$qb_key}[] = [ + 'condition' => $prefix . $k . $v, + 'escape' => $escape, + ]; } return $this; @@ -693,11 +701,11 @@ protected function whereHaving($qb_key, $key, $value = null, $type = 'AND ', $es * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * - * @param string $key The field to search - * @param array $values The values searched on - * @param bool $escape + * @param string $key The field to search + * @param array $values The values searched on + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function whereIn($key = null, $values = null, $escape = null) { @@ -712,11 +720,11 @@ public function whereIn($key = null, $values = null, $escape = null) * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * - * @param string $key The field to search - * @param array $values The values searched on - * @param bool $escape + * @param string $key The field to search + * @param array $values The values searched on + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orWhereIn($key = null, $values = null, $escape = null) { @@ -731,11 +739,11 @@ public function orWhereIn($key = null, $values = null, $escape = null) * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * - * @param string $key The field to search - * @param array $values The values searched on - * @param bool $escape + * @param string $key The field to search + * @param array $values The values searched on + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function whereNotIn($key = null, $values = null, $escape = null) { @@ -750,11 +758,11 @@ public function whereNotIn($key = null, $values = null, $escape = null) * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * - * @param string $key The field to search - * @param array $values The values searched on - * @param bool $escape + * @param string $key The field to search + * @param array $values The values searched on + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orWhereNotIn($key = null, $values = null, $escape = null) { @@ -766,18 +774,18 @@ public function orWhereNotIn($key = null, $values = null, $escape = null) /** * Internal WHERE IN * - * @used-by WhereIn() - * @used-by orWhereIn() - * @used-by whereNotIn() - * @used-by orWhereNotIn() + * @used-by WhereIn() + * @used-by orWhereIn() + * @used-by whereNotIn() + * @used-by orWhereNotIn() * - * @param string $key The field to search - * @param array $values The values searched on - * @param bool $not If the statement would be IN or NOT IN - * @param string $type - * @param bool $escape + * @param string $key The field to search + * @param array $values The values searched on + * @param boolean $not If the statement would be IN or NOT IN + * @param string $type + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ protected function _whereIn($key = null, $values = null, $not = false, $type = 'AND ', $escape = null) { @@ -786,7 +794,7 @@ protected function _whereIn($key = null, $values = null, $not = false, $type = ' return $this; } - if ( ! is_array($values)) + if (! is_array($values)) { $values = [$values]; } @@ -802,14 +810,14 @@ protected function _whereIn($key = null, $values = null, $not = false, $type = ' $not = ($not) ? ' NOT' : ''; - $where_in = array_values($values); + $where_in = array_values($values); $this->binds[$ok] = $where_in; $prefix = empty($this->QBWhere) ? $this->groupGetType('') : $this->groupGetType($type); $where_in = [ - 'condition' => $prefix . $key . $not . " IN :{$ok}:", - 'escape' => false, + 'condition' => $prefix . $key . $not . " IN :{$ok}:", + 'escape' => false, ]; $this->QBWhere[] = $where_in; @@ -825,13 +833,13 @@ protected function _whereIn($key = null, $values = null, $not = false, $type = ' * Generates a %LIKE% portion of the query. * Separates multiple calls with 'AND'. * - * @param mixed $field - * @param string $match - * @param string $side - * @param bool $escape - * @param bool $insensitiveSearch IF true, will force a case-insensitive search + * @param mixed $field + * @param string $match + * @param string $side + * @param boolean $escape + * @param boolean $insensitiveSearch IF true, will force a case-insensitive search * - * @return BaseBuilder + * @return BaseBuilder */ public function like($field, $match = '', $side = 'both', $escape = null, $insensitiveSearch = false) { @@ -846,13 +854,13 @@ public function like($field, $match = '', $side = 'both', $escape = null, $insen * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'AND'. * - * @param mixed $field - * @param string $match - * @param string $side - * @param bool $escape - * @param bool $insensitiveSearch IF true, will force a case-insensitive search + * @param mixed $field + * @param string $match + * @param string $side + * @param boolean $escape + * @param boolean $insensitiveSearch IF true, will force a case-insensitive search * - * @return BaseBuilder + * @return BaseBuilder */ public function notLike($field, $match = '', $side = 'both', $escape = null, $insensitiveSearch = false) { @@ -867,13 +875,13 @@ public function notLike($field, $match = '', $side = 'both', $escape = null, $in * Generates a %LIKE% portion of the query. * Separates multiple calls with 'OR'. * - * @param mixed $field - * @param string $match - * @param string $side - * @param bool $escape - * @param bool $insensitiveSearch IF true, will force a case-insensitive search + * @param mixed $field + * @param string $match + * @param string $side + * @param boolean $escape + * @param boolean $insensitiveSearch IF true, will force a case-insensitive search * - * @return BaseBuilder + * @return BaseBuilder */ public function orLike($field, $match = '', $side = 'both', $escape = null, $insensitiveSearch = false) { @@ -888,13 +896,13 @@ public function orLike($field, $match = '', $side = 'both', $escape = null, $ins * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'OR'. * - * @param mixed $field - * @param string $match - * @param string $side - * @param bool $escape - * @param bool $insensitiveSearch IF true, will force a case-insensitive search + * @param mixed $field + * @param string $match + * @param string $side + * @param boolean $escape + * @param boolean $insensitiveSearch IF true, will force a case-insensitive search * - * @return BaseBuilder + * @return BaseBuilder */ public function orNotLike($field, $match = '', $side = 'both', $escape = null, $insensitiveSearch = false) { @@ -906,24 +914,24 @@ public function orNotLike($field, $match = '', $side = 'both', $escape = null, $ /** * Internal LIKE * - * @used-by like() - * @used-by orLike() - * @used-by notLike() - * @used-by orNotLike() + * @used-by like() + * @used-by orLike() + * @used-by notLike() + * @used-by orNotLike() * - * @param mixed $field - * @param string $match - * @param string $type - * @param string $side - * @param string $not - * @param bool $escape - * @param bool $insensitiveSearch IF true, will force a case-insensitive search + * @param mixed $field + * @param string $match + * @param string $type + * @param string $side + * @param string $not + * @param boolean $escape + * @param boolean $insensitiveSearch IF true, will force a case-insensitive search * - * @return BaseBuilder + * @return BaseBuilder */ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = null, $insensitiveSearch = false) { - if ( ! is_array($field)) + if (! is_array($field)) { $field = [$field => $match]; } @@ -967,7 +975,10 @@ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $n $like_statement .= sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar); } - $this->QBWhere[] = ['condition' => $like_statement, 'escape' => $escape]; + $this->QBWhere[] = [ + 'condition' => $like_statement, + 'escape' => $escape, + ]; } return $this; @@ -982,7 +993,7 @@ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $n * @param string $column * @param string|null $not * @param string $bind - * @param bool $insensitiveSearch + * @param boolean $insensitiveSearch * * @return string $like_statement */ @@ -1004,20 +1015,20 @@ public function _like_statement(string $prefix = null, string $column, string $n /** * Starts a query group. * - * @param string $not (Internal use only) - * @param string $type (Internal use only) + * @param string $not (Internal use only) + * @param string $type (Internal use only) * - * @return BaseBuilder + * @return BaseBuilder */ public function groupStart($not = '', $type = 'AND ') { $type = $this->groupGetType($type); $this->QBWhereGroupStarted = true; - $prefix = empty($this->QBWhere) ? '' : $type; - $where = [ - 'condition' => $prefix . $not . str_repeat(' ', ++ $this->QBWhereGroupCount) . ' (', - 'escape' => false, + $prefix = empty($this->QBWhere) ? '' : $type; + $where = [ + 'condition' => $prefix . $not . str_repeat(' ', ++ $this->QBWhereGroupCount) . ' (', + 'escape' => false, ]; $this->QBWhere[] = $where; @@ -1030,7 +1041,7 @@ public function groupStart($not = '', $type = 'AND ') /** * Starts a query group, but ORs the group * - * @return BaseBuilder + * @return BaseBuilder */ public function orGroupStart() { @@ -1042,7 +1053,7 @@ public function orGroupStart() /** * Starts a query group, but NOTs the group * - * @return BaseBuilder + * @return BaseBuilder */ public function notGroupStart() { @@ -1054,7 +1065,7 @@ public function notGroupStart() /** * Starts a query group, but OR NOTs the group * - * @return BaseBuilder + * @return BaseBuilder */ public function orNotGroupStart() { @@ -1066,14 +1077,14 @@ public function orNotGroupStart() /** * Ends a query group * - * @return BaseBuilder + * @return BaseBuilder */ public function groupEnd() { $this->QBWhereGroupStarted = false; - $where = [ - 'condition' => str_repeat(' ', $this->QBWhereGroupCount -- ) . ')', - 'escape' => false, + $where = [ + 'condition' => str_repeat(' ', $this->QBWhereGroupCount -- ) . ')', + 'escape' => false, ]; $this->QBWhere[] = $where; @@ -1086,20 +1097,20 @@ public function groupEnd() /** * Group_get_type * - * @used-by groupStart() - * @used-by _like() - * @used-by whereHaving() - * @used-by _whereIn() + * @used-by groupStart() + * @used-by _like() + * @used-by whereHaving() + * @used-by _whereIn() * - * @param string $type + * @param string $type * - * @return string + * @return string */ protected function groupGetType($type) { if ($this->QBWhereGroupStarted) { - $type = ''; + $type = ''; $this->QBWhereGroupStarted = false; } @@ -1111,10 +1122,10 @@ protected function groupGetType($type) /** * GROUP BY * - * @param string $by - * @param bool $escape + * @param string $by + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function groupBy($by, $escape = null) { @@ -1131,7 +1142,10 @@ public function groupBy($by, $escape = null) if ($val !== '') { - $val = ['field' => $val, 'escape' => $escape]; + $val = [ + 'field' => $val, + 'escape' => $escape, + ]; $this->QBGroupBy[] = $val; } @@ -1147,11 +1161,11 @@ public function groupBy($by, $escape = null) * * Separates multiple calls with 'AND'. * - * @param string $key - * @param string $value - * @param bool $escape + * @param string $key + * @param string $value + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function having($key, $value = null, $escape = null) { @@ -1165,11 +1179,11 @@ public function having($key, $value = null, $escape = null) * * Separates multiple calls with 'OR'. * - * @param string $key - * @param string $value - * @param bool $escape + * @param string $key + * @param string $value + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orHaving($key, $value = null, $escape = null) { @@ -1181,11 +1195,11 @@ public function orHaving($key, $value = null, $escape = null) /** * ORDER BY * - * @param string $orderby - * @param string $direction ASC, DESC or RANDOM - * @param bool $escape + * @param string $orderby + * @param string $direction ASC, DESC or RANDOM + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orderBy($orderby, $direction = '', $escape = null) { @@ -1211,7 +1225,11 @@ public function orderBy($orderby, $direction = '', $escape = null) if ($escape === false) { - $qb_orderby[] = ['field' => $orderby, 'direction' => $direction, 'escape' => false]; + $qb_orderby[] = [ + 'field' => $orderby, + 'direction' => $direction, + 'escape' => false, + ]; } else { @@ -1220,10 +1238,14 @@ public function orderBy($orderby, $direction = '', $escape = null) { $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE)) ? [ - 'field' => ltrim(substr($field, 0, $match[0][1])), - 'direction' => ' ' . $match[1][0], - 'escape' => true, - ] : ['field' => trim($field), 'direction' => $direction, 'escape' => true]; + 'field' => ltrim(substr($field, 0, $match[0][1])), + 'direction' => ' ' . $match[1][0], + 'escape' => true, + ] : [ + 'field' => trim($field), + 'direction' => $direction, + 'escape' => true, + ]; } } @@ -1237,19 +1259,19 @@ public function orderBy($orderby, $direction = '', $escape = null) /** * LIMIT * - * @param int $value LIMIT value - * @param int $offset OFFSET value + * @param integer $value LIMIT value + * @param integer $offset OFFSET value * - * @return BaseBuilder + * @return BaseBuilder */ public function limit(int $value = null, int $offset = 0) { - if ( ! is_null($value)) + if (! is_null($value)) { $this->QBLimit = $value; } - if ( ! empty($offset)) + if (! empty($offset)) { $this->QBOffset = $offset; } @@ -1262,13 +1284,13 @@ public function limit(int $value = null, int $offset = 0) /** * Sets the OFFSET value * - * @param int $offset OFFSET value + * @param integer $offset OFFSET value * - * @return BaseBuilder + * @return BaseBuilder */ public function offset($offset) { - if ( ! empty($offset)) + if (! empty($offset)) { $this->QBOffset = (int) $offset; } @@ -1283,9 +1305,9 @@ public function offset($offset) * * Generates a platform-specific LIMIT clause. * - * @param string $sql SQL Query + * @param string $sql SQL Query * - * @return string + * @return string */ protected function _limit($sql) { @@ -1299,17 +1321,17 @@ protected function _limit($sql) * * Allows key/value pairs to be set for insert(), update() or replace(). * - * @param string|array|object $key Field name, or an array of field/value pairs - * @param string $value Field value, if $key is a single field - * @param bool $escape Whether to escape values and identifiers + * @param string|array|object $key Field name, or an array of field/value pairs + * @param string $value Field value, if $key is a single field + * @param boolean $escape Whether to escape values and identifiers * - * @return BaseBuilder + * @return BaseBuilder */ public function set($key, $value = '', $escape = null) { $key = $this->objectToArray($key); - if ( ! is_array($key)) + if (! is_array($key)) { $key = [$key => $value]; } @@ -1320,7 +1342,7 @@ public function set($key, $value = '', $escape = null) { if ($escape) { - $bind = $this->setBind($k, $v); + $bind = $this->setBind($k, $v); $this->QBSet[$this->db->protectIdentifiers($k, false, $escape)] = ":$bind:"; } else @@ -1338,7 +1360,7 @@ public function set($key, $value = '', $escape = null) * Returns the previously set() data, alternatively resetting it * if needed. * - * @param bool $clean + * @param boolean $clean * * @return array */ @@ -1361,9 +1383,9 @@ public function getSetData(bool $clean = false) * * Compiles a SELECT query string and returns the sql. * - * @param bool $reset TRUE: resets QB values; FALSE: leave QB values alone + * @param boolean $reset TRUE: resets QB values; FALSE: leave QB values alone * - * @return string + * @return string */ public function getCompiledSelect($reset = true) { @@ -1385,22 +1407,22 @@ public function getCompiledSelect($reset = true) * Compiles the select statement based on the other functions called * and runs the query * - * @param int $limit The limit clause - * @param int $offset The offset clause - * @param bool $returnSQL If true, returns the generate SQL, otherwise executes the query. - * @param bool $reset Are we want to clear query builder values? + * @param integer $limit The limit clause + * @param integer $offset The offset clause + * @param boolean $returnSQL If true, returns the generate SQL, otherwise executes the query. + * @param boolean $reset Are we want to clear query builder values? * - * @return ResultInterface + * @return ResultInterface */ public function get(int $limit = null, int $offset = 0, $returnSQL = false, $reset = true) { - if ( ! is_null($limit)) + if (! is_null($limit)) { $this->limit($limit, $offset); } $result = $returnSQL ? $this->getCompiledSelect() : $this->db->query($this->compileSelect(), $this->binds); - if($reset == true) + if ($reset === true) { $this->resetSelect(); } @@ -1416,10 +1438,10 @@ public function get(int $limit = null, int $offset = 0, $returnSQL = false, $res * Generates a platform-specific query string that counts all records in * the specified database * - * @param bool $reset Are we want to clear query builder values? - * @param bool $test Are we running automated tests? + * @param boolean $reset Are we want to clear query builder values? + * @param boolean $test Are we running automated tests? * - * @return int + * @return integer */ public function countAll($reset = true, $test = false) { @@ -1440,7 +1462,7 @@ public function countAll($reset = true, $test = false) } $query = $query->getRow(); - + if ($reset === true) { $this->resetSelect(); @@ -1457,10 +1479,10 @@ public function countAll($reset = true, $test = false) * Generates a platform-specific query string that counts all records * returned by an Query Builder query. * - * @param bool $reset - * @param bool $test The reset clause + * @param boolean $reset + * @param boolean $test The reset clause * - * @return int + * @return integer */ public function countAllResults($reset = true, $test = false) { @@ -1468,9 +1490,9 @@ public function countAllResults($reset = true, $test = false) // on Microsoft SQL Server) and ultimately unnecessary // for selecting COUNT(*) ... $orderby = []; - if ( ! empty($this->QBOrderBy)) + if (! empty($this->QBOrderBy)) { - $orderby = $this->QBOrderBy; + $orderby = $this->QBOrderBy; $this->QBOrderBy = null; } @@ -1489,9 +1511,9 @@ public function countAllResults($reset = true, $test = false) $this->resetSelect(); } // If we've previously reset the QBOrderBy values, get them back - elseif ( ! isset($this->QBOrderBy)) + elseif (! isset($this->QBOrderBy)) { - $this->QBOrderBy = $orderby??[]; + $this->QBOrderBy = $orderby ?? []; } $row = (! $result instanceof ResultInterface) @@ -1513,11 +1535,11 @@ public function countAllResults($reset = true, $test = false) * * Allows the where clause, limit and offset to be added directly * - * @param string $where - * @param int $limit - * @param int $offset + * @param string $where + * @param integer $limit + * @param integer $offset * - * @return ResultInterface + * @return ResultInterface */ public function getWhere($where = null, $limit = null, $offset = null) { @@ -1526,7 +1548,7 @@ public function getWhere($where = null, $limit = null, $offset = null) $this->where($where); } - if ( ! empty($limit)) + if (! empty($limit)) { $this->limit($limit, $offset); } @@ -1544,13 +1566,13 @@ public function getWhere($where = null, $limit = null, $offset = null) * * Compiles batch insert strings and runs the queries * - * @param array $set An associative array of insert values - * @param bool $escape Whether to escape values and identifiers + * @param array $set An associative array of insert values + * @param boolean $escape Whether to escape values and identifiers * - * @param int $batchSize - * @param bool $testing + * @param integer $batchSize + * @param boolean $testing * - * @return int Number of rows inserted or FALSE on failure + * @return integer Number of rows inserted or FALSE on failure * @throws DatabaseException */ public function insertBatch($set = null, $escape = null, $batchSize = 100, $testing = false) @@ -1601,7 +1623,7 @@ public function insertBatch($set = null, $escape = null, $batchSize = 100, $test } } - if ( ! $testing) + if (! $testing) { $this->resetWrite(); } @@ -1616,11 +1638,11 @@ public function insertBatch($set = null, $escape = null, $batchSize = 100, $test * * Generates a platform-specific insert string from the supplied data. * - * @param string $table Table name - * @param array $keys INSERT keys - * @param array $values INSERT values + * @param string $table Table name + * @param array $keys INSERT keys + * @param array $values INSERT values * - * @return string + * @return string */ protected function _insertBatch($table, $keys, $values) { @@ -1632,17 +1654,17 @@ protected function _insertBatch($table, $keys, $values) /** * The "setInsertBatch" function. Allows key/value pairs to be set for batch inserts * - * @param mixed $key - * @param string $value - * @param bool $escape + * @param mixed $key + * @param string $value + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function setInsertBatch($key, $value = '', $escape = null) { $key = $this->batchObjectToArray($key); - if ( ! is_array($key)) + if (! is_array($key)) { $key = [$key => $value]; } @@ -1668,7 +1690,7 @@ public function setInsertBatch($key, $value = '', $escape = null) $clean = []; foreach ($row as $k => $value) { - $clean[] = ':' . $this->setBind($k, $value) .':'; + $clean[] = ':' . $this->setBind($k, $value) . ':'; } $row = $clean; @@ -1691,9 +1713,9 @@ public function setInsertBatch($key, $value = '', $escape = null) * * Compiles an insert query and returns the sql * - * @param bool $reset TRUE: reset QB values; FALSE: leave QB values alone + * @param boolean $reset TRUE: reset QB values; FALSE: leave QB values alone * - * @return string + * @return string */ public function getCompiledInsert($reset = true) { @@ -1723,11 +1745,11 @@ public function getCompiledInsert($reset = true) * * Compiles an insert string and runs the query * - * @param array $set An associative array of insert values - * @param bool $escape Whether to escape values and identifiers - * @param bool $test Used when running tests + * @param array $set An associative array of insert values + * @param boolean $escape Whether to escape values and identifiers + * @param boolean $test Used when running tests * - * @return bool TRUE on success, FALSE on failure + * @return boolean TRUE on success, FALSE on failure */ public function insert($set = null, $escape = null, $test = false) { @@ -1764,7 +1786,7 @@ public function insert($set = null, $escape = null, $test = false) * validate that the there data is actually being set and that table * has been chosen to be inserted into. * - * @return string + * @return string * @throws DatabaseException */ protected function validateInsert() @@ -1789,11 +1811,11 @@ protected function validateInsert() * * Generates a platform-specific insert string from the supplied data * - * @param string $table The table name - * @param array $keys The insert keys - * @param array $unescapedKeys The insert values + * @param string $table The table name + * @param array $keys The insert keys + * @param array $unescapedKeys The insert values * - * @return string + * @return string */ protected function _insert($table, array $keys, array $unescapedKeys) { @@ -1807,10 +1829,10 @@ protected function _insert($table, array $keys, array $unescapedKeys) * * Compiles an replace into string and runs the query * - * @param array $set An associative array of insert values - * @param bool $returnSQL + * @param array $set An associative array of insert values + * @param boolean $returnSQL * - * @return bool TRUE on success, FALSE on failure + * @return boolean TRUE on success, FALSE on failure * @throws DatabaseException */ public function replace($set = null, $returnSQL = false) @@ -1845,11 +1867,11 @@ public function replace($set = null, $returnSQL = false) * * Generates a platform-specific replace string from the supplied data * - * @param string $table The table name - * @param array $keys The insert keys - * @param array $values The insert values + * @param string $table The table name + * @param array $keys The insert keys + * @param array $values The insert values * - * @return string + * @return string */ protected function _replace($table, $keys, $values) { @@ -1866,7 +1888,7 @@ protected function _replace($table, $keys, $values) * * Note: This is only used (and overridden) by MySQL and CUBRID. * - * @return string + * @return string */ protected function _fromTables() { @@ -1880,9 +1902,9 @@ protected function _fromTables() * * Compiles an update query and returns the sql * - * @param bool $reset TRUE: reset QB values; FALSE: leave QB values alone + * @param boolean $reset TRUE: reset QB values; FALSE: leave QB values alone * - * @return string + * @return string */ public function getCompiledUpdate($reset = true) { @@ -1908,12 +1930,12 @@ public function getCompiledUpdate($reset = true) * * Compiles an update string and runs the query. * - * @param array $set An associative array of update values - * @param mixed $where - * @param int $limit - * @param bool $test Are we testing the code? + * @param array $set An associative array of update values + * @param mixed $where + * @param integer $limit + * @param boolean $test Are we testing the code? * - * @return bool TRUE on success, FALSE on failure + * @return boolean TRUE on success, FALSE on failure */ public function update($set = null, $where = null, int $limit = null, $test = false) { @@ -1932,7 +1954,7 @@ public function update($set = null, $where = null, int $limit = null, $test = fa $this->where($where); } - if ( ! empty($limit)) + if (! empty($limit)) { if (! $this->canLimitWhereUpdates) { @@ -1944,7 +1966,7 @@ public function update($set = null, $where = null, int $limit = null, $test = fa $sql = $this->_update($this->QBFrom[0], $this->QBSet); - if ( ! $test) + if (! $test) { $this->resetWrite(); @@ -1966,10 +1988,10 @@ public function update($set = null, $where = null, int $limit = null, $test = fa * * Generates a platform-specific update string from the supplied data * - * @param string $table the Table name - * @param array $values the Update data + * @param string $table the Table name + * @param array $values the Update data * - * @return string + * @return string */ protected function _update($table, $values) { @@ -1993,8 +2015,7 @@ protected function _update($table, $values) * validate that data is actually being set and that a table has been * chosen to be update. * - * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ protected function validateUpdate() @@ -2019,12 +2040,12 @@ protected function validateUpdate() * * Compiles an update string and runs the query * - * @param array $set An associative array of update values - * @param string $index The where key - * @param int $batchSize The size of the batch to run - * @param bool $returnSQL True means SQL is returned, false will execute the query + * @param array $set An associative array of update values + * @param string $index The where key + * @param integer $batchSize The size of the batch to run + * @param boolean $returnSQL True means SQL is returned, false will execute the query * - * @return mixed Number of rows affected or FALSE on failure + * @return mixed Number of rows affected or FALSE on failure * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function updateBatch($set = null, $index = null, $batchSize = 100, $returnSQL = false) @@ -2068,7 +2089,7 @@ public function updateBatch($set = null, $index = null, $batchSize = 100, $retur // Batch this baby $affected_rows = 0; - $savedSQL = []; + $savedSQL = []; for ($i = 0, $total = count($this->QBSet); $i < $total; $i += $batchSize) { $sql = $this->_updateBatch($table, array_slice($this->QBSet, $i, $batchSize), $this->db->protectIdentifiers($index) @@ -2099,11 +2120,11 @@ public function updateBatch($set = null, $index = null, $batchSize = 100, $retur * * Generates a platform-specific batch update string from the supplied data * - * @param string $table Table name - * @param array $values Update data - * @param string $index WHERE key + * @param string $table Table name + * @param array $values Update data + * @param string $index WHERE key * - * @return string + * @return string */ protected function _updateBatch($table, $values, $index) { @@ -2139,18 +2160,18 @@ protected function _updateBatch($table, $values, $index) /** * The "setUpdateBatch" function. Allows key/value pairs to be set for batch updating * - * @param array $key - * @param string $index - * @param bool $escape + * @param array $key + * @param string $index + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function setUpdateBatch($key, $index = '', $escape = null) { $key = $this->batchObjectToArray($key); - if ( ! is_array($key)) + if (! is_array($key)) { // @todo error } @@ -2160,7 +2181,7 @@ public function setUpdateBatch($key, $index = '', $escape = null) foreach ($key as $k => $v) { $index_set = false; - $clean = []; + $clean = []; foreach ($v as $k2 => $v2) { if ($k2 === $index) @@ -2191,8 +2212,8 @@ public function setUpdateBatch($key, $index = '', $escape = null) * * Compiles a delete string and runs "DELETE FROM table" * - * @param bool $test - * @return bool TRUE on success, FALSE on failure + * @param boolean $test + * @return boolean TRUE on success, FALSE on failure */ public function emptyTable($test = false) { @@ -2219,9 +2240,9 @@ public function emptyTable($test = false) * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * - * @param bool $test Whether we're in test mode or not. + * @param boolean $test Whether we're in test mode or not. * - * @return bool TRUE on success, FALSE on failure + * @return boolean TRUE on success, FALSE on failure */ public function truncate($test = false) { @@ -2249,9 +2270,9 @@ public function truncate($test = false) * If the database does not support the truncate() command, * then this method maps to 'DELETE FROM table' * - * @param string $table The table name + * @param string $table The table name * - * @return string + * @return string */ protected function _truncate($table) { @@ -2265,16 +2286,16 @@ protected function _truncate($table) * * Compiles a delete query string and returns the sql * - * @param bool $reset TRUE: reset QB values; FALSE: leave QB values alone + * @param boolean $reset TRUE: reset QB values; FALSE: leave QB values alone * - * @return string + * @return string */ public function getCompiledDelete($reset = true) { $table = $this->QBFrom[0]; $this->returnDeleteSQL = true; - $sql = $this->delete($table, '', null, $reset); + $sql = $this->delete($table, '', null, $reset); $this->returnDeleteSQL = false; return $sql; @@ -2287,12 +2308,12 @@ public function getCompiledDelete($reset = true) * * Compiles a delete string and runs the query * - * @param mixed $where The where clause - * @param mixed $limit The limit clause - * @param bool $reset_data - * @param bool $returnSQL + * @param mixed $where The where clause + * @param mixed $limit The limit clause + * @param boolean $reset_data + * @param boolean $returnSQL * - * @return mixed + * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function delete($where = '', $limit = null, $reset_data = true, $returnSQL = false) @@ -2316,12 +2337,12 @@ public function delete($where = '', $limit = null, $reset_data = true, $returnSQ $sql = $this->_delete($table); - if ( ! empty($limit)) + if (! empty($limit)) { $this->QBLimit = $limit; } - if ( ! empty($this->QBLimit)) + if (! empty($this->QBLimit)) { if (! $this->canLimitDeletes) { @@ -2344,10 +2365,10 @@ public function delete($where = '', $limit = null, $reset_data = true, $returnSQ /** * Increments a numeric column by the specified value. * - * @param string $column - * @param int $value + * @param string $column + * @param integer $value * - * @return bool + * @return boolean */ public function increment(string $column, int $value = 1) { @@ -2363,10 +2384,10 @@ public function increment(string $column, int $value = 1) /** * Decrements a numeric column by the specified value. * - * @param string $column - * @param int $value + * @param string $column + * @param integer $value * - * @return bool + * @return boolean */ public function decrement(string $column, int $value = 1) { @@ -2384,9 +2405,9 @@ public function decrement(string $column, int $value = 1) * * Generates a platform-specific delete string from the supplied data * - * @param string $table The table name + * @param string $table The table name * - * @return string + * @return string */ protected function _delete($table) { @@ -2401,9 +2422,9 @@ protected function _delete($table) * * Used to track SQL statements written with aliased tables. * - * @param string $table The table to inspect + * @param string $table The table to inspect * - * @return string + * @return string */ protected function trackAliases($table) { @@ -2446,9 +2467,9 @@ protected function trackAliases($table) * Generates a query string based on which functions were used. * Should not be called directly. * - * @param bool $select_override + * @param boolean $select_override * - * @return string + * @return string */ protected function compileSelect($select_override = false) { @@ -2472,7 +2493,7 @@ protected function compileSelect($select_override = false) // is because until the user calls the from() function we don't know if there are aliases foreach ($this->QBSelect as $key => $val) { - $no_escape = $this->QBNoEscape[$key] ?? null; + $no_escape = $this->QBNoEscape[$key] ?? null; $this->QBSelect[$key] = $this->db->protectIdentifiers($val, false, $no_escape); } @@ -2516,15 +2537,15 @@ protected function compileSelect($select_override = false) * where(), orWhere(), having(), orHaving are called prior to from(), * join() and prefixTable is added only if needed. * - * @param string $qb_key 'QBWhere' or 'QBHaving' + * @param string $qb_key 'QBWhere' or 'QBHaving' * - * @return string SQL statement + * @return string SQL statement */ protected function compileWhereHaving($qb_key) { if (! empty($this->$qb_key)) { - for ($i = 0, $c = count($this->$qb_key); $i < $c; $i ++ ) + for ($i = 0, $c = count($this->$qb_key); $i < $c; $i ++) { // Is this condition already compiled? if (is_string($this->{$qb_key}[$i])) @@ -2542,7 +2563,7 @@ protected function compileWhereHaving($qb_key) '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i', $this->{$qb_key}[$i]['condition'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); - for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci ++ ) + for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci ++) { if (($op = $this->getOperator($conditions[$ci])) === false || ! preg_match('/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(? ')' /* optional */ // ); - if ( ! empty($matches[4])) + if (! empty($matches[4])) { -// $this->isLiteral($matches[4]) OR $matches[4] = $this->db->protectIdentifiers(trim($matches[4])); + // $this->isLiteral($matches[4]) OR $matches[4] = $this->db->protectIdentifiers(trim($matches[4])); $matches[4] = ' ' . $matches[4]; } @@ -2591,13 +2612,13 @@ protected function compileWhereHaving($qb_key) * groupBy() is called prior to from(), join() and prefixTable is added * only if needed. * - * @return string SQL statement + * @return string SQL statement */ protected function compileGroupBy() { if (! empty($this->QBGroupBy)) { - for ($i = 0, $c = count($this->QBGroupBy); $i < $c; $i ++ ) + for ($i = 0, $c = count($this->QBGroupBy); $i < $c; $i ++) { // Is it already compiled? if (is_string($this->QBGroupBy[$i])) @@ -2605,7 +2626,7 @@ protected function compileGroupBy() continue; } - $this->QBGroupBy[$i] = ($this->QBGroupBy[$i]['escape'] === false OR + $this->QBGroupBy[$i] = ($this->QBGroupBy[$i]['escape'] === false || $this->isLiteral($this->QBGroupBy[$i]['field'])) ? $this->QBGroupBy[$i]['field'] : $this->db->protectIdentifiers($this->QBGroupBy[$i]['field']); } @@ -2626,13 +2647,13 @@ protected function compileGroupBy() * orderBy() is called prior to from(), join() and prefixTable is added * only if needed. * - * @return string SQL statement + * @return string SQL statement */ protected function compileOrderBy() { if (is_array($this->QBOrderBy) && ! empty($this->QBOrderBy)) { - for ($i = 0, $c = count($this->QBOrderBy); $i < $c; $i ++ ) + for ($i = 0, $c = count($this->QBOrderBy); $i < $c; $i ++) { if ($this->QBOrderBy[$i]['escape'] !== false && ! $this->isLiteral($this->QBOrderBy[$i]['field'])) { @@ -2659,13 +2680,13 @@ protected function compileOrderBy() * * Takes an object as input and converts the class variables to array key/vals * - * @param object $object + * @param object $object * - * @return array + * @return array */ protected function objectToArray($object) { - if ( ! is_object($object)) + if (! is_object($object)) { return $object; } @@ -2674,7 +2695,7 @@ protected function objectToArray($object) foreach (get_object_vars($object) as $key => $val) { // There are some built in keys we need to ignore for this conversion - if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name') + if (! is_object($val) && ! is_array($val) && $key !== '_parent_name') { $array[$key] = $val; } @@ -2690,19 +2711,19 @@ protected function objectToArray($object) * * Takes an object as input and converts the class variables to array key/vals * - * @param object $object + * @param object $object * - * @return array + * @return array */ protected function batchObjectToArray($object) { - if ( ! is_object($object)) + if (! is_object($object)) { return $object; } - $array = []; - $out = get_object_vars($object); + $array = []; + $out = get_object_vars($object); $fields = array_keys($out); foreach ($fields as $val) @@ -2728,9 +2749,9 @@ protected function batchObjectToArray($object) * * Determines if a string represents a literal value or a field name * - * @param string $str + * @param string $str * - * @return bool + * @return boolean */ protected function isLiteral($str) { @@ -2760,7 +2781,7 @@ protected function isLiteral($str) * * Publicly-visible method to reset the QB values. * - * @return BaseBuilder + * @return BaseBuilder */ public function resetQuery() { @@ -2775,7 +2796,7 @@ public function resetQuery() /** * Resets the query builder values. Called by the get() function * - * @param array $qb_reset_items An array of fields to reset + * @param array $qb_reset_items An array of fields to reset */ protected function resetRun($qb_reset_items) { @@ -2793,16 +2814,16 @@ protected function resetRun($qb_reset_items) protected function resetSelect() { $this->resetRun([ - 'QBSelect' => [], - 'QBJoin' => [], - 'QBWhere' => [], - 'QBGroupBy' => [], - 'QBHaving' => [], - 'QBOrderBy' => [], - 'QBNoEscape' => [], - 'QBDistinct' => false, - 'QBLimit' => false, - 'QBOffset' => false, + 'QBSelect' => [], + 'QBJoin' => [], + 'QBWhere' => [], + 'QBGroupBy' => [], + 'QBHaving' => [], + 'QBOrderBy' => [], + 'QBNoEscape' => [], + 'QBDistinct' => false, + 'QBLimit' => false, + 'QBOffset' => false, ]); if (! empty($this->db)) @@ -2821,12 +2842,12 @@ protected function resetSelect() protected function resetWrite() { $this->resetRun([ - 'QBSet' => [], - 'QBJoin' => [], - 'QBWhere' => [], - 'QBOrderBy' => [], - 'QBKeys' => [], - 'QBLimit' => false, + 'QBSet' => [], + 'QBJoin' => [], + 'QBWhere' => [], + 'QBOrderBy' => [], + 'QBKeys' => [], + 'QBLimit' => false, ]); } @@ -2835,9 +2856,9 @@ protected function resetWrite() /** * Tests whether the string has an SQL operator * - * @param string $str + * @param string $str * - * @return bool + * @return boolean */ protected function hasOperator($str) { @@ -2849,9 +2870,9 @@ protected function hasOperator($str) /** * Returns the SQL string operator * - * @param string $str + * @param string $str * - * @return string + * @return string */ protected function getOperator($str) { @@ -2859,7 +2880,7 @@ protected function getOperator($str) if (empty($_operators)) { - $_les = ($this->db->likeEscapeStr !== '') ? '\s+' . preg_quote(trim(sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar)), '/') : ''; + $_les = ($this->db->likeEscapeStr !== '') ? '\s+' . preg_quote(trim(sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar)), '/') : ''; $_operators = [ '\s*(?:<|>|!)?=\s*', // =, <=, >=, != '\s*<>?\s*', // <, <> @@ -2872,7 +2893,7 @@ protected function getOperator($str) '\s+IN\s*\(.*\)', // IN(list) '\s+NOT IN\s*\(.*\)', // NOT IN (list) '\s+LIKE\s+\S.*(' . $_les . ')?', // LIKE 'expr'[ ESCAPE '%s'] - '\s+NOT LIKE\s+\S.*(' . $_les . ')?' // NOT LIKE 'expr'[ ESCAPE '%s'] + '\s+NOT LIKE\s+\S.*(' . $_les . ')?', // NOT LIKE 'expr'[ ESCAPE '%s'] ]; } @@ -2891,7 +2912,7 @@ protected function getOperator($str) */ protected function setBind(string $key, $value = null) { - if ( ! array_key_exists($key, $this->binds)) + if (! array_key_exists($key, $this->binds)) { $this->binds[$key] = $value; diff --git a/system/Database/BasePreparedQuery.php b/system/Database/BasePreparedQuery.php index 867b95400fb0..355fd145af47 100644 --- a/system/Database/BasePreparedQuery.php +++ b/system/Database/BasePreparedQuery.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Events\Events; abstract class BasePreparedQuery implements PreparedQueryInterface @@ -50,7 +51,7 @@ abstract class BasePreparedQuery implements PreparedQueryInterface /** * The error code, if any. * - * @var int + * @var integer */ protected $errorCode; @@ -93,7 +94,7 @@ public function __construct(ConnectionInterface $db) * override this method. * * @param string $sql - * @param array $options Passed to the connection's prepare statement. + * @param array $options Passed to the connection's prepare statement. * @param string $queryClass * * @return mixed @@ -112,7 +113,7 @@ public function prepare(string $sql, array $options = [], $queryClass = 'CodeIgn $query->setQuery($sql); - if ( ! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) + if (! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) { $query->swapPrefix($this->db->DBPrefix, $this->db->swapPre); } @@ -128,7 +129,7 @@ public function prepare(string $sql, array $options = [], $queryClass = 'CodeIgn * The database-dependent portion of the prepare statement. * * @param string $sql - * @param array $options Passed to the connection's prepare statement. + * @param array $options Passed to the connection's prepare statement. * * @return mixed */ @@ -195,7 +196,7 @@ abstract public function _getResult(); */ public function close() { - if ( ! is_object($this->statement)) + if (! is_object($this->statement)) { return; } @@ -212,7 +213,7 @@ public function close() */ public function getQueryString(): string { - if ( ! $this->query instanceof QueryInterface) + if (! $this->query instanceof QueryInterface) { throw new \BadMethodCallException('Cannot call getQueryString on a prepared query until after the query has been prepared.'); } @@ -225,7 +226,7 @@ public function getQueryString(): string /** * A helper to determine if any error exists. * - * @return bool + * @return boolean */ public function hasError() { @@ -237,7 +238,7 @@ public function hasError() /** * Returns the error code created while executing this statement. * - * @return int + * @return integer */ public function getErrorCode(): int { diff --git a/system/Database/BaseUtils.php b/system/Database/BaseUtils.php index 50f3021c3dfb..4efa53ed0314 100644 --- a/system/Database/BaseUtils.php +++ b/system/Database/BaseUtils.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use \CodeIgniter\Database\Exceptions\DatabaseException; /** @@ -46,7 +47,7 @@ abstract class BaseUtils /** * Database object * - * @var object + * @var object */ protected $db; @@ -55,23 +56,23 @@ abstract class BaseUtils /** * List databases statement * - * @var string + * @var string */ - protected $listDatabases = FALSE; + protected $listDatabases = false; /** * OPTIMIZE TABLE statement * - * @var string + * @var string */ - protected $optimizeTable = FALSE; + protected $optimizeTable = false; /** * REPAIR TABLE statement * - * @var string + * @var string */ - protected $repairTable = FALSE; + protected $repairTable = false; //-------------------------------------------------------------------- @@ -90,7 +91,7 @@ public function __construct(ConnectionInterface &$db) /** * List databases * - * @return array|bool + * @return array|boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function listDatabases() @@ -100,7 +101,7 @@ public function listDatabases() { return $this->db->dataCache['db_names']; } - elseif ($this->listDatabases === FALSE) + elseif ($this->listDatabases === false) { if ($this->db->DBDebug) { @@ -112,12 +113,12 @@ public function listDatabases() $this->db->dataCache['db_names'] = []; $query = $this->db->query($this->listDatabases); - if ($query === FALSE) + if ($query === false) { return $this->db->dataCache['db_names']; } - for ($i = 0, $query = $query->getResultArray(), $c = count($query); $i < $c; $i ++ ) + for ($i = 0, $query = $query->getResultArray(), $c = count($query); $i < $c; $i ++) { $this->db->dataCache['db_names'][] = current($query[$i]); } @@ -130,8 +131,8 @@ public function listDatabases() /** * Determine if a particular database exists * - * @param string $database_name - * @return bool + * @param string $database_name + * @return boolean */ public function databaseExists($database_name) { @@ -143,13 +144,13 @@ public function databaseExists($database_name) /** * Optimize Table * - * @param string $table_name - * @return bool|mixed + * @param string $table_name + * @return boolean|mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function optimizeTable($table_name) { - if ($this->optimizeTable === FALSE) + if ($this->optimizeTable === false) { if ($this->db->DBDebug) { @@ -159,13 +160,13 @@ public function optimizeTable($table_name) } $query = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($table_name))); - if ($query !== FALSE) + if ($query !== false) { $query = $query->getResultArray(); return current($query); } - return FALSE; + return false; } //-------------------------------------------------------------------- @@ -178,7 +179,7 @@ public function optimizeTable($table_name) */ public function optimizeDatabase() { - if ($this->optimizeTable === FALSE) + if ($this->optimizeTable === false) { if ($this->db->DBDebug) { @@ -197,9 +198,9 @@ public function optimizeDatabase() } // Build the result array... - $res = $res->getResultArray(); - $res = current($res); - $key = str_replace($this->db->database . '.', '', current($res)); + $res = $res->getResultArray(); + $res = current($res); + $key = str_replace($this->db->database . '.', '', current($res)); $keys = array_keys($res); unset($res[$keys[0]]); @@ -214,13 +215,13 @@ public function optimizeDatabase() /** * Repair Table * - * @param string $table_name - * @return mixed + * @param string $table_name + * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function repairTable($table_name) { - if ($this->repairTable === FALSE) + if ($this->repairTable === false) { if ($this->db->DBDebug) { @@ -244,12 +245,12 @@ public function repairTable($table_name) /** * Generate CSV from a query result object * - * @param ResultInterface $query Query result object - * @param string $delim Delimiter (default: ,) - * @param string $newline Newline character (default: \n) - * @param string $enclosure Enclosure (default: ") + * @param ResultInterface $query Query result object + * @param string $delim Delimiter (default: ,) + * @param string $newline Newline character (default: \n) + * @param string $enclosure Enclosure (default: ") * - * @return string + * @return string */ public function getCSVFromResult(ResultInterface $query, $delim = ',', $newline = "\n", $enclosure = '"') { @@ -281,17 +282,17 @@ public function getCSVFromResult(ResultInterface $query, $delim = ',', $newline /** * Generate XML data from a query result object * - * @param ResultInterface $query Query result object - * @param array $params Any preferences + * @param ResultInterface $query Query result object + * @param array $params Any preferences * - * @return string + * @return string */ public function getXMLFromResult(ResultInterface $query, $params = []) { // Set our default values foreach (['root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t"] as $key => $val) { - if ( ! isset($params[$key])) + if (! isset($params[$key])) { $params[$key] = $val; } @@ -301,7 +302,7 @@ public function getXMLFromResult(ResultInterface $query, $params = []) extract($params); // Load the xml helper - helper('xml'); + helper('xml'); // Generate the result $xml = '<' . $root . '>' . $newline; while ($row = $query->getUnbufferedRow()) @@ -322,8 +323,8 @@ public function getXMLFromResult(ResultInterface $query, $params = []) /** * Database Backup * - * @param array $params - * @return mixed + * @param array $params + * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function backup($params = []) @@ -338,14 +339,14 @@ public function backup($params = []) // Set up our default preferences $prefs = [ - 'tables' => [], - 'ignore' => [], - 'filename' => '', - 'format' => 'gzip', // gzip, zip, txt - 'add_drop' => TRUE, - 'add_insert' => TRUE, - 'newline' => "\n", - 'foreign_key_checks' => TRUE + 'tables' => [], + 'ignore' => [], + 'filename' => '', + 'format' => 'gzip', // gzip, zip, txt + 'add_drop' => true, + 'add_insert' => true, + 'newline' => "\n", + 'foreign_key_checks' => true, ]; // Did the user submit any preferences? If so set them.... @@ -368,7 +369,7 @@ public function backup($params = []) } // Validate the format - if ( ! in_array($prefs['format'], ['gzip', 'zip', 'txt'], TRUE)) + if (! in_array($prefs['format'], ['gzip', 'zip', 'txt'], true)) { $prefs['format'] = 'txt'; } @@ -376,7 +377,7 @@ public function backup($params = []) // Is the encoder supported? If not, we'll either issue an // error or use plain text depending on the debug settings if (($prefs['format'] === 'gzip' && ! function_exists('gzencode')) - OR ( $prefs['format'] === 'zip' && ! function_exists('gzcompress'))) + || ( $prefs['format'] === 'zip' && ! function_exists('gzcompress'))) { if ($this->db->DBDebug) { @@ -404,17 +405,17 @@ public function backup($params = []) } // Tack on the ".sql" file extension if needed - if ( ! preg_match('|.+?\.sql$|', $prefs['filename'])) + if (! preg_match('|.+?\.sql$|', $prefs['filename'])) { $prefs['filename'] .= '.sql'; } } // Load the Zip class and output it -// $CI =& get_instance(); -// $CI->load->library('zip'); -// $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); -// return $CI->zip->get_zip(); + // $CI =& get_instance(); + // $CI->load->library('zip'); + // $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); + // return $CI->zip->get_zip(); } elseif ($prefs['format'] === 'txt') // Was a text file requested? { diff --git a/system/Database/Config.php b/system/Database/Config.php index 0a97742b1c28..b672d8576d3c 100644 --- a/system/Database/Config.php +++ b/system/Database/Config.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Config\BaseConfig; use Config\Database; @@ -65,9 +66,9 @@ class Config extends BaseConfig /** * Creates the default * - * @param string|array $group The name of the connection group to use, - * or an array of configuration settings. - * @param bool $getShared Whether to return a shared instance of the connection. + * @param string|array $group The name of the connection group to use, + * or an array of configuration settings. + * @param boolean $getShared Whether to return a shared instance of the connection. * * @return BaseConnection */ @@ -76,17 +77,17 @@ public static function connect($group = null, bool $getShared = true) if (is_array($group)) { $config = $group; - $group = 'custom'; + $group = 'custom'; } $config = $config ?? new \Config\Database(); if (empty($group)) { - $group = ENVIRONMENT == 'testing' ? 'tests' : $config->defaultGroup; + $group = ENVIRONMENT === 'testing' ? 'tests' : $config->defaultGroup; } - if (is_string($group) && ! isset($config->$group) && $group != 'custom') + if (is_string($group) && ! isset($config->$group) && $group !== 'custom') { throw new \InvalidArgumentException($group . ' is not a valid database connection group.'); } @@ -140,15 +141,15 @@ public static function forge(string $group = null) if (empty($group)) { - $group = ENVIRONMENT == 'testing' ? 'tests' : $config->defaultGroup; + $group = ENVIRONMENT === 'testing' ? 'tests' : $config->defaultGroup; } - if ( ! isset($config->$group)) + if (! isset($config->$group)) { throw new \InvalidArgumentException($group . ' is not a valid database connection group.'); } - if ( ! isset(self::$instances[$group])) + if (! isset(self::$instances[$group])) { $db = self::connect($group); } @@ -180,12 +181,12 @@ public static function utils(string $group = null) $group = $config->defaultGroup; } - if ( ! isset($config->group)) + if (! isset($config->group)) { throw new \InvalidArgumentException($group . ' is not a valid database connection group.'); } - if ( ! isset(self::$instances[$group])) + if (! isset(self::$instances[$group])) { $db = self::connect($group); } diff --git a/system/Database/ConnectionInterface.php b/system/Database/ConnectionInterface.php index 3bd3c262d620..ac055beee8ef 100644 --- a/system/Database/ConnectionInterface.php +++ b/system/Database/ConnectionInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -56,7 +56,7 @@ public function initialize(); /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * @return mixed */ public function connect($persistent = false); diff --git a/system/Database/Database.php b/system/Database/Database.php index 11c9512d7c53..c6fddab06d8c 100644 --- a/system/Database/Database.php +++ b/system/Database/Database.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -64,9 +64,8 @@ class Database * @param array $params * @param string $alias * - * @return mixed + * @return mixed * @internal param bool $useBuilder - * */ public function load(array $params = [], string $alias) { @@ -102,7 +101,7 @@ public function loadForge(ConnectionInterface $db) $className = strpos($db->DBDriver, '\\') === false ? '\CodeIgniter\Database\\' . $db->DBDriver . '\\Forge' : $db->DBDriver . '\\Forge'; // Make sure a connection exists - if ( ! $db->connID) + if (! $db->connID) { $db->initialize(); } @@ -126,7 +125,7 @@ public function loadUtils(ConnectionInterface $db) $className = strpos($db->DBDriver, '\\') === false ? '\CodeIgniter\Database\\' . $db->DBDriver . '\\Utils' : $db->DBDriver . '\\Utils'; // Make sure a connection exists - if ( ! $db->connID) + if (! $db->connID) { $db->initialize(); } diff --git a/system/Database/Exceptions/DatabaseException.php b/system/Database/Exceptions/DatabaseException.php index e4d5c3e6ee0f..b74d0ac377ba 100644 --- a/system/Database/Exceptions/DatabaseException.php +++ b/system/Database/Exceptions/DatabaseException.php @@ -29,12 +29,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -42,7 +42,8 @@ class DatabaseException extends \Error implements ExceptionInterface { /** * Exit status code - * @var int + * + * @var integer */ protected $code = 8; } diff --git a/system/Database/Exceptions/ExceptionInterface.php b/system/Database/Exceptions/ExceptionInterface.php index bd283cbc9452..4c8adb53c633 100644 --- a/system/Database/Exceptions/ExceptionInterface.php +++ b/system/Database/Exceptions/ExceptionInterface.php @@ -6,6 +6,7 @@ * * catch (\CodeIgniter\Database\Exceptions\ExceptionInterface) { ... } */ + interface ExceptionInterface extends \CodeIgniter\Exceptions\ExceptionInterface { diff --git a/system/Database/Forge.php b/system/Database/Forge.php index 8c170a5c49c9..10df88024bda 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use \CodeIgniter\Database\Exceptions\DatabaseException; /** @@ -66,6 +67,7 @@ class Forge /** * List of unique keys. + * * @var array */ protected $uniqueKeys = []; @@ -96,28 +98,28 @@ class Forge /** * CREATE DATABASE statement * - * @var string + * @var string */ protected $createDatabaseStr = 'CREATE DATABASE %s'; /** * DROP DATABASE statement * - * @var string + * @var string */ protected $dropDatabaseStr = 'DROP DATABASE %s'; /** * CREATE TABLE statement * - * @var string + * @var string */ protected $createTableStr = "%s %s (%s\n)"; /** * CREATE TABLE IF statement * - * @var string + * @var string */ protected $createTableIfStr = 'CREATE TABLE IF NOT EXISTS'; @@ -127,42 +129,42 @@ class Forge * Whether table keys are created from within the * CREATE TABLE statement. * - * @var bool + * @var boolean */ protected $createTableKeys = false; /** * DROP TABLE IF EXISTS statement * - * @var string + * @var string */ protected $dropTableIfStr = 'DROP TABLE IF EXISTS'; /** * RENAME TABLE statement * - * @var string + * @var string */ protected $renameTableStr = 'ALTER TABLE %s RENAME TO %s;'; /** * UNSIGNED support * - * @var bool|array + * @var boolean|array */ protected $unsigned = true; /** * NULL value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $null = ''; /** * DEFAULT value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $default = ' DEFAULT '; @@ -195,9 +197,9 @@ public function getConnection() /** * Create database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function createDatabase($db_name) @@ -235,9 +237,9 @@ public function createDatabase($db_name) /** * Drop database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropDatabase($db_name) @@ -278,11 +280,11 @@ public function dropDatabase($db_name) /** * Add Key * - * @param string|array $key - * @param bool $primary - * @param bool $unique + * @param string|array $key + * @param boolean $primary + * @param boolean $unique * - * @return Forge + * @return Forge */ public function addKey($key, bool $primary = false, bool $unique = false) { @@ -321,7 +323,6 @@ public function addPrimaryKey($key) //-------------------------------------------------------------------- - /** * Add Unique Key * @@ -339,9 +340,9 @@ public function addUniqueKey($key) /** * Add Field * - * @param array $field + * @param array $field * - * @return Forge + * @return Forge */ public function addField($field) { @@ -382,11 +383,11 @@ public function addField($field) /** * Add Foreign Key * - * @param string $fieldName - * @param string $tableName - * @param string $tableField - * @param bool $onUpdate - * @param bool $onDelete + * @param string $fieldName + * @param string $tableName + * @param string $tableField + * @param boolean $onUpdate + * @param boolean $onDelete * * @return \CodeIgniter\Database\Forge * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -405,7 +406,6 @@ public function addForeignKey($fieldName = '', $tableName = '', $tableField = '' 'onUpdate' => strtoupper($onUpdate), ]; - return $this; } @@ -414,16 +414,16 @@ public function addForeignKey($fieldName = '', $tableName = '', $tableField = '' /** * Foreign Key Drop * - * @param string $table Table name - * @param string $foreign_name Foreign name + * @param string $table Table name + * @param string $foreign_name Foreign name * - * @return bool|\CodeIgniter\Database\BaseResult|\CodeIgniter\Database\Query|false|mixed + * @return boolean|\CodeIgniter\Database\BaseResult|\CodeIgniter\Database\Query|false|mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropForeignKey($table, $foreign_name) { - $sql = sprintf($this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix.$table), - $this->db->escapeIdentifiers($this->db->DBPrefix.$foreign_name)); + $sql = sprintf($this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix . $table), + $this->db->escapeIdentifiers($this->db->DBPrefix . $foreign_name)); if ($sql === false) { @@ -443,11 +443,11 @@ public function dropForeignKey($table, $foreign_name) /** * Create Table * - * @param string $table Table name - * @param bool $if_not_exists Whether to add IF NOT EXISTS condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $if_not_exists Whether to add IF NOT EXISTS condition + * @param array $attributes Associative array of table attributes * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function createTable($table, $if_not_exists = false, array $attributes = []) @@ -504,11 +504,11 @@ public function createTable($table, $if_not_exists = false, array $attributes = /** * Create Table * - * @param string $table Table name - * @param bool $if_not_exists Whether to add 'IF NOT EXISTS' condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $if_not_exists Whether to add 'IF NOT EXISTS' condition + * @param array $attributes Associative array of table attributes * - * @return mixed + * @return mixed */ protected function _createTable($table, $if_not_exists, $attributes) { @@ -529,8 +529,8 @@ protected function _createTable($table, $if_not_exists, $attributes) $columns = $this->_processFields(true); for ($i = 0, $c = count($columns); $i < $c; $i++) { - $columns[$i] = ($columns[$i]['_literal'] !== false) ? "\n\t".$columns[$i]['_literal'] - : "\n\t".$this->_processColumn($columns[$i]); + $columns[$i] = ($columns[$i]['_literal'] !== false) ? "\n\t" . $columns[$i]['_literal'] + : "\n\t" . $this->_processColumn($columns[$i]); } $columns = implode(',', $columns); @@ -545,7 +545,7 @@ protected function _createTable($table, $if_not_exists, $attributes) } // createTableStr will usually have the following format: "%s %s (%s\n)" - $sql = sprintf($this->createTableStr.'%s', $sql, $this->db->escapeIdentifiers($table), $columns, + $sql = sprintf($this->createTableStr . '%s', $sql, $this->db->escapeIdentifiers($table), $columns, $this->_createTableAttributes($attributes)); return $sql; @@ -556,9 +556,9 @@ protected function _createTable($table, $if_not_exists, $attributes) /** * CREATE TABLE attributes * - * @param array $attributes Associative array of table attributes + * @param array $attributes Associative array of table attributes * - * @return string + * @return string */ protected function _createTableAttributes($attributes) { @@ -580,9 +580,9 @@ protected function _createTableAttributes($attributes) /** * Drop Table * - * @param string $table_name Table name - * @param bool $if_exists Whether to add an IF EXISTS condition - * @param bool $cascade Whether to add an CASCADE condition + * @param string $table_name Table name + * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param boolean $cascade Whether to add an CASCADE condition * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -599,14 +599,13 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) return false; } - // If the prefix is already starting the table name, remove it... if (! empty($this->db->DBPrefix) && strpos($table_name, $this->db->DBPrefix) === 0) { $table_name = substr($table_name, strlen($this->db->DBPrefix)); } - if (($query = $this->_dropTable($this->db->DBPrefix.$table_name, $if_exists, $cascade)) === true) + if (($query = $this->_dropTable($this->db->DBPrefix . $table_name, $if_exists, $cascade)) === true) { return true; } @@ -616,7 +615,7 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) // Update table list cache if ($query && ! empty($this->db->dataCache['table_names'])) { - $key = array_search(strtolower($this->db->DBPrefix.$table_name), + $key = array_search(strtolower($this->db->DBPrefix . $table_name), array_map('strtolower', $this->db->dataCache['table_names']), true); if ($key !== false) { @@ -634,11 +633,11 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) * * Generates a platform-specific DROP TABLE string * - * @param string $table Table name - * @param bool $if_exists Whether to add an IF EXISTS condition - * @param bool $cascade Whether to add an CASCADE condition + * @param string $table Table name + * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param boolean $cascade Whether to add an CASCADE condition * - * @return string + * @return string */ protected function _dropTable($table, $if_exists, $cascade) { @@ -659,7 +658,7 @@ protected function _dropTable($table, $if_exists, $cascade) } } - $sql = $sql.' '.$this->db->escapeIdentifiers($table); + $sql = $sql . ' ' . $this->db->escapeIdentifiers($table); return $sql; } @@ -669,10 +668,10 @@ protected function _dropTable($table, $if_exists, $cascade) /** * Rename Table * - * @param string $table_name Old table name - * @param string $new_table_name New table name + * @param string $table_name Old table name + * @param string $new_table_name New table name * - * @return mixed + * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function renameTable($table_name, $new_table_name) @@ -692,17 +691,17 @@ public function renameTable($table_name, $new_table_name) } $result = $this->db->query(sprintf($this->renameTableStr, - $this->db->escapeIdentifiers($this->db->DBPrefix.$table_name), - $this->db->escapeIdentifiers($this->db->DBPrefix.$new_table_name)) + $this->db->escapeIdentifiers($this->db->DBPrefix . $table_name), + $this->db->escapeIdentifiers($this->db->DBPrefix . $new_table_name)) ); if ($result && ! empty($this->db->dataCache['table_names'])) { - $key = array_search(strtolower($this->db->DBPrefix.$table_name), + $key = array_search(strtolower($this->db->DBPrefix . $table_name), array_map('strtolower', $this->db->dataCache['table_names']), true); if ($key !== false) { - $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix.$new_table_name; + $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix . $new_table_name; } } @@ -714,10 +713,10 @@ public function renameTable($table_name, $new_table_name) /** * Column Add * - * @param string $table Table name - * @param array $field Column definition + * @param string $table Table name + * @param array $field Column definition * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function addColumn($table, $field) @@ -730,7 +729,7 @@ public function addColumn($table, $field) $this->addField([$k => $field[$k]]); } - $sqls = $this->_alterTable('ADD', $this->db->DBPrefix.$table, $this->_processFields()); + $sqls = $this->_alterTable('ADD', $this->db->DBPrefix . $table, $this->_processFields()); $this->_reset(); if ($sqls === false) { @@ -758,15 +757,15 @@ public function addColumn($table, $field) /** * Column Drop * - * @param string $table Table name - * @param string $column_name Column name + * @param string $table Table name + * @param string $column_name Column name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropColumn($table, $column_name) { - $sql = $this->_alterTable('DROP', $this->db->DBPrefix.$table, $column_name); + $sql = $this->_alterTable('DROP', $this->db->DBPrefix . $table, $column_name); if ($sql === false) { if ($this->db->DBDebug) @@ -785,10 +784,10 @@ public function dropColumn($table, $column_name) /** * Column Modify * - * @param string $table Table name - * @param string $field Column definition + * @param string $table Table name + * @param string $field Column definition * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function modifyColumn($table, $field) @@ -806,7 +805,7 @@ public function modifyColumn($table, $field) throw new \RuntimeException('Field information is required'); } - $sqls = $this->_alterTable('CHANGE', $this->db->DBPrefix.$table, $this->_processFields()); + $sqls = $this->_alterTable('CHANGE', $this->db->DBPrefix . $table, $this->_processFields()); $this->_reset(); if ($sqls === false) { @@ -834,29 +833,29 @@ public function modifyColumn($table, $field) /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alter_type ALTER type + * @param string $table Table name + * @param mixed $field Column definition * - * @return string|string[] + * @return string|string[] */ protected function _alterTable($alter_type, $table, $field) { - $sql = 'ALTER TABLE '.$this->db->escapeIdentifiers($table).' '; + $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . ' '; // DROP has everything it needs now. if ($alter_type === 'DROP') { - return $sql.'DROP COLUMN '.$this->db->escapeIdentifiers($field); + return $sql . 'DROP COLUMN ' . $this->db->escapeIdentifiers($field); } - $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type.' COLUMN '; + $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type . ' COLUMN '; $sqls = []; for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql - .($field[$i]['_literal'] !== false ? $field[$i]['_literal'] : $this->_processColumn($field[$i])); + . ($field[$i]['_literal'] !== false ? $field[$i]['_literal'] : $this->_processColumn($field[$i])); } return $sqls; @@ -867,9 +866,9 @@ protected function _alterTable($alter_type, $table, $field) /** * Process fields * - * @param bool $create_table + * @param boolean $create_table * - * @return array + * @return array */ protected function _processFields($create_table = false) { @@ -925,7 +924,7 @@ protected function _processFields($create_table = false) { if ($attributes['NULL'] === true) { - $field['null'] = empty($this->null) ? '' : ' '.$this->null; + $field['null'] = empty($this->null) ? '' : ' ' . $this->null; } else { @@ -952,12 +951,12 @@ protected function _processFields($create_table = false) case 'ENUM': case 'SET': $attributes['CONSTRAINT'] = $this->db->escapeString($attributes['CONSTRAINT']); - $field['length'] = is_array($attributes['CONSTRAINT']) ? "('".implode("','", - $attributes['CONSTRAINT'])."')" : '('.$attributes['CONSTRAINT'].')'; + $field['length'] = is_array($attributes['CONSTRAINT']) ? "('" . implode("','", + $attributes['CONSTRAINT']) . "')" : '(' . $attributes['CONSTRAINT'] . ')'; break; default: - $field['length'] = is_array($attributes['CONSTRAINT']) ? '('.implode(',', - $attributes['CONSTRAINT']).')' : '('.$attributes['CONSTRAINT'].')'; + $field['length'] = is_array($attributes['CONSTRAINT']) ? '(' . implode(',', + $attributes['CONSTRAINT']) . ')' : '(' . $attributes['CONSTRAINT'] . ')'; break; } } @@ -973,19 +972,19 @@ protected function _processFields($create_table = false) /** * Process column * - * @param array $field + * @param array $field * - * @return string + * @return string */ protected function _processColumn($field) { return $this->db->escapeIdentifiers($field['name']) - .' '.$field['type'].$field['length'] - .$field['unsigned'] - .$field['default'] - .$field['null'] - .$field['auto_increment'] - .$field['unique']; + . ' ' . $field['type'] . $field['length'] + . $field['unsigned'] + . $field['default'] + . $field['null'] + . $field['auto_increment'] + . $field['unique']; } //-------------------------------------------------------------------- @@ -995,9 +994,9 @@ protected function _processColumn($field) * * Performs a data type mapping between different databases. * - * @param array &$attributes + * @param array &$attributes * - * @return void + * @return void */ protected function _attributeType(&$attributes) { @@ -1018,10 +1017,10 @@ protected function _attributeType(&$attributes) * - array(TYPE => UTYPE) will change $field['type'], * from TYPE to UTYPE in case of a match * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeUnsigned(&$attributes, &$field) { @@ -1062,10 +1061,10 @@ protected function _attributeUnsigned(&$attributes, &$field) /** * Field attribute DEFAULT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeDefault(&$attributes, &$field) { @@ -1078,15 +1077,15 @@ protected function _attributeDefault(&$attributes, &$field) { if ($attributes['DEFAULT'] === null) { - $field['default'] = empty($this->null) ? '' : $this->default.$this->null; + $field['default'] = empty($this->null) ? '' : $this->default . $this->null; // Override the NULL attribute if that's our default $attributes['NULL'] = true; - $field['null'] = empty($this->null) ? '' : ' '.$this->null; + $field['null'] = empty($this->null) ? '' : ' ' . $this->null; } else { - $field['default'] = $this->default.$this->db->escape($attributes['DEFAULT']); + $field['default'] = $this->default . $this->db->escape($attributes['DEFAULT']); } } } @@ -1096,10 +1095,10 @@ protected function _attributeDefault(&$attributes, &$field) /** * Field attribute UNIQUE * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeUnique(&$attributes, &$field) { @@ -1114,15 +1113,15 @@ protected function _attributeUnique(&$attributes, &$field) /** * Field attribute AUTO_INCREMENT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeAutoIncrement(&$attributes, &$field) { if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'int') !== false + && stripos($field['type'], 'int') !== false ) { $field['auto_increment'] = ' AUTO_INCREMENT'; @@ -1134,9 +1133,9 @@ protected function _attributeAutoIncrement(&$attributes, &$field) /** * Process primary keys * - * @param string $table Table name + * @param string $table Table name * - * @return string + * @return string */ protected function _processPrimaryKeys($table) { @@ -1152,8 +1151,8 @@ protected function _processPrimaryKeys($table) if (count($this->primaryKeys) > 0) { - $sql .= ",\n\tCONSTRAINT ".$this->db->escapeIdentifiers('pk_'.$table) - .' PRIMARY KEY('.implode(', ', $this->db->escapeIdentifiers($this->primaryKeys)).')'; + $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers('pk_' . $table) + . ' PRIMARY KEY(' . implode(', ', $this->db->escapeIdentifiers($this->primaryKeys)) . ')'; } return $sql; @@ -1164,9 +1163,9 @@ protected function _processPrimaryKeys($table) /** * Process indexes * - * @param string $table + * @param string $table * - * @return array + * @return array */ protected function _processIndexes($table) { @@ -1190,15 +1189,15 @@ protected function _processIndexes($table) if (in_array($i, $this->uniqueKeys)) { - $sqls[] = 'ALTER TABLE '.$this->db->escapeIdentifiers($table) - .' ADD CONSTRAINT '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' UNIQUE ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) + . ' ADD CONSTRAINT ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' UNIQUE (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; continue; } - $sqls[] = 'CREATE INDEX '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' ON '.$this->db->escapeIdentifiers($table) - .' ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'CREATE INDEX ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' ON ' . $this->db->escapeIdentifiers($table) + . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; } return $sqls; @@ -1209,35 +1208,45 @@ protected function _processIndexes($table) /** * Process foreign keys * - * @param string $table Table name + * @param string $table Table name * - * @return string + * @return string */ - protected function _processForeignKeys($table) { - $sql = ''; - - $allowActions = ['CASCADE','SET NULL','NO ACTION','RESTRICT','SET DEFAULT']; + protected function _processForeignKeys($table) + { + $sql = ''; - if (count($this->foreignKeys) > 0){ - foreach ($this->foreignKeys as $field => $fkey) { - $name_index = $table.'_'.$field.'_foreign'; + $allowActions = [ + 'CASCADE', + 'SET NULL', + 'NO ACTION', + 'RESTRICT', + 'SET DEFAULT', + ]; - $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) - . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES '.$this->db->escapeIdentifiers($this->db->DBPrefix.$fkey['table']).' ('.$this->db->escapeIdentifiers($fkey['field']).')'; + if (count($this->foreignKeys) > 0) + { + foreach ($this->foreignKeys as $field => $fkey) + { + $name_index = $table . '_' . $field . '_foreign'; - if($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions)){ - $sql .= " ON DELETE ".$fkey['onDelete']; - } + $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) + . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')'; - if($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions)){ - $sql .= " ON UPDATE ".$fkey['onUpdate']; - } + if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions)) + { + $sql .= ' ON DELETE ' . $fkey['onDelete']; + } - } - } + if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions)) + { + $sql .= ' ON UPDATE ' . $fkey['onUpdate']; + } + } + } - return $sql; - } + return $sql; + } //-------------------------------------------------------------------- @@ -1246,7 +1255,7 @@ protected function _processForeignKeys($table) { * * Resets table creation vars * - * @return void + * @return void */ protected function _reset() { diff --git a/system/Database/Migration.php b/system/Database/Migration.php index 2e497d904054..88a5002ef5a3 100644 --- a/system/Database/Migration.php +++ b/system/Database/Migration.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -44,18 +44,21 @@ abstract class Migration /** * The name of the database group to use. + * * @var string */ protected $DBGroup; /** * Database Connection instance - * @var BaseConnection + * + * @var BaseConnection */ protected $db; /** * Database Forge instance. + * * @var Forge */ protected $forge; @@ -64,7 +67,7 @@ abstract class Migration /** * Constructor. - * + * * @param \CodeIgniter\Database\Forge $forge */ public function __construct(Forge $forge = null) diff --git a/system/Database/MigrationRunner.php b/system/Database/MigrationRunner.php index 72e3d190dc55..6ec1e66ea6f7 100644 --- a/system/Database/MigrationRunner.php +++ b/system/Database/MigrationRunner.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\Autoload; use CodeIgniter\CLI\CLI; use CodeIgniter\Config\BaseConfig; @@ -49,7 +50,7 @@ class MigrationRunner /** * Whether or not migrations are allowed to run. * - * @var bool + * @var boolean */ protected $enabled = false; @@ -70,7 +71,7 @@ class MigrationRunner /** * The version that current() will take us to. * - * @var int + * @var integer */ protected $currentVersion = 0; @@ -114,14 +115,14 @@ class MigrationRunner * If true, will continue instead of throwing * exceptions. * - * @var bool + * @var boolean */ protected $silent = false; /** * used to return messages for CLI. * - * @var bool + * @var boolean */ protected $cliMessages = []; @@ -137,16 +138,16 @@ class MigrationRunner */ public function __construct(BaseConfig $config, ConnectionInterface $db = null) { - $this->enabled = $config->enabled ?? false; - $this->type = $config->type ?? 'timestamp'; - $this->table = $config->table ?? 'migrations'; + $this->enabled = $config->enabled ?? false; + $this->type = $config->type ?? 'timestamp'; + $this->table = $config->table ?? 'migrations'; $this->currentVersion = $config->currentVersion ?? 0; // Default name space is the app namespace $this->namespace = APP_NAMESPACE; // get default database group - $config = new \Config\Database(); + $config = new \Config\Database(); $this->group = $config->defaultGroup; unset($config); @@ -155,7 +156,7 @@ public function __construct(BaseConfig $config, ConnectionInterface $db = null) throw ConfigException::forMissingMigrationsTable(); } - if ( ! in_array($this->type, ['sequential', 'timestamp'])) + if (! in_array($this->type, ['sequential', 'timestamp'])) { throw ConfigException::forInvalidMigrationType($this->type); } @@ -178,27 +179,27 @@ public function __construct(BaseConfig $config, ConnectionInterface $db = null) * Calls each migration step required to get to the schema version of * choice * - * @param string $targetVersion Target schema version - * @param string $namespace - * @param string $group + * @param string $targetVersion Target schema version + * @param string $namespace + * @param string $group * * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure * @throws ConfigException */ public function version(string $targetVersion, $namespace = null, $group = null) { - if ( ! $this->enabled) + if (! $this->enabled) { throw ConfigException::forDisabledMigrations(); } // Set Namespace if not null - if ( ! is_null($namespace)) + if (! is_null($namespace)) { $this->setNamespace($namespace); } // Set database group if not null - if ( ! is_null($group)) + if (! is_null($group)) { $this->setGroup($group); } @@ -232,12 +233,10 @@ public function version(string $targetVersion, $namespace = null, $group = null) // loop migration for each namespace (module) foreach ($migrations as $version => $migration) { - // Only include migrations within the scoop if (($method === 'up' && $version > $currentVersion && $version <= $targetVersion) || ( $method === 'down' && $version <= $currentVersion && $version > $targetVersion) ) { - include_once $migration->path; // Get namespaced class name $class = $this->namespace . '\Database\Migrations\Migration_' . ($migration->name); @@ -245,7 +244,7 @@ public function version(string $targetVersion, $namespace = null, $group = null) $this->setName($migration->name); // Validate the migration file structure - if ( ! class_exists($class, false)) + if (! class_exists($class, false)) { throw new \RuntimeException(sprintf(lang('Migrations.classNotFound'), $class)); } @@ -253,7 +252,7 @@ public function version(string $targetVersion, $namespace = null, $group = null) // Forcing migration to selected database group $instance = new $class(\Config\Database::forge($this->group)); - if ( ! is_callable([$instance, $method])) + if (! is_callable([$instance, $method])) { throw new \RuntimeException(sprintf(lang('Migrations.missingMethod'), $method)); } @@ -281,18 +280,17 @@ public function version(string $targetVersion, $namespace = null, $group = null) * @param string $namespace * @param string $group * - * @return mixed Current version string on success, FALSE on failure + * @return mixed Current version string on success, FALSE on failure */ public function latest($namespace = null, $group = null) { - // Set Namespace if not null - if ( ! is_null($namespace)) + if (! is_null($namespace)) { $this->setNamespace($namespace); } // Set database group if not null - if ( ! is_null($group)) + if (! is_null($group)) { $this->setGroup($group); } @@ -313,23 +311,22 @@ public function latest($namespace = null, $group = null) * * @param string $group * - * @return bool + * @return boolean */ public function latestAll($group = null) { // Set database group if not null - if ( ! is_null($group)) + if (! is_null($group)) { $this->setGroup($group); } // Get all namespaces form PSR4 paths. - $config = new Autoload(); + $config = new Autoload(); $namespaces = $config->psr4; foreach ($namespaces as $namespace => $path) { - $this->setNamespace($namespace); $migrations = $this->findMigrations(); @@ -340,7 +337,7 @@ public function latestAll($group = null) $lastMigration = end($migrations)->version; // No New migrations to add - if ($lastMigration == $this->getVersion()) + if ($lastMigration === $this->getVersion()) { continue; } @@ -360,12 +357,12 @@ public function latestAll($group = null) * * @param string $group * - * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure + * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure */ public function current($group = null) { // Set database group if not null - if ( ! is_null($group)) + if (! is_null($group)) { $this->setGroup($group); } @@ -378,7 +375,7 @@ public function current($group = null) /** * Retrieves list of available migration scripts * - * @return array list of migrations as $version for one namespace + * @return array list of migrations as $version for one namespace */ public function findMigrations() { @@ -402,8 +399,8 @@ public function findMigrations() $migration = new \stdClass(); // Get migration version number $migration->version = $this->getMigrationNumber($name); - $migration->name = $this->getMigrationName($name); - $migration->path = $file; + $migration->name = $this->getMigrationName($name); + $migration->path = $file; // Add to migrations[version] $migrations[$migration->version] = $migration; @@ -420,11 +417,11 @@ public function findMigrations() * if sequential check if no gaps and check if all consistent with migrations table if downgrading * if timestamp check if consistent with migrations table if downgrading * - * @param array $migrations - * @param string $method - * @param int $targetversion + * @param array $migrations + * @param string $method + * @param integer $targetversion * - * @return bool + * @return boolean */ protected function checkMigrations($migrations, $method, $targetversion) { @@ -439,7 +436,7 @@ protected function checkMigrations($migrations, $method, $targetversion) } // Check if $targetversion file is found - if ($targetversion != 0 && ! array_key_exists($targetversion, $migrations)) + if ($targetversion !== 0 && ! array_key_exists($targetversion, $migrations)) { if ($this->silent) { @@ -453,7 +450,7 @@ protected function checkMigrations($migrations, $method, $targetversion) if ($method === 'down') { $history_migrations = $this->getHistory($this->group); - $history_size = count($history_migrations) - 1; + $history_size = count($history_migrations) - 1; } // Check for sequence gaps $loop = 0; @@ -461,14 +458,14 @@ protected function checkMigrations($migrations, $method, $targetversion) { if ($this->type === 'sequential' && abs($migration->version - $loop) > 1) { - throw new \RuntimeException(lang('Migration.gap') . " " . $migration->version); + throw new \RuntimeException(lang('Migration.gap') . ' ' . $migration->version); } // Check if all old migration files are all available to do downgrading if ($method === 'down') { - if ($loop <= $history_size && $history_migrations[$loop]['version'] != $migration->version) + if ($loop <= $history_size && $history_migrations[$loop]['version'] !== $migration->version) { - throw new \RuntimeException(lang('Migration.gap') . " " . $migration->version); + throw new \RuntimeException(lang('Migration.gap') . ' ' . $migration->version); } } $loop ++; @@ -540,7 +537,7 @@ public function getHistory($group = 'default') ->orderBy('version', 'ASC') ->get(); - if ( ! $query) + if (! $query) { return []; } @@ -554,7 +551,7 @@ public function getHistory($group = 'default') * If $silent == true, then will not throw exceptions and will * attempt to continue gracefully. * - * @param bool $silent + * @param boolean $silent * * @return MigrationRunner */ @@ -570,9 +567,9 @@ public function setSilent(bool $silent) /** * Extracts the migration number from a filename * - * @param string $migration + * @param string $migration * - * @return string Numeric portion of a migration filename + * @return string Numeric portion of a migration filename */ protected function getMigrationNumber($migration) { @@ -584,9 +581,9 @@ protected function getMigrationNumber($migration) /** * Extracts the migration class name from a filename * - * @param string $migration + * @param string $migration * - * @return string text portion of a migration filename + * @return string text portion of a migration filename */ protected function getMigrationName($migration) { @@ -601,7 +598,7 @@ protected function getMigrationName($migration) /** * Retrieves current schema version * - * @return string Current migration version + * @return string Current migration version */ protected function getVersion() { @@ -620,11 +617,10 @@ protected function getVersion() /** * Retrieves current schema version * - * @return string Current migration version + * @return string Current migration version */ public function getCliMessages() { - return $this->cliMessages; } @@ -636,18 +632,17 @@ public function getCliMessages() * @param string $version * * @internal param string $migration Migration reached - * */ protected function addHistory($version) { $this->db->table($this->table) ->insert([ - 'version' => $version, - 'name' => $this->name, - 'group' => $this->group, - 'namespace' => $this->namespace, - 'time' => time(), - ]); + 'version' => $version, + 'name' => $this->name, + 'group' => $this->group, + 'namespace' => $this->namespace, + 'time' => time(), + ]); if (is_cli()) { $this->cliMessages[] = "\t" . CLI::color(lang('Migrations.added'), 'yellow') . "($this->namespace) " . $version . '_' . $this->name; @@ -690,30 +685,30 @@ protected function ensureTable() $forge = \Config\Database::forge(); $forge->addField([ - 'version' => [ - 'type' => 'VARCHAR', + 'version' => [ + 'type' => 'VARCHAR', 'constraint' => 255, - 'null' => false, + 'null' => false, ], - 'name' => [ - 'type' => 'VARCHAR', + 'name' => [ + 'type' => 'VARCHAR', 'constraint' => 255, - 'null' => false, + 'null' => false, ], - 'group' => [ - 'type' => 'VARCHAR', + 'group' => [ + 'type' => 'VARCHAR', 'constraint' => 255, - 'null' => false, + 'null' => false, ], - 'namespace' => [ - 'type' => 'VARCHAR', + 'namespace' => [ + 'type' => 'VARCHAR', 'constraint' => 255, - 'null' => false, + 'null' => false, ], - 'time' => [ - 'type' => 'INT', + 'time' => [ + 'type' => 'INT', 'constraint' => 11, - 'null' => false, + 'null' => false, ], ]); diff --git a/system/Database/MySQLi/Builder.php b/system/Database/MySQLi/Builder.php index 8a13e01cc2bd..1d370a0e5079 100644 --- a/system/Database/MySQLi/Builder.php +++ b/system/Database/MySQLi/Builder.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseBuilder; /** @@ -46,7 +47,7 @@ class Builder extends BaseBuilder /** * Identifier escape character * - * @var string + * @var string */ protected $escapeChar = '`'; diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index df2b81690b59..ae095d1584ee 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use \CodeIgniter\Database\Exceptions\DatabaseException; @@ -48,7 +49,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Database driver * - * @var string + * @var string */ public $DBDriver = 'MySQLi'; @@ -59,7 +60,7 @@ class Connection extends BaseConnection implements ConnectionInterface * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. * - * @var bool + * @var boolean */ public $deleteHack = true; @@ -68,7 +69,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Identifier escape character * - * @var string + * @var string */ public $escapeChar = '`'; @@ -88,7 +89,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -99,14 +100,14 @@ public function connect($persistent = false) if ($this->hostname[0] === '/') { $hostname = null; - $port = null; - $socket = $this->hostname; + $port = null; + $socket = $this->hostname; } else { $hostname = ($persistent === true) ? 'p:' . $this->hostname : $this->hostname; - $port = empty($this->port) ? null : $this->port; - $socket = null; + $port = empty($this->port) ? null : $this->port; + $socket = null; } $client_flags = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0; @@ -139,14 +140,14 @@ public function connect($persistent = false) if (is_array($this->encrypt)) { - $ssl = []; - empty($this->encrypt['ssl_key']) || $ssl['key'] = $this->encrypt['ssl_key']; - empty($this->encrypt['ssl_cert']) || $ssl['cert'] = $this->encrypt['ssl_cert']; - empty($this->encrypt['ssl_ca']) || $ssl['ca'] = $this->encrypt['ssl_ca']; + $ssl = []; + empty($this->encrypt['ssl_key']) || $ssl['key'] = $this->encrypt['ssl_key']; + empty($this->encrypt['ssl_cert']) || $ssl['cert'] = $this->encrypt['ssl_cert']; + empty($this->encrypt['ssl_ca']) || $ssl['ca'] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) || $ssl['capath'] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) || $ssl['cipher'] = $this->encrypt['ssl_cipher']; - if ( ! empty($ssl)) + if (! empty($ssl)) { if (isset($this->encrypt['ssl_verify'])) { @@ -178,8 +179,7 @@ public function connect($persistent = false) ) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails - if ( - ($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'") + if (($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'") ->fetch_object()->Value) ) { @@ -194,7 +194,7 @@ public function connect($persistent = false) return false; } - if ( ! $this->mysqli->set_charset($this->charset)) + if (! $this->mysqli->set_charset($this->charset)) { log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}')."); $this->mysqli->close(); @@ -300,10 +300,10 @@ public function getVersion() */ public function execute($sql) { - while($this->connID->more_results()) + while ($this->connID->more_results()) { $this->connID->next_result(); - if($res = $this->connID->store_result()) + if ($res = $this->connID->store_result()) { $res->free(); } @@ -319,9 +319,9 @@ public function execute($sql) * * If needed, each database adapter can prep the query string * - * @param string $sql an SQL query + * @param string $sql an SQL query * - * @return string + * @return string */ protected function prepQuery($sql) { @@ -352,8 +352,8 @@ public function affectedRows(): int /** * Platform-dependant string escape * - * @param string $str - * @return string + * @param string $str + * @return string */ protected function _escapeString(string $str): string { @@ -375,7 +375,7 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ @@ -383,7 +383,7 @@ protected function _listTables($prefixLimit = false): string { $sql = 'SHOW TABLES FROM ' . $this->escapeIdentifiers($this->database); - if ($prefixLimit !== FALSE && $this->DBPrefix !== '') + if ($prefixLimit !== false && $this->DBPrefix !== '') { return $sql . " LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%'"; } @@ -402,7 +402,7 @@ protected function _listTables($prefixLimit = false): string */ protected function _listColumns(string $table = ''): string { - return 'SHOW COLUMNS FROM ' . $this->protectIdentifiers($table, TRUE, NULL, FALSE); + return 'SHOW COLUMNS FROM ' . $this->protectIdentifiers($table, true, null, false); } //-------------------------------------------------------------------- @@ -410,29 +410,29 @@ protected function _listColumns(string $table = ''): string /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array { - $table = $this->protectIdentifiers($table, TRUE, NULL, FALSE); + $table = $this->protectIdentifiers($table, true, null, false); - if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === FALSE) + if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === false) { throw new DatabaseException(lang('Database.failGetFieldData')); } $query = $query->getResultObject(); $retval = []; - for ($i = 0, $c = count($query); $i < $c; $i ++ ) + for ($i = 0, $c = count($query); $i < $c; $i ++) { - $retval[$i] = new \stdClass(); + $retval[$i] = new \stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length); - $retval[$i]->default = $query[$i]->Default; + $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } @@ -444,16 +444,16 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException * @throws \LogicException */ public function _indexData(string $table): array { - $table = $this->protectIdentifiers($table, TRUE, NULL, FALSE); + $table = $this->protectIdentifiers($table, true, null, false); - if (($query = $this->query('SHOW CREATE TABLE ' . $table)) === FALSE) + if (($query = $this->query('SHOW CREATE TABLE ' . $table)) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); } @@ -469,13 +469,13 @@ public function _indexData(string $table): array $line = trim($line); if (strpos($line, 'PRIMARY KEY') === 0) { - $obj = new \stdClass(); - $obj->name = 'PRIMARY KEY'; - $_fields = explode(',', preg_replace('/^.*\((.+)\).*$/', '$1', $line)); - $obj->fields = array_map(function($v) { + $obj = new \stdClass(); + $obj->name = 'PRIMARY KEY'; + $_fields = explode(',', preg_replace('/^.*\((.+)\).*$/', '$1', $line)); + $obj->fields = array_map(function ($v) { return trim($v, '`'); }, $_fields); - $obj->type = 'PRIMARY'; + $obj->type = 'PRIMARY'; $retval[] = $obj; } @@ -483,12 +483,12 @@ public function _indexData(string $table): array { if (preg_match('/KEY `([^`]+)` \((.+)\)/', $line, $matches)) { - $obj = new \stdClass(); - $obj->name = $matches[1]; - $obj->fields = array_map(function($v) { + $obj = new \stdClass(); + $obj->name = $matches[1]; + $obj->fields = array_map(function ($v) { return trim($v, '`'); }, explode(',', $matches[2])); - $obj->type = $unique ? 'UNIQUE' : 'INDEX'; + $obj->type = $unique ? 'UNIQUE' : 'INDEX'; $retval[] = $obj; } @@ -507,8 +507,8 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _foreignKeyData(string $table): array @@ -522,9 +522,9 @@ public function _foreignKeyData(string $table): array INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS AS rc ON tc.CONSTRAINT_NAME = rc.CONSTRAINT_NAME WHERE - tc.CONSTRAINT_TYPE = '.$this->escape('FOREIGN KEY').' AND - tc.TABLE_SCHEMA = '.$this->escape($this->database).' AND - tc.TABLE_NAME = '.$this->escape($table); + tc.CONSTRAINT_TYPE = ' . $this->escape('FOREIGN KEY') . ' AND + tc.TABLE_SCHEMA = ' . $this->escape($this->database) . ' AND + tc.TABLE_NAME = ' . $this->escape($table); if (($query = $this->query($sql)) === false) { @@ -535,10 +535,10 @@ public function _foreignKeyData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->CONSTRAINT_NAME; - $obj->table_name = $row->TABLE_NAME; - $obj->foreign_table_name = $row->REFERENCED_TABLE_NAME; + $obj = new \stdClass(); + $obj->constraint_name = $row->CONSTRAINT_NAME; + $obj->table_name = $row->TABLE_NAME; + $obj->foreign_table_name = $row->REFERENCED_TABLE_NAME; $retval[] = $obj; } @@ -555,19 +555,22 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error() { - if ( ! empty($this->mysqli->connect_errno)) + if (! empty($this->mysqli->connect_errno)) { return [ - 'code' => $this->mysqli->connect_errno, - 'message' => $this->mysqli->connect_error + 'code' => $this->mysqli->connect_errno, + 'message' => $this->mysqli->connect_error, ]; } - return ['code' => $this->connID->errno, 'message' => $this->connID->error]; + return [ + 'code' => $this->connID->errno, + 'message' => $this->connID->error, + ]; } //-------------------------------------------------------------------- @@ -575,7 +578,7 @@ public function error() /** * Insert ID * - * @return int + * @return integer */ public function insertID() { @@ -587,7 +590,7 @@ public function insertID() /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -601,7 +604,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { @@ -619,7 +622,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index b378675cef3f..67ca601ffa32 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -45,14 +45,14 @@ class Forge extends \CodeIgniter\Database\Forge /** * CREATE DATABASE statement * - * @var string + * @var string */ protected $createDatabaseStr = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s'; /** * DROP CONSTRAINT statement * - * @var string + * @var string */ protected $dropConstraintStr = 'ALTER TABLE %s DROP FOREIGN KEY %s'; @@ -62,14 +62,14 @@ class Forge extends \CodeIgniter\Database\Forge * Whether table keys are created from within the * CREATE TABLE statement. * - * @var bool + * @var boolean */ protected $createTableKeys = true; /** * UNSIGNED support * - * @var array + * @var array */ protected $_unsigned = [ 'TINYINT', @@ -88,8 +88,8 @@ class Forge extends \CodeIgniter\Database\Forge /** * Table Options list which required to be quoted - * - * @var array + * + * @var array */ protected $_quoted_table_options = [ 'COMMENT', @@ -104,7 +104,7 @@ class Forge extends \CodeIgniter\Database\Forge /** * NULL value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $_null = 'NULL'; @@ -113,8 +113,8 @@ class Forge extends \CodeIgniter\Database\Forge /** * CREATE TABLE attributes * - * @param array $attributes Associative array of table attributes - * @return string + * @param array $attributes Associative array of table attributes + * @return string */ protected function _createTableAttributes($attributes) { @@ -125,7 +125,7 @@ protected function _createTableAttributes($attributes) if (is_string($key)) { $sql .= ' ' . strtoupper($key) . ' = '; - + if (in_array(strtoupper($key), $this->_quoted_table_options)) { $sql .= $this->db->escape($attributes[$key]); @@ -137,12 +137,12 @@ protected function _createTableAttributes($attributes) } } - if ( ! empty($this->db->charset) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) + if (! empty($this->db->charset) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) { $sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset); } - if ( ! empty($this->db->DBCollat) && ! strpos($sql, 'COLLATE')) + if (! empty($this->db->DBCollat) && ! strpos($sql, 'COLLATE')) { $sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat); } @@ -155,10 +155,10 @@ protected function _createTableAttributes($attributes) /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition - * @return string|string[] + * @param string $alter_type ALTER type + * @param string $table Table name + * @param mixed $field Column definition + * @return string|string[] */ protected function _alterTable($alter_type, $table, $field) { @@ -168,9 +168,9 @@ protected function _alterTable($alter_type, $table, $field) } $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table); - for ($i = 0, $c = count($field); $i < $c; $i ++ ) + for ($i = 0, $c = count($field); $i < $c; $i ++) { - if ($field[$i]['_literal'] !== FALSE) + if ($field[$i]['_literal'] !== false) { $field[$i] = ($alter_type === 'ADD') ? "\n\tADD " . $field[$i]['_literal'] : "\n\tMODIFY " . $field[$i]['_literal']; } @@ -197,14 +197,14 @@ protected function _alterTable($alter_type, $table, $field) /** * Process column * - * @param array $field - * @return string + * @param array $field + * @return string */ protected function _processColumn($field) { $extra_clause = isset($field['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($field['after']) : ''; - if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) + if (empty($extra_clause) && isset($field['first']) && $field['first'] === true) { $extra_clause = ' FIRST'; } @@ -226,27 +226,27 @@ protected function _processColumn($field) /** * Process indexes * - * @param string $table (ignored) - * @return string + * @param string $table (ignored) + * @return string */ protected function _processIndexes($table) { $sql = ''; - for ($i = 0, $c = count($this->keys); $i < $c; $i ++ ) + for ($i = 0, $c = count($this->keys); $i < $c; $i ++) { if (is_array($this->keys[$i])) { - for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2 ++ ) + for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2 ++) { - if ( ! isset($this->fields[$this->keys[$i][$i2]])) + if (! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } - elseif ( ! isset($this->fields[$this->keys[$i]])) + elseif (! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; diff --git a/system/Database/MySQLi/PreparedQuery.php b/system/Database/MySQLi/PreparedQuery.php index c80bae0714b6..f9f07ddf4587 100644 --- a/system/Database/MySQLi/PreparedQuery.php +++ b/system/Database/MySQLi/PreparedQuery.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\PreparedQueryInterface; use \CodeIgniter\Database\BasePreparedQuery; @@ -49,8 +50,8 @@ class PreparedQuery extends BasePreparedQuery implements PreparedQueryInterface * override this method. * * @param string $sql - * @param array $options Passed to the connection's prepare statement. - * Unused in the MySQLi driver. + * @param array $options Passed to the connection's prepare statement. + * Unused in the MySQLi driver. * * @return mixed */ @@ -60,9 +61,9 @@ public function _prepare(string $sql, array $options = []) // with terminating semicolons. $sql = rtrim($sql, ';'); - if ( ! $this->statement = $this->db->mysqli->prepare($sql)) + if (! $this->statement = $this->db->mysqli->prepare($sql)) { - $this->errorCode = $this->db->mysqli->errno; + $this->errorCode = $this->db->mysqli->errno; $this->errorString = $this->db->mysqli->error; } diff --git a/system/Database/MySQLi/Result.php b/system/Database/MySQLi/Result.php index 490c6af3550e..f7495c6697f3 100644 --- a/system/Database/MySQLi/Result.php +++ b/system/Database/MySQLi/Result.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseResult; use CodeIgniter\Database\ResultInterface; @@ -47,7 +48,7 @@ class Result extends BaseResult implements ResultInterface /** * Gets the number of fields in the result set. * - * @return int + * @return integer */ public function getFieldCount(): int { @@ -82,17 +83,17 @@ public function getFieldNames(): array */ public function getFieldData(): array { - $retval = []; + $retval = []; $fieldData = $this->resultID->fetch_fields(); - for ($i = 0, $c = count($fieldData); $i < $c; $i ++ ) + for ($i = 0, $c = count($fieldData); $i < $c; $i ++) { - $retval[$i] = new \stdClass(); - $retval[$i]->name = $fieldData[$i]->name; - $retval[$i]->type = $fieldData[$i]->type; - $retval[$i]->max_length = $fieldData[$i]->max_length; + $retval[$i] = new \stdClass(); + $retval[$i]->name = $fieldData[$i]->name; + $retval[$i]->type = $fieldData[$i]->type; + $retval[$i]->max_length = $fieldData[$i]->max_length; $retval[$i]->primary_key = (int) ($fieldData[$i]->flags & 2); - $retval[$i]->default = $fieldData[$i]->def; + $retval[$i]->default = $fieldData[$i]->def; } return $retval; @@ -119,7 +120,7 @@ public function freeResult() * internally before fetching results to make sure the result set * starts at zero. * - * @param int $n + * @param integer $n * * @return mixed */ diff --git a/system/Database/MySQLi/Utils.php b/system/Database/MySQLi/Utils.php index af0ca54da224..fb27f811718b 100644 --- a/system/Database/MySQLi/Utils.php +++ b/system/Database/MySQLi/Utils.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -45,14 +45,14 @@ class Utils extends \CodeIgniter\Database\BaseUtils /** * List databases statement * - * @var string + * @var string */ protected $listDatabases = 'SHOW DATABASES'; /** * OPTIMIZE TABLE statement * - * @var string + * @var string */ protected $optimizeTable = 'OPTIMIZE TABLE %s'; diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php index 55e777ded06b..c697c6f23dca 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseBuilder; use \CodeIgniter\Database\Exceptions\DatabaseException; @@ -49,25 +50,28 @@ class Builder extends BaseBuilder * * @var array */ - protected $randomKeyword = ['RANDOM()', 'RANDOM()']; + protected $randomKeyword = [ + 'RANDOM()', + 'RANDOM()', + ]; //-------------------------------------------------------------------- /** * ORDER BY * - * @param string $orderby - * @param string $direction ASC, DESC or RANDOM - * @param bool $escape + * @param string $orderby + * @param string $direction ASC, DESC or RANDOM + * @param boolean $escape * - * @return BaseBuilder + * @return BaseBuilder */ public function orderBy($orderby, $direction = '', $escape = null) { $direction = strtoupper(trim($direction)); if ($direction === 'RANDOM') { - if ( ! is_float($orderby) && ctype_digit((string) $orderby)) + if (! is_float($orderby) && ctype_digit((string) $orderby)) { $orderby = (float) ($orderby > 1 ? "0.{$orderby}" : $orderby); } @@ -77,9 +81,9 @@ public function orderBy($orderby, $direction = '', $escape = null) $this->db->simpleQuery("SET SEED {$orderby}"); } - $orderby = $this->randomKeyword[0]; + $orderby = $this->randomKeyword[0]; $direction = ''; - $escape = false; + $escape = false; } return parent::orderBy($orderby, $direction, $escape); @@ -90,10 +94,10 @@ public function orderBy($orderby, $direction = '', $escape = null) /** * Increments a numeric column by the specified value. * - * @param string $column - * @param int $value + * @param string $column + * @param integer $value * - * @return bool + * @return boolean */ public function increment(string $column, int $value = 1) { @@ -109,10 +113,10 @@ public function increment(string $column, int $value = 1) /** * Decrements a numeric column by the specified value. * - * @param string $column - * @param int $value + * @param string $column + * @param integer $value * - * @return bool + * @return boolean */ public function decrement(string $column, int $value = 1) { @@ -133,13 +137,12 @@ public function decrement(string $column, int $value = 1) * we simply do a DELETE and an INSERT on the first key/value * combo, assuming that it's either the primary key or a unique key. * - * @param array $set An associative array of insert values - * @param bool $returnSQL + * @param array $set An associative array of insert values + * @param boolean $returnSQL * - * @return bool TRUE on success, FALSE on failure - * @throws DatabaseException + * @return boolean TRUE on success, FALSE on failure + * @throws DatabaseException * @internal param true $bool returns the generated SQL, false executes the query. - * */ public function replace($set = null, $returnSQL = false) { @@ -159,12 +162,12 @@ public function replace($set = null, $returnSQL = false) $table = $this->QBFrom[0]; - $set = $this->binds; - $keys = array_keys($set); + $set = $this->binds; + $keys = array_keys($set); $values = array_values($set); $builder = $this->db->table($table); - $exists = $builder->where("$keys[0] = $values[0]", null, false)->get()->getFirstRow(); + $exists = $builder->where("$keys[0] = $values[0]", null, false)->get()->getFirstRow(); if (empty($exists)) { @@ -189,21 +192,20 @@ public function replace($set = null, $returnSQL = false) * * Compiles a delete string and runs the query * - * @param string $where - * @param null $limit - * @param bool $reset_data - * @param bool $returnSQL + * @param string $where + * @param null $limit + * @param boolean $reset_data + * @param boolean $returnSQL * - * @return mixed - * @throws DatabaseException + * @return mixed + * @throws DatabaseException * @internal param the $mixed where clause * @internal param the $mixed limit clause * @internal param $bool - * */ public function delete($where = '', $limit = null, $reset_data = true, $returnSQL = false) { - if ( ! empty($limit) || ! empty($this->QBLimit)) + if (! empty($limit) || ! empty($this->QBLimit)) { throw new DatabaseException('PostgreSQL does not allow LIMITs on DELETE queries.'); } @@ -218,9 +220,9 @@ public function delete($where = '', $limit = null, $reset_data = true, $returnSQ * * Generates a platform-specific LIMIT clause. * - * @param string $sql SQL Query + * @param string $sql SQL Query * - * @return string + * @return string */ protected function _limit($sql) { @@ -237,15 +239,14 @@ protected function _limit($sql) * @param string $table * @param array $values * - * @return string - * @throws DatabaseException + * @return string + * @throws DatabaseException * @internal param the $string table name * @internal param the $array update data - * */ protected function _update($table, $values) { - if ( ! empty($this->QBLimit)) + if (! empty($this->QBLimit)) { throw new DatabaseException('Postgres does not support LIMITs with UPDATE queries.'); } @@ -261,11 +262,11 @@ protected function _update($table, $values) * * Generates a platform-specific batch update string from the supplied data * - * @param string $table Table name - * @param array $values Update data - * @param string $index WHERE key + * @param string $table Table name + * @param array $values Update data + * @param string $index WHERE key * - * @return string + * @return string */ protected function _updateBatch($table, $values, $index) { @@ -303,9 +304,9 @@ protected function _updateBatch($table, $values, $index) * * Generates a platform-specific delete string from the supplied data * - * @param string $table The table name + * @param string $table The table name * - * @return string + * @return string */ protected function _delete($table) { @@ -323,9 +324,9 @@ protected function _delete($table) * If the database does not support the truncate() command, * then this method maps to 'DELETE FROM table' * - * @param string $table The table name + * @param string $table The table name * - * @return string + * @return string */ protected function _truncate($table) { @@ -346,7 +347,7 @@ protected function _truncate($table) * @param string $column * @param string|null $not * @param string $bind - * @param bool $insensitiveSearch + * @param boolean $insensitiveSearch * * @return string $like_statement */ diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index cb30f5b15e15..f35271853288 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\Exceptions\DatabaseException; @@ -64,7 +65,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Identifier escape character * - * @var string + * @var string */ public $escapeChar = '"'; @@ -73,7 +74,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * @return mixed */ public function connect($persistent = false) @@ -167,7 +168,7 @@ public function getVersion() return $this->dataCache['version']; } - if ( ! $this->connID or ( $pgVersion = pg_version($this->connID)) === false) + if (! $this->connID || ( $pgVersion = pg_version($this->connID)) === false) { $this->initialize(); } @@ -235,8 +236,8 @@ public function escape($str) /** * Platform-dependant string escape * - * @param string $str - * @return string + * @param string $str + * @return string */ protected function _escapeString(string $str): string { @@ -253,7 +254,7 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ @@ -285,7 +286,7 @@ protected function _listColumns(string $table = ''): string return 'SELECT "column_name" FROM "information_schema"."columns" WHERE LOWER("table_name") = ' - . $this->escape($this->DBPrefix.strtolower($table)); + . $this->escape($this->DBPrefix . strtolower($table)); } //-------------------------------------------------------------------- @@ -293,8 +294,8 @@ protected function _listColumns(string $table = ''): string /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array @@ -311,12 +312,12 @@ public function _fieldData(string $table): array $query = $query->getResultObject(); $retval = []; - for ($i = 0, $c = count($query); $i < $c; $i ++ ) + for ($i = 0, $c = count($query); $i < $c; $i ++) { - $retval[$i] = new \stdClass(); - $retval[$i]->name = $query[$i]->column_name; - $retval[$i]->type = $query[$i]->data_type; - $retval[$i]->default = $query[$i]->column_default; + $retval[$i] = new \stdClass(); + $retval[$i]->name = $query[$i]->column_name; + $retval[$i]->type = $query[$i]->data_type; + $retval[$i]->default = $query[$i]->column_default; $retval[$i]->max_length = $query[$i]->character_maximum_length > 0 ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision; } @@ -328,8 +329,8 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _indexData(string $table): array @@ -348,10 +349,10 @@ public function _indexData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->name = $row->indexname; - $_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); - $obj->fields = array_map(function($v) { + $obj = new \stdClass(); + $obj->name = $row->indexname; + $_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); + $obj->fields = array_map(function ($v) { return trim($v); }, $_fields); @@ -361,11 +362,11 @@ public function _indexData(string $table): array } else { - $obj->type = (strpos($row->indexdef, 'CREATE UNIQUE') === 0) ? 'UNIQUE' :'INDEX'; + $obj->type = (strpos($row->indexdef, 'CREATE UNIQUE') === 0) ? 'UNIQUE' : 'INDEX'; } $retval[] = $obj; - } + } return $retval; } @@ -375,8 +376,8 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _foreignKeyData(string $table): array @@ -390,8 +391,8 @@ public function _foreignKeyData(string $table): array ON tc.constraint_name = kcu.constraint_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name - WHERE constraint_type = '.$this->escape('FOREIGN KEY').' AND - tc.table_name = '.$this->escape($table); + WHERE constraint_type = ' . $this->escape('FOREIGN KEY') . ' AND + tc.table_name = ' . $this->escape($table); if (($query = $this->query($sql)) === false) { @@ -402,11 +403,11 @@ public function _foreignKeyData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->constraint_name; - $obj->table_name = $row->table_name; + $obj = new \stdClass(); + $obj->constraint_name = $row->constraint_name; + $obj->table_name = $row->table_name; $obj->foreign_table_name = $row->foreign_table_name; - $retval[] = $obj; + $retval[] = $obj; } return $retval; @@ -421,13 +422,13 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error() { return [ - 'code' => '', - 'message' => pg_last_error($this->connID) + 'code' => '', + 'message' => pg_last_error($this->connID), ]; } @@ -436,7 +437,7 @@ public function error() /** * Insert ID * - * @return int + * @return integer */ public function insertID() { @@ -444,7 +445,7 @@ public function insertID() // 'server' key is only available since PostgreSQL 7.4 $v = $v['server'] ?? 0; - $table = func_num_args() > 0 ? func_get_arg(0) : null; + $table = func_num_args() > 0 ? func_get_arg(0) : null; $column = func_num_args() > 1 ? func_get_arg(1) : null; if ($table === null && $v >= '8.1') @@ -455,10 +456,10 @@ public function insertID() { if ($column !== null && $v >= '8.0') { - $sql = "SELECT pg_get_serial_sequence('{$table}', '{$column}') AS seq"; + $sql = "SELECT pg_get_serial_sequence('{$table}', '{$column}') AS seq"; $query = $this->query($sql); $query = $query->getRow(); - $seq = $query->seq; + $seq = $query->seq; } else { @@ -497,7 +498,7 @@ protected function buildDSN() $this->hostname === '' || $this->DSN = "host={$this->hostname} "; - if ( ! empty($this->port) && ctype_digit($this->port)) + if (! empty($this->port) && ctype_digit($this->port)) { $this->DSN .= "port={$this->port} "; } @@ -535,8 +536,8 @@ protected function buildDSN() /** * Set client encoding * - * @param string $charset The client encoding to which the data will be converted. - * @return bool + * @param string $charset The client encoding to which the data will be converted. + * @return boolean */ protected function setClientEncoding($charset) { @@ -548,7 +549,7 @@ protected function setClientEncoding($charset) /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -560,7 +561,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { @@ -572,7 +573,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { diff --git a/system/Database/Postgre/Forge.php b/system/Database/Postgre/Forge.php index 446aa65f48a7..1a262bb3719e 100644 --- a/system/Database/Postgre/Forge.php +++ b/system/Database/Postgre/Forge.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -45,32 +45,31 @@ class Forge extends \CodeIgniter\Database\Forge /** * DROP CONSTRAINT statement * - * @var string + * @var string */ protected $dropConstraintStr = 'ALTER TABLE %s DROP CONSTRAINT %s'; - /** * UNSIGNED support * - * @var array + * @var array */ protected $_unsigned = [ - 'INT2' => 'INTEGER', - 'SMALLINT' => 'INTEGER', - 'INT' => 'BIGINT', - 'INT4' => 'BIGINT', - 'INTEGER' => 'BIGINT', - 'INT8' => 'NUMERIC', - 'BIGINT' => 'NUMERIC', - 'REAL' => 'DOUBLE PRECISION', - 'FLOAT' => 'DOUBLE PRECISION' + 'INT2' => 'INTEGER', + 'SMALLINT' => 'INTEGER', + 'INT' => 'BIGINT', + 'INT4' => 'BIGINT', + 'INTEGER' => 'BIGINT', + 'INT8' => 'NUMERIC', + 'BIGINT' => 'NUMERIC', + 'REAL' => 'DOUBLE PRECISION', + 'FLOAT' => 'DOUBLE PRECISION', ]; /** * NULL value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $_null = 'NULL'; @@ -79,8 +78,8 @@ class Forge extends \CodeIgniter\Database\Forge /** * CREATE TABLE attributes * - * @param array $attributes Associative array of table attributes - * @return string + * @param array $attributes Associative array of table attributes + * @return string */ protected function _createTableAttributes($attributes) { @@ -92,11 +91,11 @@ protected function _createTableAttributes($attributes) /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alter_type ALTER type + * @param string $table Table name + * @param mixed $field Column definition * - * @return string|array + * @return string|array */ protected function _alterTable($alter_type, $table, $field) { @@ -105,9 +104,9 @@ protected function _alterTable($alter_type, $table, $field) return parent::_alterTable($alter_type, $table, $field); } - $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table); + $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table); $sqls = []; - for ($i = 0, $c = count($field); $i < $c; $i ++ ) + for ($i = 0, $c = count($field); $i < $c; $i ++) { if ($field[$i]['_literal'] !== false) { @@ -120,7 +119,7 @@ protected function _alterTable($alter_type, $table, $field) . " TYPE {$field[$i]['type']}{$field[$i]['length']}"; } - if ( ! empty($field[$i]['default'])) + if (! empty($field[$i]['default'])) { $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field[$i]['name']) . " SET DEFAULT {$field[$i]['default']}"; @@ -132,13 +131,13 @@ protected function _alterTable($alter_type, $table, $field) . ($field[$i]['null'] === true ? ' DROP' : ' SET') . ' NOT NULL'; } - if ( ! empty($field[$i]['new_name'])) + if (! empty($field[$i]['new_name'])) { $sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($field[$i]['name']) . ' TO ' . $this->db->escapeIdentifiers($field[$i]['new_name']); } - if ( ! empty($field[$i]['comment'])) + if (! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN' . $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($field[$i]['name']) @@ -149,13 +148,13 @@ protected function _alterTable($alter_type, $table, $field) return $sqls; } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * Process column * - * @param array $field - * @return string + * @param array $field + * @return string */ protected function _processColumn($field) { @@ -167,7 +166,6 @@ protected function _processColumn($field) . $field['unique']; } - //-------------------------------------------------------------------- /** @@ -175,9 +173,9 @@ protected function _processColumn($field) * * Performs a data type mapping between different databases. * - * @param array &$attributes + * @param array &$attributes * - * @return void + * @return void */ protected function _attributeType(&$attributes) { @@ -190,11 +188,11 @@ protected function _attributeType(&$attributes) switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': - $attributes['TYPE'] = 'SMALLINT'; + $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = false; return; case 'MEDIUMINT': - $attributes['TYPE'] = 'INTEGER'; + $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = false; return; case 'DATETIME': @@ -209,14 +207,14 @@ protected function _attributeType(&$attributes) /** * Field attribute AUTO_INCREMENT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeAutoIncrement(&$attributes, &$field) { - if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true) + if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true) { $field['type'] = $field['type'] === 'NUMERIC' ? 'BIGSERIAL' : 'SERIAL'; } @@ -229,11 +227,11 @@ protected function _attributeAutoIncrement(&$attributes, &$field) * * Generates a platform-specific DROP TABLE string * - * @param string $table Table name - * @param bool $if_exists Whether to add an IF EXISTS condition - * @param bool $cascade + * @param string $table Table name + * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param boolean $cascade * - * @return string + * @return string */ protected function _dropTable($table, $if_exists, $cascade) { diff --git a/system/Database/Postgre/PreparedQuery.php b/system/Database/Postgre/PreparedQuery.php index bcb95948fccc..874dc539b6cf 100644 --- a/system/Database/Postgre/PreparedQuery.php +++ b/system/Database/Postgre/PreparedQuery.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\PreparedQueryInterface; use \CodeIgniter\Database\BasePreparedQuery; @@ -52,6 +53,7 @@ class PreparedQuery extends BasePreparedQuery implements PreparedQueryInterface /** * The result resource from a successful * pg_exec. Or false. + * * @var */ protected $result; @@ -66,8 +68,8 @@ class PreparedQuery extends BasePreparedQuery implements PreparedQueryInterface * override this method. * * @param string $sql - * @param array $options Passed to the connection's prepare statement. - * Unused in the MySQLi driver. + * @param array $options Passed to the connection's prepare statement. + * Unused in the MySQLi driver. * * @return mixed */ @@ -81,9 +83,9 @@ public function _prepare(string $sql, array $options = []) // than what was put in. $this->query->setQuery($sql); - if ( ! $this->statement = pg_prepare($this->db->connID, $this->name, $sql)) + if (! $this->statement = pg_prepare($this->db->connID, $this->name, $sql)) { - $this->errorCode = 0; + $this->errorCode = 0; $this->errorString = pg_last_error($this->db->connID); } @@ -98,7 +100,7 @@ public function _prepare(string $sql, array $options = []) * * @param array $data * - * @return bool + * @return boolean */ public function _execute($data) { @@ -139,7 +141,7 @@ public function parameterize(string $sql): string // Track our current value $count = 0; - $sql = preg_replace_callback('/\?/', function($matches) use (&$count) { + $sql = preg_replace_callback('/\?/', function ($matches) use (&$count) { $count ++; return "\${$count}"; }, $sql); diff --git a/system/Database/Postgre/Result.php b/system/Database/Postgre/Result.php index 2f9c8458a3f5..545ccb1ddc06 100644 --- a/system/Database/Postgre/Result.php +++ b/system/Database/Postgre/Result.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseResult; use CodeIgniter\Database\ResultInterface; @@ -47,7 +48,7 @@ class Result extends BaseResult implements ResultInterface /** * Gets the number of fields in the result set. * - * @return int + * @return integer */ public function getFieldCount(): int { @@ -64,7 +65,7 @@ public function getFieldCount(): int public function getFieldNames(): array { $fieldNames = []; - for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++ ) + for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++) { $fieldNames[] = pg_field_name($this->resultID, $i); } @@ -83,11 +84,11 @@ public function getFieldData(): array { $retval = []; - for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++ ) + for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++) { - $retval[$i] = new \stdClass(); - $retval[$i]->name = pg_field_name($this->resultID, $i); - $retval[$i]->type = pg_field_type($this->resultID, $i); + $retval[$i] = new \stdClass(); + $retval[$i]->name = pg_field_name($this->resultID, $i); + $retval[$i]->type = pg_field_type($this->resultID, $i); $retval[$i]->max_length = pg_field_size($this->resultID, $i); // $retval[$i]->primary_key = (int)($fieldData[$i]->flags & 2); // $retval[$i]->default = $fieldData[$i]->def; @@ -119,7 +120,7 @@ public function freeResult() * internally before fetching results to make sure the result set * starts at zero. * - * @param int $n + * @param integer $n * * @return mixed */ diff --git a/system/Database/Postgre/Utils.php b/system/Database/Postgre/Utils.php index 61bf40f34b05..67f6188f8860 100644 --- a/system/Database/Postgre/Utils.php +++ b/system/Database/Postgre/Utils.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -45,14 +45,14 @@ class Utils extends \CodeIgniter\Database\BaseUtils /** * List databases statement * - * @var string + * @var string */ protected $listDatabases = 'SELECT datname FROM pg_database'; /** * OPTIMIZE TABLE statement * - * @var string + * @var string */ protected $optimizeTable = 'REINDEX TABLE %s'; diff --git a/system/Database/PreparedQueryInterface.php b/system/Database/PreparedQueryInterface.php index 18f20eff6c54..db3a750bb826 100644 --- a/system/Database/PreparedQueryInterface.php +++ b/system/Database/PreparedQueryInterface.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + interface PreparedQueryInterface { @@ -55,7 +56,7 @@ public function execute(...$data); * info necessary to execute the query later. * * @param string $sql - * @param array $options Passed to the connection's prepare statement. + * @param array $options Passed to the connection's prepare statement. * * @return mixed */ @@ -82,7 +83,7 @@ public function getQueryString(): string; /** * Returns the error code created while executing this statement. * - * @return int + * @return integer */ public function getErrorCode(): int; diff --git a/system/Database/Query.php b/system/Database/Query.php index 9cafb1740596..2a382c43887d 100644 --- a/system/Database/Query.php +++ b/system/Database/Query.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -70,7 +70,7 @@ class Query implements QueryInterface * * Character used to identify values in a prepared statement. * - * @var string + * @var string */ protected $bindMarker = '?'; @@ -93,7 +93,7 @@ class Query implements QueryInterface /** * The error code, if any. * - * @var int + * @var integer */ protected $errorCode; @@ -130,7 +130,7 @@ public function __construct(&$db) * Sets the raw query string to use for this statement. * * @param string $sql - * @param array $binds + * @param array $binds * * @return mixed */ @@ -138,7 +138,7 @@ public function setQuery(string $sql, $binds = null) { $this->originalQueryString = $sql; - if ( ! is_null($binds)) + if (! is_null($binds)) { $this->binds = $binds; } @@ -213,8 +213,8 @@ public function setDuration(float $start, float $end = null) /** * Returns the start time in seconds with microseconds. * - * @param bool $returnRaw - * @param int $decimals + * @param boolean $returnRaw + * @param integer $decimals * * @return mixed */ @@ -233,7 +233,7 @@ public function getStartTime($returnRaw = false, int $decimals = 6) * Returns the duration of this query during execution, or null if * the query has not been executed yet. * - * @param int $decimals The accuracy of the returned time. + * @param integer $decimals The accuracy of the returned time. * * @return mixed */ @@ -247,14 +247,14 @@ public function getDuration(int $decimals = 6) /** * Stores the error description that happened for this query. * - * @param int $code - * @param string $error + * @param integer $code + * @param string $error * * @return Query */ public function setError(int $code, string $error) { - $this->errorCode = $code; + $this->errorCode = $code; $this->errorString = $error; return $this; @@ -265,7 +265,7 @@ public function setError(int $code, string $error) /** * Reports whether this statement created an error not. * - * @return bool + * @return boolean */ public function hasError(): bool { @@ -277,7 +277,7 @@ public function hasError(): bool /** * Returns the error code created while executing this statement. * - * @return int + * @return integer */ public function getErrorCode(): int { @@ -301,7 +301,7 @@ public function getErrorMessage(): string /** * Determines if the statement is a write-type query or not. * - * @return bool + * @return boolean */ public function isWriteType(): bool { @@ -359,20 +359,20 @@ protected function compileBinds() return; } - if ( ! is_array($this->binds)) + if (! is_array($this->binds)) { - $binds = [$this->binds]; + $binds = [$this->binds]; $bindCount = 1; } else { - $binds = $this->binds; + $binds = $this->binds; $bindCount = count($binds); } // Reverse the binds so that duplicate named binds // will be processed prior to the original binds. - if ( ! is_numeric(key(array_slice($binds, 0, 1)))) + if (! is_numeric(key(array_slice($binds, 0, 1)))) { $binds = array_reverse($binds); } @@ -396,8 +396,9 @@ protected function compileBinds() /** * Match bindings - * @param string $sql - * @param array $binds + * + * @param string $sql + * @param array $binds * @return string */ protected function matchNamedBinds(string $sql, array $binds) @@ -418,7 +419,7 @@ protected function matchNamedBinds(string $sql, array $binds) $replacers[":{$placeholder}:"] = $escapedValue; -// $sql = preg_replace('|:' . $placeholder . '(?!\w)|', $escapedValue, $sql); + // $sql = preg_replace('|:' . $placeholder . '(?!\w)|', $escapedValue, $sql); } $sql = strtr($sql, $replacers); @@ -430,10 +431,11 @@ protected function matchNamedBinds(string $sql, array $binds) /** * Match bindings - * @param string $sql - * @param array $binds - * @param int $bindCount - * @param int $ml + * + * @param string $sql + * @param array $binds + * @param integer $bindCount + * @param integer $ml * @return string */ protected function matchSimpleBinds(string $sql, array $binds, int $bindCount, int $ml) @@ -464,7 +466,8 @@ protected function matchSimpleBinds(string $sql, array $binds, int $bindCount, i $escapedValue = '(' . implode(',', $escapedValue) . ')'; } $sql = substr_replace($sql, $escapedValue, $matches[0][$c][1], $ml); - } while ($c !== 0); + } + while ($c !== 0); return $sql; } diff --git a/system/Database/QueryInterface.php b/system/Database/QueryInterface.php index cae2a5d42556..e158bae55ab3 100644 --- a/system/Database/QueryInterface.php +++ b/system/Database/QueryInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -51,7 +51,7 @@ interface QueryInterface * Sets the raw query string to use for this statement. * * @param string $sql - * @param array $binds + * @param array $binds * * @return mixed */ @@ -87,7 +87,7 @@ public function setDuration(float $start, float $end = null); * Returns the duration of this query during execution, or null if * the query has not been executed yet. * - * @param int $decimals The accuracy of the returned time. + * @param integer $decimals The accuracy of the returned time. * * @return mixed */ @@ -98,8 +98,8 @@ public function getDuration(int $decimals = 6); /** * Stores the error description that happened for this query. * - * @param int $code - * @param string $error + * @param integer $code + * @param string $error */ public function setError(int $code, string $error); @@ -108,7 +108,7 @@ public function setError(int $code, string $error); /** * Reports whether this statement created an error not. * - * @return bool + * @return boolean */ public function hasError(): bool; @@ -117,7 +117,7 @@ public function hasError(): bool; /** * Returns the error code created while executing this statement. * - * @return int + * @return integer */ public function getErrorCode(): int; @@ -135,7 +135,7 @@ public function getErrorMessage(): string; /** * Determines if the statement is a write-type query or not. * - * @return bool + * @return boolean */ public function isWriteType(): bool; diff --git a/system/Database/ResultInterface.php b/system/Database/ResultInterface.php index 7f42e3f06ced..da3f0b06b205 100644 --- a/system/Database/ResultInterface.php +++ b/system/Database/ResultInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -58,7 +58,7 @@ public function getResult($type = 'object'): array; /** * Returns the results as an array of custom objects. * - * @param string $className The name of the class to use. + * @param string $className The name of the class to use. * * @return mixed */ @@ -94,8 +94,8 @@ public function getResultObject(): array; * * If row doesn't exist, returns null. * - * @param int $n The index of the results to return - * @param string $type The type of result object. 'array', 'object' or class name. + * @param integer $n The index of the results to return + * @param string $type The type of result object. 'array', 'object' or class name. * * @return mixed */ @@ -108,8 +108,8 @@ public function getRow($n = 0, $type = 'object'); * * If row doesn't exists, returns null. * - * @param int $n - * @param string $className + * @param integer $n + * @param string $className * * @return mixed */ @@ -122,7 +122,7 @@ public function getCustomRowObject($n, string $className); * * If row doesn't exist, returns null. * - * @param int $n + * @param integer $n * * @return mixed */ @@ -135,7 +135,7 @@ public function getRowArray($n = 0); * * If row doesn't exist, returns null. * - * @param int $n + * @param integer $n * * @return mixed */ @@ -146,7 +146,7 @@ public function getRowObject($n = 0); /** * Assigns an item into a particular column slot. * - * @param $key + * @param $key * @param null $value * * @return mixed @@ -213,7 +213,7 @@ public function getUnbufferedRow($type = 'object'); /** * Gets the number of fields in the result set. * - * @return int + * @return integer */ public function getFieldCount(): int; @@ -251,7 +251,7 @@ public function freeResult(); * internally before fetching results to make sure the result set * starts at zero. * - * @param int $n + * @param integer $n * * @return mixed */ diff --git a/system/Database/SQLite3/Builder.php b/system/Database/SQLite3/Builder.php index 1c6f4c2eed07..9ffe98fc63b4 100644 --- a/system/Database/SQLite3/Builder.php +++ b/system/Database/SQLite3/Builder.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseBuilder; /** @@ -43,65 +44,65 @@ class Builder extends BaseBuilder { - /** - * Identifier escape character - * - * @var string - */ - protected $escapeChar = '`'; + /** + * Identifier escape character + * + * @var string + */ + protected $escapeChar = '`'; /** * Default installs of SQLite typically do not * support limiting delete clauses. * - * @var bool + * @var boolean */ - protected $canLimitDeletes = false; + protected $canLimitDeletes = false; /** * Default installs of SQLite do no support * limiting update queries in combo with WHERE. * - * @var bool + * @var boolean */ - protected $canLimitWhereUpdates = false; + protected $canLimitWhereUpdates = false; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Replace statement - * - * Generates a platform-specific replace string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * - * @return string - */ - protected function _replace($table, $keys, $values) - { - return 'INSERT OR '.parent::_replace($table, $keys, $values); - } + /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @param string the table name + * @param array the insert keys + * @param array the insert values + * + * @return string + */ + protected function _replace($table, $keys, $values) + { + return 'INSERT OR ' . parent::_replace($table, $keys, $values); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Truncate statement - * - * Generates a platform-specific truncate string from the supplied data - * - * If the database does not support the TRUNCATE statement, - * then this method maps to 'DELETE FROM table' - * - * @param string $table - * @return string - */ - protected function _truncate($table) - { - return 'DELETE FROM '.$table; - } + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * + * If the database does not support the TRUNCATE statement, + * then this method maps to 'DELETE FROM table' + * + * @param string $table + * @return string + */ + protected function _truncate($table) + { + return 'DELETE FROM ' . $table; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/system/Database/SQLite3/Connection.php b/system/Database/SQLite3/Connection.php index 4c2cd9bccc5a..1e1db6fe15b5 100644 --- a/system/Database/SQLite3/Connection.php +++ b/system/Database/SQLite3/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\Exceptions\DatabaseException; @@ -48,7 +49,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Database driver * - * @var string + * @var string */ public $DBDriver = 'SQLite3'; @@ -57,23 +58,26 @@ class Connection extends BaseConnection implements ConnectionInterface /** * ORDER BY random keyword * - * @var array + * @var array */ - protected $_random_keyword = ['RANDOM()', 'RANDOM()']; + protected $_random_keyword = [ + 'RANDOM()', + 'RANDOM()', + ]; //-------------------------------------------------------------------- /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function connect($persistent = false) { - if ($persistent and $this->db->DBDebug) + if ($persistent && $this->db->DBDebug) { throw new DatabaseException('SQLite3 doesn\'t support persistent connections.'); } @@ -82,9 +86,10 @@ public function connect($persistent = false) return (! $this->password) ? new \SQLite3($this->database) : new \SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password); - } catch (\Exception $e) + } + catch (\Exception $e) { - throw new DatabaseException('SQLite3 error: '.$e->getMessage()); + throw new DatabaseException('SQLite3 error: ' . $e->getMessage()); } } @@ -149,13 +154,12 @@ public function getVersion() //-------------------------------------------------------------------- - /** * Execute the query * - * @param string $sql + * @param string $sql * - * @return mixed \SQLite3Result object or bool + * @return mixed \SQLite3Result object or bool */ public function execute($sql) { @@ -181,9 +185,9 @@ public function affectedRows(): int /** * Platform-dependant string escape * - * @param string $str + * @param string $str * - * @return string + * @return string */ protected function _escapeString(string $str): string { @@ -195,15 +199,15 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ protected function _listTables($prefixLimit = false): string { return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\'' - .(($prefixLimit !== false && $this->DBPrefix != '') - ? ' AND "NAME" LIKE \''.$this->escapeLikeString($this->DBPrefix).'%\' '.sprintf($this->likeEscapeStr, + . (($prefixLimit !== false && $this->DBPrefix !== '') + ? ' AND "NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . '%\' ' . sprintf($this->likeEscapeStr, $this->likeEscapeChar) : ''); } @@ -219,14 +223,13 @@ protected function _listTables($prefixLimit = false): string */ protected function _listColumns(string $table = ''): string { - return 'PRAGMA TABLE_INFO('.$this->protectIdentifiers($table, true, null, false).')'; + return 'PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')'; } - /** * Fetch Field Names * - * @param string $table Table name + * @param string $table Table name * * @return array|false * @throws DatabaseException @@ -254,7 +257,7 @@ public function getFieldNames($table) return false; } - $query = $this->query($sql); + $query = $this->query($sql); $this->dataCache['field_names'][$table] = []; foreach ($query->getResultArray() as $row) @@ -289,18 +292,17 @@ public function getFieldNames($table) //-------------------------------------------------------------------- - /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array { - if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protectIdentifiers($table, true, null, - false).')')) === false) + if (($query = $this->query('PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, + false) . ')')) === false) { throw new DatabaseException(lang('Database.failGetFieldData')); } @@ -328,15 +330,15 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _indexData(string $table): array { // Get indexes // Don't use PRAGMA index_list, so we can preserve index order - $sql = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=".$this->escape(strtolower($table)); + $sql = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=" . $this->escape(strtolower($table)); if (($query = $this->query($sql)) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); @@ -351,7 +353,7 @@ public function _indexData(string $table): array // Get fields for index $obj->fields = []; - if (($fields = $this->query('PRAGMA index_info('.$this->escape(strtolower($row->name)).')')) === false) + if (($fields = $this->query('PRAGMA index_info(' . $this->escape(strtolower($row->name)) . ')')) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); } @@ -373,8 +375,8 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] */ public function _foreignKeyData(string $table): array { @@ -398,9 +400,9 @@ public function _foreignKeyData(string $table): array foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->from.' to '. $row->table.'.'.$row->to; - $obj->table_name = $table; + $obj = new \stdClass(); + $obj->constraint_name = $row->from . ' to ' . $row->table . '.' . $row->to; + $obj->table_name = $table; $obj->foreign_table_name = $row->table; $retval[] = $obj; @@ -419,11 +421,14 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error(): array { - return ['code' => $this->connID->lastErrorCode(), 'message' => $this->connID->lastErrorMsg()]; + return [ + 'code' => $this->connID->lastErrorCode(), + 'message' => $this->connID->lastErrorMsg(), + ]; } //-------------------------------------------------------------------- @@ -431,7 +436,7 @@ public function error(): array /** * Insert ID * - * @return int + * @return integer */ public function insertID(): int { @@ -443,7 +448,7 @@ public function insertID(): int /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -455,7 +460,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { @@ -467,7 +472,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { @@ -479,7 +484,7 @@ protected function _transRollback(): bool /** * Determines if the statement is a write-type query or not. * - * @return bool + * @return boolean */ public function isWriteType($sql): bool { @@ -494,11 +499,11 @@ public function isWriteType($sql): bool * Checks to see if the current install supports Foreign Keys * and has them enabled. * - * @return bool + * @return boolean */ protected function supportsForeignKeys(): bool { - $result = $this->simpleQuery("PRAGMA foreign_keys"); + $result = $this->simpleQuery('PRAGMA foreign_keys'); return (bool)$result; } diff --git a/system/Database/SQLite3/Forge.php b/system/Database/SQLite3/Forge.php index 8de90fc74e3e..f8c13b9bb065 100644 --- a/system/Database/SQLite3/Forge.php +++ b/system/Database/SQLite3/Forge.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -47,14 +47,14 @@ class Forge extends \CodeIgniter\Database\Forge /** * UNSIGNED support * - * @var bool|array + * @var boolean|array */ protected $_unsigned = false; /** * NULL value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $_null = 'NULL'; @@ -62,7 +62,6 @@ class Forge extends \CodeIgniter\Database\Forge /** * Constructor. - * */ public function __construct($db) { @@ -80,9 +79,9 @@ public function __construct($db) /** * Create database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean */ public function createDatabase($db_name): bool { @@ -96,9 +95,9 @@ public function createDatabase($db_name): bool /** * Drop database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean * @throws \CodeIgniter\DatabaseException */ public function dropDatabase($db_name): bool @@ -143,13 +142,13 @@ public function dropDatabase($db_name): bool /** * ALTER TABLE * - * @todo implement drop_column(), modify_column() + * @todo implement drop_column(), modify_column() * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alter_type ALTER type + * @param string $table Table name + * @param mixed $field Column definition * - * @return string|array + * @return string|array */ protected function _alterTable($alter_type, $table, $field) { @@ -166,18 +165,18 @@ protected function _alterTable($alter_type, $table, $field) /** * Process column * - * @param array $field + * @param array $field * - * @return string + * @return string */ protected function _processColumn($field) { return $this->db->escapeIdentifiers($field['name']) - .' '.$field['type'] - .$field['auto_increment'] - .$field['null'] - .$field['unique'] - .$field['default']; + . ' ' . $field['type'] + . $field['auto_increment'] + . $field['null'] + . $field['unique'] + . $field['default']; } //-------------------------------------------------------------------- @@ -185,9 +184,9 @@ protected function _processColumn($field) /** * Process indexes * - * @param string $table + * @param string $table * - * @return array + * @return array */ protected function _processIndexes($table) { @@ -211,15 +210,15 @@ protected function _processIndexes($table) if (in_array($i, $this->uniqueKeys)) { - $sqls[] = 'CREATE UNIQUE INDEX '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' ON '.$this->db->escapeIdentifiers($table) - .' ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'CREATE UNIQUE INDEX ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' ON ' . $this->db->escapeIdentifiers($table) + . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; continue; } - $sqls[] = 'CREATE INDEX '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' ON '.$this->db->escapeIdentifiers($table) - .' ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'CREATE INDEX ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' ON ' . $this->db->escapeIdentifiers($table) + . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; } return $sqls; @@ -231,9 +230,9 @@ protected function _processIndexes($table) * * Performs a data type mapping between different databases. * - * @param array &$attributes + * @param array &$attributes * - * @return void + * @return void */ protected function _attributeType(&$attributes) { @@ -254,15 +253,15 @@ protected function _attributeType(&$attributes) /** * Field attribute AUTO_INCREMENT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeAutoIncrement(&$attributes, &$field) { if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'int') !== false) + && stripos($field['type'], 'int') !== false) { $field['type'] = 'INTEGER PRIMARY KEY'; $field['default'] = ''; @@ -279,10 +278,10 @@ protected function _attributeAutoIncrement(&$attributes, &$field) /** * Foreign Key Drop * - * @param string $table Table name - * @param string $foreign_name Foreign name + * @param string $table Table name + * @param string $foreign_name Foreign name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropForeignKey($table, $foreign_name) diff --git a/system/Database/SQLite3/PreparedQuery.php b/system/Database/SQLite3/PreparedQuery.php index af33a7d4d0f7..0ad54baf9c33 100644 --- a/system/Database/SQLite3/PreparedQuery.php +++ b/system/Database/SQLite3/PreparedQuery.php @@ -27,108 +27,110 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\PreparedQueryInterface; use \CodeIgniter\Database\BasePreparedQuery; class PreparedQuery extends BasePreparedQuery implements PreparedQueryInterface { - /** - * The SQLite3Result resource, or false. - * @var - */ - protected $result; - - //-------------------------------------------------------------------- - - /** - * Prepares the query against the database, and saves the connection - * info necessary to execute the query later. - * - * NOTE: This version is based on SQL code. Child classes should - * override this method. - * - * @param string $sql - * @param array $options Passed to the connection's prepare statement. - * Unused in the MySQLi driver. - * - * @return mixed - */ - public function _prepare(string $sql, array $options = []) - { - if ( ! ($this->statement = $this->db->connID->prepare($sql))) - { - $this->errorCode = $this->db->connID->lastErrorCode(); - $this->errorString = $this->db->connID->lastErrorMsg(); - } - - return $this; - } - - //-------------------------------------------------------------------- - - /** - * Takes a new set of data and runs it against the currently - * prepared query. Upon success, will return a Results object. - * - * @todo finalize() - * - * @param array $data - * - * @return bool - */ - public function _execute($data) - { - if (is_null($this->statement)) - { - throw new \BadMethodCallException('You must call prepare before trying to execute a prepared statement.'); - } - - foreach ($data as $key=>$item) - { - // Determine the type string - if (is_integer($item)) - { - $bindType = SQLITE3_INTEGER; - } - elseif (is_float($item)) - { - $bindType = SQLITE3_FLOAT; - } - else - { - $bindType = SQLITE3_TEXT; - } - - // Bind it - $this->statement->bindValue($key+1, $item, $bindType); - } - - $this->result = $this->statement->execute(); - - return $this->result !== false; - } - - //-------------------------------------------------------------------- - - /** - * Returns the result object for the prepared query. - * - * @return mixed - */ - public function _getResult() - { - return $this->result; - } - - //-------------------------------------------------------------------- + /** + * The SQLite3Result resource, or false. + * + * @var + */ + protected $result; + + //-------------------------------------------------------------------- + + /** + * Prepares the query against the database, and saves the connection + * info necessary to execute the query later. + * + * NOTE: This version is based on SQL code. Child classes should + * override this method. + * + * @param string $sql + * @param array $options Passed to the connection's prepare statement. + * Unused in the MySQLi driver. + * + * @return mixed + */ + public function _prepare(string $sql, array $options = []) + { + if (! ($this->statement = $this->db->connID->prepare($sql))) + { + $this->errorCode = $this->db->connID->lastErrorCode(); + $this->errorString = $this->db->connID->lastErrorMsg(); + } + + return $this; + } + + //-------------------------------------------------------------------- + + /** + * Takes a new set of data and runs it against the currently + * prepared query. Upon success, will return a Results object. + * + * @todo finalize() + * + * @param array $data + * + * @return boolean + */ + public function _execute($data) + { + if (is_null($this->statement)) + { + throw new \BadMethodCallException('You must call prepare before trying to execute a prepared statement.'); + } + + foreach ($data as $key => $item) + { + // Determine the type string + if (is_integer($item)) + { + $bindType = SQLITE3_INTEGER; + } + elseif (is_float($item)) + { + $bindType = SQLITE3_FLOAT; + } + else + { + $bindType = SQLITE3_TEXT; + } + + // Bind it + $this->statement->bindValue($key + 1, $item, $bindType); + } + + $this->result = $this->statement->execute(); + + return $this->result !== false; + } + + //-------------------------------------------------------------------- + + /** + * Returns the result object for the prepared query. + * + * @return mixed + */ + public function _getResult() + { + return $this->result; + } + + //-------------------------------------------------------------------- } diff --git a/system/Database/SQLite3/Result.php b/system/Database/SQLite3/Result.php index 6afa78b676d4..5737bf352997 100644 --- a/system/Database/SQLite3/Result.php +++ b/system/Database/SQLite3/Result.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseResult; use CodeIgniter\Database\ResultInterface; @@ -44,153 +45,154 @@ class Result extends BaseResult implements ResultInterface { - /** - * Gets the number of fields in the result set. - * - * @return int - */ - public function getFieldCount(): int - { - return $this->resultID->numColumns(); - } - - //-------------------------------------------------------------------- - - /** - * Generates an array of column names in the result set. - * - * @return array - */ - public function getFieldNames(): array - { - $fieldNames = []; - for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++ ) - { - $fieldNames[] = $this->resultID->columnName($i); - } - - return $fieldNames; - } - - //-------------------------------------------------------------------- - - /** - * Generates an array of objects representing field meta-data. - * - * @return array - */ - public function getFieldData(): array - { - static $data_types = [ - SQLITE3_INTEGER => 'integer', - SQLITE3_FLOAT => 'float', - SQLITE3_TEXT => 'text', - SQLITE3_BLOB => 'blob', - SQLITE3_NULL => 'null' - ]; - - $retval = []; - - for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++ ) - { - $retval[$i] = new \stdClass(); - $retval[$i]->name = $this->resultID->columnName($i); - $type = $this->resultID->columnType($i); - $retval[$i]->type = isset($data_types[$type]) ? $data_types[$type] : $type; - $retval[$i]->max_length = NULL; - } - - return $retval; - } - - //-------------------------------------------------------------------- - - /** - * Frees the current result. - * - * @return mixed - */ - public function freeResult() - { - if (is_object($this->resultID)) - { - $this->resultID->finalize(); - $this->resultID = false; - } - } - - //-------------------------------------------------------------------- - - /** - * Moves the internal pointer to the desired offset. This is called - * internally before fetching results to make sure the result set - * starts at zero. - * - * @param int $n - * - * @return mixed - * @throws \CodeIgniter\DatabaseException - */ - public function dataSeek($n = 0) - { - if ($n != 0) - { - if ($this->db->DBDebug) { - throw new DatabaseException('SQLite3 doesn\'t support seeking to other offset.'); - } - return false; - } - return $this->resultID->reset(); - } - - //-------------------------------------------------------------------- - - /** - * Returns the result set as an array. - * - * Overridden by driver classes. - * - * @return array - */ - protected function fetchAssoc() - { - return $this->resultID->fetchArray(SQLITE3_ASSOC); - } - - //-------------------------------------------------------------------- - - /** - * Returns the result set as an object. - * - * Overridden by child classes. - * - * @param string $className - * - * @return object - */ - protected function fetchObject($className = 'stdClass') - { - // No native support for fetching rows as objects - if (($row = $this->fetchAssoc()) === FALSE) - { - return FALSE; - } - elseif ($className === 'stdClass') - { - return (object) $row; - } - - $classObj = new $className(); - $classSet = \Closure::bind(function ($key, $value) { - $this->$key = $value; - }, $classObj, $className - ); - foreach (array_keys($row) as $key) - { - $classSet($key, $row[$key]); - } - return $classObj; - } - - //-------------------------------------------------------------------- + /** + * Gets the number of fields in the result set. + * + * @return integer + */ + public function getFieldCount(): int + { + return $this->resultID->numColumns(); + } + + //-------------------------------------------------------------------- + + /** + * Generates an array of column names in the result set. + * + * @return array + */ + public function getFieldNames(): array + { + $fieldNames = []; + for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++) + { + $fieldNames[] = $this->resultID->columnName($i); + } + + return $fieldNames; + } + + //-------------------------------------------------------------------- + + /** + * Generates an array of objects representing field meta-data. + * + * @return array + */ + public function getFieldData(): array + { + static $data_types = [ + SQLITE3_INTEGER => 'integer', + SQLITE3_FLOAT => 'float', + SQLITE3_TEXT => 'text', + SQLITE3_BLOB => 'blob', + SQLITE3_NULL => 'null', + ]; + + $retval = []; + + for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i ++) + { + $retval[$i] = new \stdClass(); + $retval[$i]->name = $this->resultID->columnName($i); + $type = $this->resultID->columnType($i); + $retval[$i]->type = isset($data_types[$type]) ? $data_types[$type] : $type; + $retval[$i]->max_length = null; + } + + return $retval; + } + + //-------------------------------------------------------------------- + + /** + * Frees the current result. + * + * @return mixed + */ + public function freeResult() + { + if (is_object($this->resultID)) + { + $this->resultID->finalize(); + $this->resultID = false; + } + } + + //-------------------------------------------------------------------- + + /** + * Moves the internal pointer to the desired offset. This is called + * internally before fetching results to make sure the result set + * starts at zero. + * + * @param integer $n + * + * @return mixed + * @throws \CodeIgniter\DatabaseException + */ + public function dataSeek($n = 0) + { + if ($n !== 0) + { + if ($this->db->DBDebug) + { + throw new DatabaseException('SQLite3 doesn\'t support seeking to other offset.'); + } + return false; + } + return $this->resultID->reset(); + } + + //-------------------------------------------------------------------- + + /** + * Returns the result set as an array. + * + * Overridden by driver classes. + * + * @return array + */ + protected function fetchAssoc() + { + return $this->resultID->fetchArray(SQLITE3_ASSOC); + } + + //-------------------------------------------------------------------- + + /** + * Returns the result set as an object. + * + * Overridden by child classes. + * + * @param string $className + * + * @return object + */ + protected function fetchObject($className = 'stdClass') + { + // No native support for fetching rows as objects + if (($row = $this->fetchAssoc()) === false) + { + return false; + } + elseif ($className === 'stdClass') + { + return (object) $row; + } + + $classObj = new $className(); + $classSet = \Closure::bind(function ($key, $value) { + $this->$key = $value; + }, $classObj, $className + ); + foreach (array_keys($row) as $key) + { + $classSet($key, $row[$key]); + } + return $classObj; + } + + //-------------------------------------------------------------------- } diff --git a/system/Database/SQLite3/Utils.php b/system/Database/SQLite3/Utils.php index 9df3b665ca47..e5c967dd82c9 100644 --- a/system/Database/SQLite3/Utils.php +++ b/system/Database/SQLite3/Utils.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -42,27 +42,27 @@ class Utils extends \CodeIgniter\Database\BaseUtils { - /** - * OPTIMIZE TABLE statement - * - * @var string - */ - protected $optimizeTable = 'REINDEX %s'; + /** + * OPTIMIZE TABLE statement + * + * @var string + */ + protected $optimizeTable = 'REINDEX %s'; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Platform dependent version of the backup function. - * - * @param array|null $prefs - * @todo build - * - * @return mixed - */ - public function _backup(array $prefs = null) - { - throw new DatabaseException('Unsupported feature of the database platform you are using.'); - } + /** + * Platform dependent version of the backup function. + * + * @param array|null $prefs + * @todo build + * + * @return mixed + */ + public function _backup(array $prefs = null) + { + throw new DatabaseException('Unsupported feature of the database platform you are using.'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/system/Database/Seeder.php b/system/Database/Seeder.php index 1b412e59578e..c57e7e06d9a3 100644 --- a/system/Database/Seeder.php +++ b/system/Database/Seeder.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\CLI\CLI; use CodeIgniter\Config\BaseConfig; @@ -46,37 +47,43 @@ class Seeder /** * The name of the database group to use. + * * @var string */ protected $DBGroup; /** * Where we can find the Seed files. + * * @var string */ protected $seedPath; /** * An instance of the main Database configuration + * * @var BaseConfig */ protected $config; /** * Database Connection instance + * * @var BaseConnection */ protected $db; /** * Database Forge instance. + * * @var Forge */ protected $forge; /** * If true, will not display CLI messages. - * @var bool + * + * @var boolean */ protected $silent = false; @@ -85,7 +92,7 @@ class Seeder /** * Seeder constructor. * - * @param BaseConfig $config + * @param BaseConfig $config * @param BaseConnection $db */ public function __construct(BaseConfig $config, BaseConnection $db = null) @@ -99,7 +106,7 @@ public function __construct(BaseConfig $config, BaseConnection $db = null) $this->seedPath = rtrim($this->seedPath, '/') . '/Seeds/'; - if ( ! is_dir($this->seedPath)) + if (! is_dir($this->seedPath)) { throw new \InvalidArgumentException('Unable to locate the seeds directory. Please check Config\Database::filesPath'); } @@ -142,12 +149,12 @@ public function call(string $class) { $path = $this->seedPath . $path; - if ( ! is_file($path)) + if (! is_file($path)) { throw new \InvalidArgumentException('The specified Seeder is not a valid file: ' . $path); } - if ( ! class_exists($class, false)) + if (! class_exists($class, false)) { require_once $path; } @@ -186,7 +193,7 @@ public function setPath(string $path) /** * Sets the silent treatment. * - * @param bool $silent + * @param boolean $silent * * @return Seeder */ @@ -209,7 +216,6 @@ public function setSilent(bool $silent) */ public function run() { - } //-------------------------------------------------------------------- diff --git a/system/Debug/Exceptions.php b/system/Debug/Exceptions.php index 8a10a34d5444..5f0839f84501 100644 --- a/system/Debug/Exceptions.php +++ b/system/Debug/Exceptions.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -46,7 +46,7 @@ class Exceptions /** * Nesting level of the output buffering mechanism * - * @var int + * @var integer */ public $ob_level; @@ -124,16 +124,16 @@ public function initialize() */ public function exceptionHandler(\Throwable $exception) { - $codes = $this->determineCodes($exception); + $codes = $this->determineCodes($exception); $statusCode = $codes[0]; - $exitCode = $codes[1]; + $exitCode = $codes[1]; // Log it if ($this->config->log === true && ! in_array($statusCode, $this->config->ignoreCodes)) { - log_message('critical', $exception->getMessage()."\n{trace}", [ - 'trace' => $exception->getTraceAsString() - ]); + log_message('critical', $exception->getMessage() . "\n{trace}", [ + 'trace' => $exception->getTraceAsString(), + ]); } if (! is_cli()) @@ -164,11 +164,11 @@ public function exceptionHandler(\Throwable $exception) * * This seems to be primarily when a user triggers it with trigger_error(). * - * @param int $severity - * @param string $message - * @param string|null $file - * @param int|null $line - * @param null $context + * @param integer $severity + * @param string $message + * @param string|null $file + * @param integer|null $line + * @param null $context * * @throws \ErrorException */ @@ -191,7 +191,7 @@ public function shutdownHandler() // If we've got an error that hasn't been displayed, then convert // it to an Exception and use the Exception handler to display it // to the user. - if ( ! is_null($error)) + if (! is_null($error)) { // Fatal Error? if (in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) @@ -215,7 +215,7 @@ public function shutdownHandler() protected function determineView(\Throwable $exception, string $template_path): string { // Production environments should have a custom exception file. - $view = 'production.php'; + $view = 'production.php'; $template_path = rtrim($template_path, '/ ') . '/'; if (str_ireplace(['off', 'none', 'no', 'false', 'null'], '', ini_get('display_errors'))) @@ -244,7 +244,7 @@ protected function determineView(\Throwable $exception, string $template_path): * Given an exception and status code will display the error to the client. * * @param \Throwable $exception - * @param int $statusCode + * @param integer $statusCode */ protected function render(\Throwable $exception, int $statusCode) { @@ -256,8 +256,8 @@ protected function render(\Throwable $exception, int $statusCode) } $path = is_cli() - ? $path.'cli/' - : $path.'html/'; + ? $path . 'cli/' + : $path . 'html/'; // Determine the vew $view = $this->determineView($exception, $path); @@ -285,7 +285,7 @@ protected function render(\Throwable $exception, int $statusCode) * Gathers the variables that will be made available to the view. * * @param \Throwable $exception - * @param int $statusCode + * @param integer $statusCode * * @return array */ @@ -302,7 +302,6 @@ protected function collectVars(\Throwable $exception, int $statusCode) ]; } - /** * Determines the HTTP status code and the exit status code for this request. * @@ -330,7 +329,7 @@ protected function determineCodes(\Throwable $exception): array return [ $statusCode ?? 500, - $exitStatus + $exitStatus, ]; } @@ -344,9 +343,9 @@ protected function determineCodes(\Throwable $exception): array * * This makes nicer looking paths for the error output. * - * @param string $file + * @param string $file * - * @return string + * @return string */ public static function cleanPath($file) { @@ -395,11 +394,11 @@ public static function describeMemory(int $bytes): string /** * Creates a syntax-highlighted version of a PHP file. * - * @param $file - * @param $lineNumber - * @param int $lines + * @param $file + * @param $lineNumber + * @param integer $lines * - * @return bool|string + * @return boolean|string */ public static function highlightFile($file, $lineNumber, $lines = 15) { @@ -421,7 +420,8 @@ public static function highlightFile($file, $lineNumber, $lines = 15) try { $source = file_get_contents($file); - } catch (\Throwable $e) + } + catch (\Throwable $e) { return false; } @@ -452,9 +452,9 @@ public static function highlightFile($file, $lineNumber, $lines = 15) foreach ($source as $n => $row) { $spans += substr_count($row, ']+>#', $row, $tags); $out .= sprintf("{$format} %s\n%s", $n + $start + 1, strip_tags($row), implode('', $tags[0]) diff --git a/system/Debug/Iterator.php b/system/Debug/Iterator.php index d04d5061d6d5..442aad49816b 100644 --- a/system/Debug/Iterator.php +++ b/system/Debug/Iterator.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -64,7 +64,7 @@ class Iterator * Tests are simply closures that the user can define any sequence of * things to happen during the test. * - * @param $name + * @param $name * @param \Closure $closure * * @return $this @@ -85,8 +85,8 @@ public function add($name, \Closure $closure) * time to execute the desired number of iterations, and the approximate * memory usage used during those iterations. * - * @param int $iterations - * @param bool $output + * @param integer $iterations + * @param boolean $output * * @return string */ @@ -97,10 +97,10 @@ public function run($iterations = 1000, $output = true) // clear memory before start gc_collect_cycles(); - $start = microtime(true); + $start = microtime(true); $start_mem = $max_memory = memory_get_usage(true); - for ($i = 0; $i < $iterations; $i ++ ) + for ($i = 0; $i < $iterations; $i ++) { $result = $test(); @@ -110,9 +110,9 @@ public function run($iterations = 1000, $output = true) } $this->results[$name] = [ - 'time' => microtime(true) - $start, + 'time' => microtime(true) - $start, 'memory' => $max_memory - $start_mem, - 'n' => $iterations, + 'n' => $iterations, ]; } @@ -139,7 +139,7 @@ public function getReport() helper('number'); // Template - $tpl = " + $tpl = '
@@ -150,13 +150,13 @@ public function getReport() {rows} -
Test
"; + '; - $rows = ""; + $rows = ''; foreach ($this->results as $name => $result) { - $memory = number_to_size($result['memory'], 4); + $memory = number_to_size($result['memory'], 4); $rows .= " {$name} @@ -167,7 +167,7 @@ public function getReport() $tpl = str_replace('{rows}', $rows, $tpl); - return $tpl . "
"; + return $tpl . '
'; } //-------------------------------------------------------------------- diff --git a/system/Debug/Timer.php b/system/Debug/Timer.php index b638ff63cf5c..97101019803f 100644 --- a/system/Debug/Timer.php +++ b/system/Debug/Timer.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -65,16 +65,16 @@ class Timer * 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. + * @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, + 'start' => ! empty($time) ? $time : microtime(true), + 'end' => null, ]; return $this; @@ -88,7 +88,7 @@ public function start(string $name, float $time = null) * 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. + * @param string $name The name of this timer. * * @return Timer */ @@ -111,8 +111,8 @@ public function stop(string $name) /** * Returns the duration of a recorded timer. * - * @param string $name The name of the timer. - * @param int $decimals Number of decimal places. + * @param string $name The name of the timer. + * @param integer $decimals Number of decimal places. * * @return null|float Returns null if timer exists by that name. * Returns a float representing the number of @@ -142,7 +142,7 @@ public function getElapsedTime(string $name, int $decimals = 4) /** * Returns the array of timers, with the duration pre-calculated for you. * - * @param int $decimals Number of decimal places + * @param integer $decimals Number of decimal places * * @return array */ @@ -170,7 +170,7 @@ public function getTimers(int $decimals = 4) * * @param string $name * - * @return bool + * @return boolean */ public function has(string $name) { diff --git a/system/Debug/Toolbar.php b/system/Debug/Toolbar.php index 926000661bb4..f3d9b284bb82 100644 --- a/system/Debug/Toolbar.php +++ b/system/Debug/Toolbar.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\App; use Config\Services; use CodeIgniter\Config\BaseConfig; @@ -79,8 +80,8 @@ public function __construct(BaseConfig $config) { if (! class_exists($collector)) { - log_message('critical', 'Toolbar collector does not exists(' . $collector . ').'. - 'please check $toolbarCollectors in the Config\App.php file.'); + log_message('critical', 'Toolbar collector does not exists(' . $collector . ').' . + 'please check $toolbarCollectors in the Config\App.php file.'); continue; } @@ -93,7 +94,7 @@ public function __construct(BaseConfig $config) /** * Returns all the data required by Debug Bar * - * @param float $startTime App start time + * @param float $startTime App start time * @param float $totalTime * @param \CodeIgniter\HTTP\RequestInterface $request * @param \CodeIgniter\HTTP\ResponseInterface $response @@ -107,14 +108,14 @@ public function run($startTime, $totalTime, $request, $response): string $data['method'] = $request->getMethod(true); $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, 5); - $data['segmentCount'] = (int)ceil($data['totalTime']/$data['segmentDuration']); + $data['totalTime'] = $totalTime * 1000; + $data['totalMemory'] = number_format((memory_get_peak_usage()) / 1024 / 1024, 3); + $data['segmentDuration'] = $this->roundTo($data['totalTime'] / 7, 5); + $data['segmentCount'] = (int)ceil($data['totalTime'] / $data['segmentDuration']); $data['CI_VERSION'] = \CodeIgniter\CodeIgniter::CI_VERSION; $data['collectors'] = []; - foreach($this->collectors as $collector) + foreach ($this->collectors as $collector) { $data['collectors'][] = [ 'title' => $collector->getTitle(), @@ -187,17 +188,17 @@ public function run($startTime, $totalTime, $request, $response): string $data['vars']['cookies'][esc($name)] = esc($value); } - $data['vars']['request'] = ($request->isSecure() ? 'HTTPS' : 'HTTP').'/'.$request->getProtocolVersion(); + $data['vars']['request'] = ($request->isSecure() ? 'HTTPS' : 'HTTP') . '/' . $request->getProtocolVersion(); $data['vars']['response'] = [ - 'statusCode' => $response->getStatusCode(), - 'reason' => esc($response->getReason()), - 'contentType' => esc($response->getHeaderLine('content-type')), + 'statusCode' => $response->getStatusCode(), + 'reason' => esc($response->getReason()), + 'contentType' => esc($response->getHeaderLine('content-type')), ]; $data['config'] = \CodeIgniter\Debug\Toolbar\Collectors\Config::display(); - if( $response->CSP !== null ) + if ($response->CSP !== null) { $response->CSP->addImageSrc( 'data:' ); } @@ -210,8 +211,8 @@ public function run($startTime, $totalTime, $request, $response): string /** * Format output * - * @param string $data JSON encoded Toolbar data - * @param string $format html, json, xml + * @param string $data JSON encoded Toolbar data + * @param string $format html, json, xml * * @return string */ @@ -220,7 +221,7 @@ protected static function format(string $data, string $format = 'html') $data = json_decode($data, true); // History must be loaded on the fly - $filenames = glob(WRITEPATH.'debugbar/debugbar_*'); + $filenames = glob(WRITEPATH . 'debugbar/debugbar_*'); $total = count($filenames); rsort($filenames); @@ -231,12 +232,12 @@ protected static function format(string $data, string $format = 'html') for ($i = 0; $i < $total; $i++) { - // Oldest files will be deleted - if ($app->toolbarMaxHistory >= 0 && $i+1 > $app->toolbarMaxHistory) + // Oldest files will be deleted + if ($app->toolbarMaxHistory >= 0 && $i + 1 > $app->toolbarMaxHistory) { unlink($filenames[$i]); continue; - } + } // Get the contents of this specific history request ob_start(); @@ -250,7 +251,7 @@ protected static function format(string $data, string $format = 'html') $files[] = [ 'time' => (int)$time = substr($filenames[$i], -10), 'datetime' => date('Y-m-d H:i:s', $time), - 'active' => (int)($time == $current), + 'active' => (int)($time === $current), 'status' => $file['vars']['response']['statusCode'], 'method' => $file['method'], 'url' => $file['url'], @@ -260,7 +261,7 @@ protected static function format(string $data, string $format = 'html') } // Set the History here. Class is not necessary - $data['collectors'][] = [ + $data['collectors'][] = [ 'title' => 'History', 'titleSafe' => 'history', 'titleDetails' => '', @@ -281,9 +282,9 @@ protected static function format(string $data, string $format = 'html') case 'html': $data['styles'] = []; extract($data); - $parser = Services::parser(BASEPATH . 'Debug/Toolbar/Views/', null,false); + $parser = Services::parser(BASEPATH . 'Debug/Toolbar/Views/', null, false); ob_start(); - include(__DIR__.'/Toolbar/Views/toolbar.tpl.php'); + include(__DIR__ . '/Toolbar/Views/toolbar.tpl.php'); $output = ob_get_contents(); ob_end_clean(); break; @@ -304,36 +305,36 @@ protected static function format(string $data, string $format = 'html') /** * Called within the view to display the timeline itself. * - * @param array $collectors - * @param float $startTime - * @param int $segmentCount - * @param int $segmentDuration + * @param array $collectors + * @param float $startTime + * @param integer $segmentCount + * @param integer $segmentDuration * * @return string */ - protected static function renderTimeline(array $collectors, $startTime, int $segmentCount, int $segmentDuration, array& $styles ): string + protected static function renderTimeline(array $collectors, $startTime, int $segmentCount, int $segmentDuration, array& $styles): string { - $displayTime = $segmentCount*$segmentDuration; + $displayTime = $segmentCount * $segmentDuration; $rows = self::collectTimelineData($collectors); $output = ''; - $styleCount = 0; + $styleCount = 0; foreach ($rows as $row) { - $output .= ""; + $output .= ''; $output .= "{$row['name']}"; $output .= "{$row['component']}"; - $output .= "".number_format($row['duration']*1000, 2)." ms"; + $output .= "" . number_format($row['duration'] * 1000, 2) . ' ms'; $output .= ""; - $offset = ((($row['start']-$startTime)*1000)/$displayTime)*100; - $length = (($row['duration']*1000)/$displayTime)*100; + $offset = ((($row['start'] - $startTime) * 1000) / $displayTime) * 100; + $length = (($row['duration'] * 1000) / $displayTime) * 100; - $styles['debug-bar-timeline-'.$styleCount] = "left: {$offset}%; width: {$length}%;"; - $output .= ""; - $output .= ""; - $output .= ""; + $styles['debug-bar-timeline-' . $styleCount] = "left: {$offset}%; width: {$length}%;"; + $output .= ""; + $output .= ''; + $output .= ''; $styleCount++; } @@ -398,16 +399,16 @@ protected function collectVarData()// : array /** * Rounds a number to the nearest incremental value. * - * @param float $number - * @param int $increments + * @param float $number + * @param integer $increments * * @return float */ protected function roundTo($number, $increments = 5) { - $increments = 1/$increments; + $increments = 1 / $increments; - return (ceil($number*$increments)/$increments); + return (ceil($number * $increments) / $increments); } //-------------------------------------------------------------------- @@ -419,7 +420,7 @@ public static function eventHandler() { self::$request = Services::request(); - if(ENVIRONMENT == 'testing') + if (ENVIRONMENT === 'testing') { return; } @@ -432,7 +433,7 @@ public static function eventHandler() header('Content-Type: application/javascript'); ob_start(); - include(BASEPATH.'Debug/Toolbar/toolbarloader.js.php'); + include(BASEPATH . 'Debug/Toolbar/toolbarloader.js.php'); $output = ob_get_contents(); @ob_end_clean(); @@ -449,12 +450,12 @@ public static function eventHandler() $format = self::$request->negotiate('media', [ 'text/html', 'application/json', - 'application/xml' + 'application/xml', ]); $format = explode('/', $format)[1]; - $file = sanitize_filename('debugbar_'.self::$request->getGet('debugbar_time')); - $filename = WRITEPATH.'debugbar/'.$file; + $file = sanitize_filename('debugbar_' . self::$request->getGet('debugbar_time')); + $filename = WRITEPATH . 'debugbar/' . $file; // Show the toolbar if (file_exists($filename)) diff --git a/system/Debug/Toolbar/Collectors/BaseCollector.php b/system/Debug/Toolbar/Collectors/BaseCollector.php index c30051dda643..a203599fdc6c 100644 --- a/system/Debug/Toolbar/Collectors/BaseCollector.php +++ b/system/Debug/Toolbar/Collectors/BaseCollector.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ @@ -46,7 +46,7 @@ class BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = false; @@ -54,7 +54,7 @@ class BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = false; @@ -62,7 +62,7 @@ class BaseCollector * Whether this collector needs to display * a label or not. * - * @var bool + * @var boolean */ protected $hasLabel = false; @@ -70,7 +70,7 @@ class BaseCollector * Whether this collector has data that * should be shown in the Vars tab. * - * @var bool + * @var boolean */ protected $hasVarData = false; @@ -87,7 +87,7 @@ class BaseCollector /** * Gets the Collector's title. * - * @param bool $safe + * @param boolean $safe * @return string */ public function getTitle($safe = false): string @@ -117,7 +117,7 @@ public function getTitleDetails(): string /** * Does this collector need it's own tab? * - * @return bool + * @return boolean */ public function hasTabContent(): bool { @@ -129,7 +129,7 @@ public function hasTabContent(): bool /** * Does this collector have a label? * - * @return bool + * @return boolean */ public function hasLabel(): bool { @@ -141,7 +141,7 @@ public function hasLabel(): bool /** * Does this collector have information for the timeline? * - * @return bool + * @return boolean */ public function hasTimelineData(): bool { @@ -158,7 +158,7 @@ public function hasTimelineData(): bool */ public function timelineData(): array { - if ( ! $this->hasTimeline) + if (! $this->hasTimeline) { return []; } @@ -245,9 +245,9 @@ public function display(): array * * This makes nicer looking paths for the error output. * - * @param string $file + * @param string $file * - * @return string + * @return string */ public function cleanPath($file) { @@ -282,7 +282,7 @@ public function getBadgeValue() * * If not, then the toolbar button won't get shown. * - * @return bool + * @return boolean */ public function isEmpty() { diff --git a/system/Debug/Toolbar/Collectors/Database.php b/system/Debug/Toolbar/Collectors/Database.php index 84097fae519f..319d9439523f 100644 --- a/system/Debug/Toolbar/Collectors/Database.php +++ b/system/Debug/Toolbar/Collectors/Database.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Database\Query; /** @@ -126,20 +127,20 @@ protected function formatTimelineData(): array { // Connection Time $data[] = [ - 'name' => 'Connecting to Database: "' . $alias . '"', - 'component' => 'Database', - 'start' => $connection->getConnectStart(), - 'duration' => $connection->getConnectDuration() + 'name' => 'Connecting to Database: "' . $alias . '"', + 'component' => 'Database', + 'start' => $connection->getConnectStart(), + 'duration' => $connection->getConnectDuration(), ]; } foreach (static::$queries as $query) { $data[] = [ - 'name' => 'Query', - 'component' => 'Database', - 'start' => $query->getStartTime(true), - 'duration' => $query->getDuration() + 'name' => 'Query', + 'component' => 'Database', + 'start' => $query->getStartTime(true), + 'duration' => $query->getDuration(), ]; } @@ -156,13 +157,40 @@ protected function formatTimelineData(): array public function display(): array { // Key words we want bolded - $highlight = ['SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT JOIN', 'ORDER BY', 'GROUP BY', - 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR ', 'HAVING', 'OFFSET', 'NOT IN', - 'IN', 'LIKE', 'NOT LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')' + $highlight = [ + 'SELECT', + 'DISTINCT', + 'FROM', + 'WHERE', + 'AND', + 'LEFT JOIN', + 'ORDER BY', + 'GROUP BY', + 'LIMIT', + 'INSERT', + 'INTO', + 'VALUES', + 'UPDATE', + 'OR ', + 'HAVING', + 'OFFSET', + 'NOT IN', + 'IN', + 'LIKE', + 'NOT LIKE', + 'COUNT', + 'MAX', + 'MIN', + 'ON', + 'AS', + 'AVG', + 'SUM', + '(', + ')', ]; $data = [ - 'queries' => [] + 'queries' => [], ]; foreach (static::$queries as $query) @@ -175,8 +203,8 @@ public function display(): array } $data['queries'][] = [ - 'duration' => ($query->getDuration(5) * 1000) .' ms', - 'sql' => $sql + 'duration' => ($query->getDuration(5) * 1000) . ' ms', + 'sql' => $sql, ]; } @@ -188,7 +216,7 @@ public function display(): array /** * Gets the "badge" value for the button. * - * @return int + * @return integer */ public function getBadgeValue() { @@ -213,7 +241,7 @@ public function getTitleDetails(): string /** * Does this collector have any data collected? * - * @return bool + * @return boolean */ public function isEmpty() { @@ -232,7 +260,6 @@ public function isEmpty() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADMSURBVEhLY6A3YExLSwsA4nIycQDIDIhRWEBqamo/UNF/SjDQjF6ocZgAKPkRiFeEhoYyQ4WIBiA9QAuWAPEHqBAmgLqgHcolGQD1V4DMgHIxwbCxYD+QBqcKINseKo6eWrBioPrtQBq/BcgY5ht0cUIYbBg2AJKkRxCNWkDQgtFUNJwtABr+F6igE8olGQD114HMgHIxAVDyAhA/AlpSA8RYUwoeXAPVex5qHCbIyMgwBCkAuQJIY00huDBUz/mUlBQDqHGjgBjAwAAACexpph6oHSQAAAAASUVORK5CYII='; - } } diff --git a/system/Debug/Toolbar/Collectors/Events.php b/system/Debug/Toolbar/Collectors/Events.php index e4125c39e8b9..f6587d3b4916 100644 --- a/system/Debug/Toolbar/Collectors/Events.php +++ b/system/Debug/Toolbar/Collectors/Events.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Services; use CodeIgniter\View\RendererInterface; @@ -48,7 +49,7 @@ class Events extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = false; @@ -56,7 +57,7 @@ class Events extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = true; @@ -64,7 +65,7 @@ class Events extends BaseCollector * Whether this collector has data that * should be shown in the Vars tab. * - * @var bool + * @var boolean */ protected $hasVarData = false; @@ -78,6 +79,7 @@ class Events extends BaseCollector /** * Instance of the Renderer service + * * @var RendererInterface */ protected $viewer; @@ -109,10 +111,10 @@ protected function formatTimelineData(): array foreach ($rows as $name => $info) { $data[] = [ - 'name' => 'View: ' . $info['view'], - 'component' => 'Views', - 'start' => $info['start'], - 'duration' => $info['end'] - $info['start'] + 'name' => 'View: ' . $info['view'], + 'component' => 'Views', + 'start' => $info['start'], + 'duration' => $info['end'] - $info['start'], ]; } @@ -129,7 +131,7 @@ protected function formatTimelineData(): array public function display(): array { $data = [ - 'events' => [] + 'events' => [], ]; foreach (\CodeIgniter\Events\Events::getPerformanceLogs() as $row) @@ -139,15 +141,15 @@ public function display(): array if (! array_key_exists($key, $data['events'])) { $data['events'][$key] = [ - 'event' => $key, - 'duration' => number_format(($row['end']-$row['start']) * 1000, 2), - 'count' => 1, + 'event' => $key, + 'duration' => number_format(($row['end'] - $row['start']) * 1000, 2), + 'count' => 1, ]; continue; } - $data['events'][$key]['duration'] += number_format(($row['end']-$row['start']) * 1000, 2); + $data['events'][$key]['duration'] += number_format(($row['end'] - $row['start']) * 1000, 2); $data['events'][$key]['count']++; } @@ -176,6 +178,5 @@ public function getBadgeValue() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEASURBVEhL7ZXNDcIwDIVTsRBH1uDQDdquUA6IM1xgCA6MwJUN2hk6AQzAz0vl0ETUxC5VT3zSU5w81/mRMGZysixbFEVR0jSKNt8geQU9aRpFmp/keX6AbjZ5oB74vsaN5lSzA4tLSjpBFxsjeSuRy4d2mDdQTWU7YLbXTNN05mKyovj5KL6B7q3hoy3KwdZxBlT+Ipz+jPHrBqOIynZgcZonoukb/0ckiTHqNvDXtXEAaygRbaB9FvUTjRUHsIYS0QaSp+Dw6wT4hiTmYHOcYZsdLQ2CbXa4ftuuYR4x9vYZgdb4vsFYUdmABMYeukK9/SUme3KMFQ77+Yfzh8eYF8+orDuDWU5LAAAAAElFTkSuQmCC'; - } } diff --git a/system/Debug/Toolbar/Collectors/Files.php b/system/Debug/Toolbar/Collectors/Files.php index 3e565a5c6d1d..21f017b168bf 100644 --- a/system/Debug/Toolbar/Collectors/Files.php +++ b/system/Debug/Toolbar/Collectors/Files.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ @@ -46,7 +46,7 @@ class Files extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = false; @@ -54,7 +54,7 @@ class Files extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = true; @@ -87,7 +87,7 @@ public function getTitleDetails(): string */ public function display(): array { - $rawFiles = get_included_files(); + $rawFiles = get_included_files(); $coreFiles = []; $userFiles = []; @@ -98,15 +98,15 @@ public function display(): array if (strpos($path, 'BASEPATH') !== false) { $coreFiles[] = [ - 'name' => basename($file), - 'path' => $path + 'name' => basename($file), + 'path' => $path, ]; } else { $userFiles[] = [ - 'name' => basename($file), - 'path' => $path + 'name' => basename($file), + 'path' => $path, ]; } } @@ -115,8 +115,8 @@ public function display(): array sort($coreFiles); return [ - 'coreFiles' => $coreFiles, - 'userFiles' => $userFiles, + 'coreFiles' => $coreFiles, + 'userFiles' => $userFiles, ]; } @@ -125,7 +125,7 @@ public function display(): array /** * Displays the number of included files as a badge in the tab button. * - * @return int + * @return integer */ public function getBadgeValue() { @@ -144,6 +144,5 @@ public function getBadgeValue() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGBSURBVEhL7ZQ9S8NQGIVTBQUncfMfCO4uLgoKbuKQOWg+OkXERRE1IAXrIHbVDrqIDuLiJgj+gro7S3dnpfq88b1FMTE3VZx64HBzzvvZWxKnj15QCcPwCD5HUfSWR+JtzgmtsUcQBEva5IIm9SwSu+95CAWbUuy67qBa32ByZEDpIaZYZSZMjjQuPcQUq8yEyYEb8FSerYeQVGbAFzJkX1PyQWLhgCz0BxTCekC1Wp0hsa6yokzhed4oje6Iz6rlJEkyIKfUEFtITVtQdAibn5rMyaYsMS+a5wTv8qeXMhcU16QZbKgl3hbs+L4/pnpdc87MElZgq10p5DxGdq8I7xrvUWUKvG3NbSK7ubngYzdJwSsF7TiOh9VOgfcEz1UayNe3JUPM1RWC5GXYgTfc75B4NBmXJnAtTfpABX0iPvEd9ezALwkplCFXcr9styiNOKc1RRZpaPM9tcqBwlWzGY1qPL9wjqRBgF5BH6j8HWh2S7MHlX8PrmbK+k/8PzjOOzx1D3i1pKTTAAAAAElFTkSuQmCC'; - } } diff --git a/system/Debug/Toolbar/Collectors/Logs.php b/system/Debug/Toolbar/Collectors/Logs.php index bd15bfef4d3a..26aab0eceeef 100644 --- a/system/Debug/Toolbar/Collectors/Logs.php +++ b/system/Debug/Toolbar/Collectors/Logs.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Config\Services; /** @@ -47,7 +48,7 @@ class Logs extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = false; @@ -55,7 +56,7 @@ class Logs extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = true; @@ -91,7 +92,7 @@ public function display(): array } return [ - 'logs' => $logs + 'logs' => $logs, ]; } @@ -119,7 +120,6 @@ public function isEmpty() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACYSURBVEhLYxgFJIHU1FSjtLS0i0D8AYj7gEKMEBkqAaAFF4D4ERCvAFrwH4gDoFIMKSkpFkB+OTEYqgUTACXfA/GqjIwMQyD9H2hRHlQKJFcBEiMGQ7VgAqCBvUgK32dmZspCpagGGNPT0/1BLqeF4bQHQJePpiIwhmrBBEADR1MRfgB0+WgqAmOoFkwANHA0FY0CUgEDAwCQ0PUpNB3kqwAAAABJRU5ErkJggg=='; - } //-------------------------------------------------------------------- @@ -129,9 +129,12 @@ public function icon(): string */ protected function collectLogs() { - if (! is_null($this->data)) return; + if (! is_null($this->data)) + { + return; + } - $logger = Services::logger(true); + $logger = Services::logger(true); $this->data = $logger->logCache; } diff --git a/system/Debug/Toolbar/Collectors/Routes.php b/system/Debug/Toolbar/Collectors/Routes.php index 3bb25fd2857c..917978d3419d 100644 --- a/system/Debug/Toolbar/Collectors/Routes.php +++ b/system/Debug/Toolbar/Collectors/Routes.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Config\Services; /** @@ -47,7 +48,7 @@ class Routes extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = false; @@ -55,7 +56,7 @@ class Routes extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = true; @@ -77,7 +78,7 @@ class Routes extends BaseCollector public function display(): array { $rawRoutes = Services::routes(true); - $router = Services::router(null, true); + $router = Services::router(null, true); /* * Matched Route @@ -85,47 +86,47 @@ public function display(): array $route = $router->getMatchedRoute(); // Get our parameters - $method = is_callable($router->controllerName()) ? new \ReflectionFunction($router->controllerName()) : new \ReflectionMethod($router->controllerName(), $router->methodName()); + $method = is_callable($router->controllerName()) ? new \ReflectionFunction($router->controllerName()) : new \ReflectionMethod($router->controllerName(), $router->methodName()); $rawParams = $method->getParameters(); $params = []; foreach ($rawParams as $key => $param) { $params[] = [ - 'name' => $param->getName(), - 'value' => $router->params()[$key] ?? - "<empty> | default: " . var_export($param->getDefaultValue(), true) + 'name' => $param->getName(), + 'value' => $router->params()[$key] ?? + '<empty> | default: ' . var_export($param->getDefaultValue(), true), ]; } $matchedRoute = [ [ - 'directory' => $router->directory(), + 'directory' => $router->directory(), 'controller' => $router->controllerName(), - 'method' => $router->methodName(), + 'method' => $router->methodName(), 'paramCount' => count($router->params()), 'truePCount' => count($params), - 'params' => $params ?? [] - ] + 'params' => $params ?? [], + ], ]; /* * Defined Routes */ $rawRoutes = $rawRoutes->getRoutes(); - $routes = []; + $routes = []; foreach ($rawRoutes as $from => $to) { $routes[] = [ - 'from' => $from, - 'to' => $to + 'from' => $from, + 'to' => $to, ]; } return [ 'matchedRoute' => $matchedRoute, - 'routes' => $routes + 'routes' => $routes, ]; } @@ -134,7 +135,7 @@ public function display(): array /** * Returns a count of all the routes in the system. * - * @return int + * @return integer */ public function getBadgeValue() { @@ -155,6 +156,5 @@ public function getBadgeValue() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAFDSURBVEhL7ZRNSsNQFIUjVXSiOFEcuQIHDpzpxC0IGYeE/BEInbWlCHEDLsSiuANdhKDjgm6ggtSJ+l25ldrmmTwIgtgDh/t37r1J+16cX0dRFMtpmu5pWAkrvYjjOB7AETzStBFW+inxu3KUJMmhludQpoflS1zXban4LYqiO224h6VLTHr8Z+z8EpIHFF9gG78nDVmW7UgTHKjsCyY98QP+pcq+g8Ku2s8G8X3f3/I8b038WZTp+bO38zxfFd+I6YY6sNUvFlSDk9CRhiAI1jX1I9Cfw7GG1UB8LAuwbU0ZwQnbRDeEN5qqBxZMLtE1ti9LtbREnMIuOXnyIf5rGIb7Wq8HmlZgwYBH7ORTcKH5E4mpjeGt9fBZcHE2GCQ3Vt7oTNPNg+FXLHnSsHkw/FR+Gg2bB8Ptzrst/v6C/wrH+QB+duli6MYJdQAAAABJRU5ErkJggg=='; - } } diff --git a/system/Debug/Toolbar/Collectors/Timers.php b/system/Debug/Toolbar/Collectors/Timers.php index 6e69ee74c677..a7ff9717425f 100644 --- a/system/Debug/Toolbar/Collectors/Timers.php +++ b/system/Debug/Toolbar/Collectors/Timers.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Config\Services; /** @@ -47,7 +48,7 @@ class Timers extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = true; @@ -55,7 +56,7 @@ class Timers extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = false; @@ -80,18 +81,20 @@ protected function formatTimelineData(): array $data = []; $benchmark = Services::timer(true); - $rows = $benchmark->getTimers(6); + $rows = $benchmark->getTimers(6); foreach ($rows as $name => $info) { - if ($name == 'total_execution') + if ($name === 'total_execution') + { continue; + } $data[] = [ - 'name' => ucwords(str_replace('_', ' ', $name)), - 'component' => 'Timer', - 'start' => $info['start'], - 'duration' => $info['end'] - $info['start'] + 'name' => ucwords(str_replace('_', ' ', $name)), + 'component' => 'Timer', + 'start' => $info['start'], + 'duration' => $info['end'] - $info['start'], ]; } diff --git a/system/Debug/Toolbar/Collectors/Views.php b/system/Debug/Toolbar/Collectors/Views.php index 711da495c530..5dc87e8921de 100644 --- a/system/Debug/Toolbar/Collectors/Views.php +++ b/system/Debug/Toolbar/Collectors/Views.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Config\Services; use CodeIgniter\View\RendererInterface; @@ -48,7 +49,7 @@ class Views extends BaseCollector * Whether this collector has data that can * be displayed in the Timeline. * - * @var bool + * @var boolean */ protected $hasTimeline = true; @@ -56,7 +57,7 @@ class Views extends BaseCollector * Whether this collector needs to display * content in a tab or not. * - * @var bool + * @var boolean */ protected $hasTabContent = false; @@ -64,7 +65,7 @@ class Views extends BaseCollector * Whether this collector needs to display * a label or not. * - * @var bool + * @var boolean */ protected $hasLabel = true; @@ -72,7 +73,7 @@ class Views extends BaseCollector * Whether this collector has data that * should be shown in the Vars tab. * - * @var bool + * @var boolean */ protected $hasVarData = true; @@ -86,6 +87,7 @@ class Views extends BaseCollector /** * Instance of the Renderer service + * * @var RendererInterface */ protected $viewer; @@ -124,10 +126,10 @@ protected function formatTimelineData(): array foreach ($rows as $name => $info) { $data[] = [ - 'name' => 'View: ' . $info['view'], - 'component' => 'Views', - 'start' => $info['start'], - 'duration' => $info['end'] - $info['start'] + 'name' => 'View: ' . $info['view'], + 'component' => 'Views', + 'start' => $info['start'], + 'duration' => $info['end'] - $info['start'], ]; } @@ -157,7 +159,7 @@ protected function formatTimelineData(): array public function getVarData() { return [ - 'View Data' => $this->viewer->getData() + 'View Data' => $this->viewer->getData(), ]; } @@ -166,7 +168,7 @@ public function getVarData() /** * Returns a count of all views. * - * @return int + * @return integer */ public function getBadgeValue() { @@ -183,6 +185,5 @@ public function getBadgeValue() public function icon(): string { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADeSURBVEhL7ZSxDcIwEEWNYA0YgGmgyAaJLTcUaaBzQQEVjMEabBQxAdw53zTHiThEovGTfnE/9rsoRUxhKLOmaa6Uh7X2+UvguLCzVxN1XW9x4EYHzik033Hp3X0LO+DaQG8MDQcuq6qao4qkHuMgQggLvkPLjqh00ZgFDBacMJYFkuwFlH1mshdkZ5JPJERA9JpI6xNCBESvibQ+IURA9JpI6xNCBESvibQ+IURA9DTsuHTOrVFFxixgB/eUFlU8uKJ0eDBFOu/9EvoeKnlJS2/08Tc8NOwQ8sIfMeYFjqKDjdU2sp4AAAAASUVORK5CYII='; - } } diff --git a/system/Debug/Toolbar/Views/toolbar.js b/system/Debug/Toolbar/Views/toolbar.js index 944893e10c3b..b8d0e830e210 100644 --- a/system/Debug/Toolbar/Views/toolbar.js +++ b/system/Debug/Toolbar/Views/toolbar.js @@ -9,10 +9,9 @@ var ciDebugBar = { //-------------------------------------------------------------------- - init : function() - { + init : function () { this.toolbar = document.getElementById('debug-bar'); - this.icon = document.getElementById('debug-icon'); + this.icon = document.getElementById('debug-icon'); ciDebugBar.createListeners(); ciDebugBar.setToolbarState(); @@ -23,39 +22,39 @@ var ciDebugBar = { document.getElementById('debug-icon-link').addEventListener('click', ciDebugBar.toggleToolbar, true); // Allows to highlight the row of the current history request - var btn = document.querySelector('button[data-time="'+localStorage.getItem('debugbar-time')+'"]'); + var btn = document.querySelector('button[data-time="' + localStorage.getItem('debugbar-time') + '"]'); ciDebugBar.addClass(btn.parentNode.parentNode, 'current'); historyLoad = document.getElementsByClassName('ci-history-load'); for (var i = 0; i < historyLoad.length; i++) { - historyLoad[i].addEventListener('click', function() { + historyLoad[i].addEventListener('click', function () { loadDoc(this.getAttribute('data-time')); }, true); } // Display the active Tab on page load var tab = ciDebugBar.readCookie('debug-bar-tab'); - if (document.getElementById(tab)) { - var el = document.getElementById(tab); + if (document.getElementById(tab)) + { + var el = document.getElementById(tab); el.style.display = 'block'; ciDebugBar.addClass(el, 'active'); - tab = document.querySelector('[data-tab='+tab+']'); - if (tab) { + tab = document.querySelector('[data-tab=' + tab + ']'); + if (tab) + { ciDebugBar.addClass(tab.parentNode, 'active'); } } - }, //-------------------------------------------------------------------- - createListeners : function() - { + createListeners : function () { var buttons = [].slice.call(document.querySelectorAll('#debug-bar .ci-label a')); - for (var i=0; i < buttons.length; i++) + for (var i = 0; i < buttons.length; i++) { buttons[i].addEventListener('click', ciDebugBar.showTab, true); } @@ -63,13 +62,13 @@ var ciDebugBar = { //-------------------------------------------------------------------- - showTab: function() - { + showTab: function () { // Get the target tab, if any var tab = document.getElementById(this.getAttribute('data-tab')); // If the label have not a tab stops here - if (! tab) { + if (! tab) + { return; } @@ -82,7 +81,7 @@ var ciDebugBar = { // Hide all tabs var tabs = document.querySelectorAll('#debug-bar .tab'); - for (var i=0; i < tabs.length; i++) + for (var i = 0; i < tabs.length; i++) { tabs[i].style.display = 'none'; } @@ -90,7 +89,7 @@ var ciDebugBar = { // Mark all labels as inactive var labels = document.querySelectorAll('#debug-bar .ci-label'); - for (var i=0; i < labels.length; i++) + for (var i = 0; i < labels.length; i++) { ciDebugBar.removeClass(labels[i], 'active'); } @@ -107,8 +106,7 @@ var ciDebugBar = { //-------------------------------------------------------------------- - addClass : function(el, className) - { + addClass : function (el, className) { if (el.classList) { el.classList.add(className); @@ -121,8 +119,7 @@ var ciDebugBar = { //-------------------------------------------------------------------- - removeClass : function(el, className) - { + removeClass : function (el, className) { if (el.classList) { el.classList.remove(className); @@ -131,17 +128,16 @@ var ciDebugBar = { { el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } - }, //-------------------------------------------------------------------- /** * Toggle display of a data table + * * @param obj */ - toggleDataTable : function(obj) - { + toggleDataTable : function (obj) { if (typeof obj == 'string') { obj = document.getElementById(obj + '_table'); @@ -158,12 +154,11 @@ var ciDebugBar = { /** * Toggle tool bar from full to icon and icon to full */ - toggleToolbar : function() - { + toggleToolbar : function () { var open = ciDebugBar.toolbar.style.display != 'none'; - ciDebugBar.icon.style.display = open == true ? 'inline-block' : 'none'; - ciDebugBar.toolbar.style.display = open == false ? 'inline-block' : 'none'; + ciDebugBar.icon.style.display = open == true ? 'inline-block' : 'none'; + ciDebugBar.toolbar.style.display = open == false ? 'inline-block' : 'none'; // Remember it for other page loads on this site ciDebugBar.createCookie('debug-bar-state', '', -1); @@ -176,54 +171,51 @@ var ciDebugBar = { * Sets the initial state of the toolbar (open or minimized) when * the page is first loaded to allow it to remember the state between refreshes. */ - setToolbarState: function() - { + setToolbarState: function () { var open = ciDebugBar.readCookie('debug-bar-state'); - ciDebugBar.icon.style.display = open != 'open' ? 'inline-block' : 'none'; - ciDebugBar.toolbar.style.display = open == 'open' ? 'inline-block' : 'none'; + ciDebugBar.icon.style.display = open != 'open' ? 'inline-block' : 'none'; + ciDebugBar.toolbar.style.display = open == 'open' ? 'inline-block' : 'none'; }, //-------------------------------------------------------------------- - toggleViewsHints: function() - { + toggleViewsHints: function () { // Avoid toggle hints on history requests that are not the initial if (localStorage.getItem('debugbar-time') != localStorage.getItem('debugbar-time-new')) { - var a = document.querySelector('a[data-tab="ci-views"]'); + var a = document.querySelector('a[data-tab="ci-views"]'); a.href = '#'; return; } - var nodeList = []; // [ Element, NewElement( 1 )/OldElement( 0 ) ] - var sortedComments = []; - var comments = []; + var nodeList = []; // [ Element, NewElement( 1 )/OldElement( 0 ) ] + var sortedComments = []; + var comments = []; - var getComments = function() - { - var nodes = []; - var result = []; + var getComments = function () { + var nodes = []; + var result = []; var xpathResults = document.evaluate( "//comment()[starts-with(., ' DEBUG-VIEW')]", document, null, XPathResult.ANY_TYPE, null); - var nextNode = xpathResults.iterateNext(); - while( nextNode ) + var nextNode = xpathResults.iterateNext(); + while ( nextNode ) { nodes.push( nextNode ); nextNode = xpathResults.iterateNext(); } // sort comment by opening and closing tags - for( var i = 0; i < nodes.length; ++i ) + for (var i = 0; i < nodes.length; ++i) { // get file path + name to use as key var path = nodes[i].nodeValue.substring( 18, nodes[i].nodeValue.length - 1 ); - if( nodes[i].nodeValue[12] === 'S' ) // simple check for start comment + if ( nodes[i].nodeValue[12] === 'S' ) // simple check for start comment { // create new entry result[path] = [ nodes[i], null ]; } - else if(result[path]) + else if (result[path]) { // add to existing entry result[path][1] = nodes[i]; @@ -234,14 +226,13 @@ var ciDebugBar = { }; // find node that has TargetNode as parentNode - var getParentNode = function( node, targetNode ) - { - if( node.parentNode === null ) + var getParentNode = function ( node, targetNode ) { + if ( node.parentNode === null ) { return null; } - if( node.parentNode !== targetNode ) + if ( node.parentNode !== targetNode ) { return getParentNode( node.parentNode, targetNode ); } @@ -251,20 +242,22 @@ var ciDebugBar = { // define invalid & outer ( also invalid ) elements const INVALID_ELEMENTS = [ 'NOSCRIPT', 'SCRIPT', 'STYLE' ]; - const OUTER_ELEMENTS = [ 'HTML', 'BODY', 'HEAD' ]; + const OUTER_ELEMENTS = [ 'HTML', 'BODY', 'HEAD' ]; - var getValidElementInner = function( node, reverse ) - { + var getValidElementInner = function ( node, reverse ) { // handle invalid tags - if( OUTER_ELEMENTS.indexOf( node.nodeName ) !== -1 ) + if ( OUTER_ELEMENTS.indexOf( node.nodeName ) !== -1 ) { - for( var i = 0; i < document.body.children.length; ++i ) + for (var i = 0; i < document.body.children.length; ++i) { - var index = reverse ? document.body.children.length - ( i + 1 ) : i; + var index = reverse ? document.body.children.length - ( i + 1 ) : i; var element = document.body.children[index]; // skip invalid tags - if( INVALID_ELEMENTS.indexOf( element.nodeName ) !== -1 ) continue; + if ( INVALID_ELEMENTS.indexOf( element.nodeName ) !== -1 ) + { + continue; + } return [ element, reverse ]; } @@ -273,28 +266,31 @@ var ciDebugBar = { } // get to next valid element - while( node !== null && INVALID_ELEMENTS.indexOf( node.nodeName ) !== -1 ) + while ( node !== null && INVALID_ELEMENTS.indexOf( node.nodeName ) !== -1 ) { node = reverse ? node.previousElementSibling : node.nextElementSibling; } // return non array if we couldnt find something - if( node === null ) return null; + if ( node === null ) + { + return null; + } return [ node, reverse ]; }; // get next valid element ( to be safe to add divs ) // @return [ element, skip element ] or null if we couldnt find a valid place - var getValidElement = function( nodeElement ) - { - if (nodeElement) { - if( nodeElement.nextElementSibling !== null ) + var getValidElement = function ( nodeElement ) { + if (nodeElement) + { + if ( nodeElement.nextElementSibling !== null ) { return getValidElementInner( nodeElement.nextElementSibling, false ) || getValidElementInner( nodeElement.previousElementSibling, true ); } - if( nodeElement.previousElementSibling !== null ) + if ( nodeElement.previousElementSibling !== null ) { return getValidElementInner( nodeElement.previousElementSibling, true ); } @@ -304,37 +300,47 @@ var ciDebugBar = { return null; }; - function showHints() { + function showHints() + { // Had AJAX? Reset view blocks sortedComments = getComments(); - for( var key in sortedComments ) + for (var key in sortedComments) { - var startElement = getValidElement( sortedComments[key][0] ); - var endElement = getValidElement( sortedComments[key][1] ); + var startElement = getValidElement( sortedComments[key][0] ); + var endElement = getValidElement( sortedComments[key][1] ); // skip if we couldnt get a valid element - if( startElement === null || endElement === null ) continue; + if ( startElement === null || endElement === null ) + { + continue; + } // find element which has same parent as startelement var jointParent = getParentNode( endElement[0], startElement[0].parentNode ); - if( jointParent === null ) + if ( jointParent === null ) { // find element which has same parent as endelement jointParent = getParentNode( startElement[0], endElement[0].parentNode ); - if( jointParent === null ) + if ( jointParent === null ) { // both tries failed continue; } - else startElement[0] = jointParent; + else + { + startElement[0] = jointParent; + } + } + else + { + endElement[0] = jointParent; } - else endElement[0] = jointParent; - var debugDiv = document.createElement( 'div' ); // holder - var debugPath = document.createElement( 'div' ); // path - var childArray = startElement[0].parentNode.childNodes; // target child array - var parent = startElement[0].parentNode; + var debugDiv = document.createElement( 'div' ); // holder + var debugPath = document.createElement( 'div' ); // path + var childArray = startElement[0].parentNode.childNodes; // target child array + var parent = startElement[0].parentNode; var start, end; // setup container @@ -346,30 +352,36 @@ var ciDebugBar = { // calc distance between them // start - for( var i = 0; i < childArray.length; ++i ) + for (var i = 0; i < childArray.length; ++i) { // check for comment ( start & end ) -> if its before valid start element - if( childArray[i] === sortedComments[key][1] || + if ( childArray[i] === sortedComments[key][1] || childArray[i] === sortedComments[key][0] || childArray[i] === startElement[0] ) { start = i; - if( childArray[i] === sortedComments[key][0] ) start++; // increase to skip the start comment + if ( childArray[i] === sortedComments[key][0] ) + { + start++; // increase to skip the start comment + } break; } } // adjust if we want to skip the start element - if( startElement[1] ) start++; + if ( startElement[1] ) + { + start++; + } // end - for( var i = start; i < childArray.length; ++i ) + for (var i = start; i < childArray.length; ++i) { - if( childArray[i] === endElement[0] ) + if ( childArray[i] === endElement[0] ) { end = i; // dont break to check for end comment after end valid element } - else if( childArray[i] === sortedComments[key][1] ) + else if ( childArray[i] === sortedComments[key][1] ) { // if we found the end comment, we can break end = i; @@ -379,10 +391,13 @@ var ciDebugBar = { // move elements var number = end - start; - if( endElement[1] ) number++; - for( var i = 0; i < number; ++i ) + if ( endElement[1] ) { - if( INVALID_ELEMENTS.indexOf( childArray[start] ) !== -1 ) + number++; + } + for (var i = 0; i < number; ++i) + { + if ( INVALID_ELEMENTS.indexOf( childArray[start] ) !== -1 ) { // skip invalid childs that can cause problems if moved start++; @@ -399,15 +414,16 @@ var ciDebugBar = { ciDebugBar.addClass(btn, 'active'); } - function hideHints() { - for( var i = 0; i < nodeList.length; ++i ) + function hideHints() + { + for (var i = 0; i < nodeList.length; ++i) { var index; // find index - for( var j = 0; j < nodeList[i].parentNode.childNodes.length; ++j ) + for (var j = 0; j < nodeList[i].parentNode.childNodes.length; ++j) { - if( nodeList[i].parentNode.childNodes[j] === nodeList[i] ) + if ( nodeList[i].parentNode.childNodes[j] === nodeList[i] ) { index = j; break; @@ -415,7 +431,7 @@ var ciDebugBar = { } // move child back - while( nodeList[i].childNodes.length !== 1 ) + while ( nodeList[i].childNodes.length !== 1 ) { nodeList[i].parentNode.insertBefore( nodeList[i].childNodes[1], nodeList[i].parentNode.childNodes[index].nextSibling ); index++; @@ -437,7 +453,7 @@ var ciDebugBar = { return; } - btn.parentNode.onclick = function() { + btn.parentNode.onclick = function () { if (ciDebugBar.readCookie('debug-view')) { hideHints(); @@ -457,8 +473,7 @@ var ciDebugBar = { //-------------------------------------------------------------------- - setToolbarPosition: function () - { + setToolbarPosition: function () { var btnPosition = document.getElementById('toolbar-position'); if (ciDebugBar.readCookie('debug-bar-position') === 'top') @@ -496,35 +511,33 @@ var ciDebugBar = { * @param value * @param days */ - createCookie : function(name,value,days) - { + createCookie : function (name,value,days) { if (days) { var date = new Date(); - date.setTime(date.getTime()+(days*24*60*60*1000)); + date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - var expires = "; expires="+date.toGMTString(); + var expires = "; expires=" + date.toGMTString(); } else { var expires = ""; } - document.cookie = name+"="+value+expires+"; path=/"; + document.cookie = name + "=" + value + expires + "; path=/"; }, //-------------------------------------------------------------------- - readCookie : function(name) - { + readCookie : function (name) { var nameEQ = name + "="; - var ca = document.cookie.split(';'); + var ca = document.cookie.split(';'); - for(var i=0;i < ca.length;i++) + for (var i = 0; i < ca.length; i++) { var c = ca[i]; - while (c.charAt(0)==' ') + while (c.charAt(0) == ' ') { c = c.substring(1,c.length); } diff --git a/system/Debug/Toolbar/Views/toolbar.tpl.php b/system/Debug/Toolbar/Views/toolbar.tpl.php index 9ec05e4ee5b6..d70f5091f003 100644 --- a/system/Debug/Toolbar/Views/toolbar.tpl.php +++ b/system/Debug/Toolbar/Views/toolbar.tpl.php @@ -1,9 +1,9 @@
@@ -133,7 +133,7 @@ - +
$value) : ?> @@ -244,7 +244,7 @@
-

Response ( )

+

Response ( )

@@ -272,9 +272,9 @@
diff --git a/system/Debug/Toolbar/toolbarloader.js.php b/system/Debug/Toolbar/toolbarloader.js.php index d1e09df0eb11..cb60f102a04f 100644 --- a/system/Debug/Toolbar/toolbarloader.js.php +++ b/system/Debug/Toolbar/toolbarloader.js.php @@ -1,4 +1,4 @@ - + document.addEventListener('DOMContentLoaded', loadDoc, false); function loadDoc(time) { diff --git a/system/Entity.php b/system/Entity.php index 6a313c6d0453..58bab62da351 100644 --- a/system/Entity.php +++ b/system/Entity.php @@ -29,12 +29,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ class Entity @@ -55,13 +55,17 @@ class Entity /* * Define properties that are automatically converted to Time instances. */ - 'dates' => ['created_at', 'updated_at', 'deleted_at'], + 'dates' => [ + 'created_at', + 'updated_at', + 'deleted_at', + ], /* * Array of field names and the type of value to cast them as * when they are accessed. */ - 'casts' => [] + 'casts' => [], ]; /** @@ -74,12 +78,12 @@ class Entity protected $_original = []; /** - * Holds info whenever prperties have to be casted - * - * @var boolean - **/ + * Holds info whenever prperties have to be casted + * + * @var boolean + **/ private $_cast = true; - + /** * Allows filling in Entity parameters during construction. * @@ -93,7 +97,7 @@ public function __construct(array $data = null) foreach ($properties as $key => $value) { - if (substr($key, 0, 1) == '_') + if (substr($key, 0, 1) === '_') { unset($properties[$key]); } @@ -139,15 +143,15 @@ public function fill(array $data) * through the __get() magic method so will have any casts, etc * applied to them. * - * @param bool $onlyChanged If true, only return values that have changed since object creation - * @param bool $cast If true, properties will be casted. + * @param boolean $onlyChanged If true, only return values that have changed since object creation + * @param boolean $cast If true, properties will be casted. * * @return array */ public function toArray(bool $onlyChanged = false, bool $cast = true): array { $this->_cast = $cast; - $return = []; + $return = []; // we need to loop over our properties so that we // allow our magic methods a chance to do their thing. @@ -155,7 +159,10 @@ public function toArray(bool $onlyChanged = false, bool $cast = true): array foreach ($properties as $key => $value) { - if (substr($key, 0, 1) == '_') continue; + if (substr($key, 0, 1) === '_') + { + continue; + } if ($onlyChanged && $this->_original[$key] === null && $value === null) { @@ -304,14 +311,16 @@ public function __unset(string $key) { // If not actual property exists, get out // before we confuse our data mapping. - if ( ! property_exists($this, $key)) + if (! property_exists($this, $key)) + { return; + } $this->$key = null; // Get the class' original default value for this property // so we can reset it to the original value. - $reflectionClass = new \ReflectionClass($this); + $reflectionClass = new \ReflectionClass($this); $defaultProperties = $reflectionClass->getDefaultProperties(); if (isset($defaultProperties[$key])) @@ -328,7 +337,7 @@ public function __unset(string $key) * * @param string $key * - * @return bool + * @return boolean */ public function __isset(string $key): bool { @@ -404,7 +413,7 @@ protected function mutateDate($value) /** * Provides the ability to cast an item as a specific data type. * - * @param $value + * @param $value * @param string $type * * @return mixed @@ -433,7 +442,7 @@ protected function castAs($value, string $type) $value = (object)$value; break; case 'array': - if (is_string($value) && (strpos($value,'a:') === 0 || strpos($value, 's:') === 0)) + if (is_string($value) && (strpos($value, 'a:') === 0 || strpos($value, 's:') === 0)) { $value = unserialize($value); } @@ -462,21 +471,21 @@ protected function castAs($value, string $type) /** * Cast as JSON * - * @param mixed $value - * @param bool $asArray + * @param mixed $value + * @param boolean $asArray * * @return mixed */ private function castAsJson($value, bool $asArray = false) { - $tmp = !is_null($value) ? ($asArray ? [] : new \stdClass) : null; - if(function_exists('json_decode')) + $tmp = ! is_null($value) ? ($asArray ? [] : new \stdClass) : null; + if (function_exists('json_decode')) { - if((is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0 || (strpos($value, '"') === 0 && strrpos($value, '"') === 0 ))) || is_numeric($value)) + if ((is_string($value) && (strpos($value, '[') === 0 || strpos($value, '{') === 0 || (strpos($value, '"') === 0 && strrpos($value, '"') === 0 ))) || is_numeric($value)) { $tmp = json_decode($value, $asArray); - if(json_last_error() !== JSON_ERROR_NONE) + if (json_last_error() !== JSON_ERROR_NONE) { throw CastException::forInvalidJsonFormatException(json_last_error()); } diff --git a/system/Events/Events.php b/system/Events/Events.php index bb53298600ad..2ec7db0f2a69 100644 --- a/system/Events/Events.php +++ b/system/Events/Events.php @@ -29,12 +29,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ define('EVENT_PRIORITY_LOW', 200); @@ -58,7 +58,7 @@ class Events * Flag to let us know if we've read from the Config file(s) * and have all of the defined events. * - * @var bool + * @var boolean */ protected static $initialized = false; @@ -66,19 +66,21 @@ class Events * If true, events will not actually be fired. * Useful during testing. * - * @var bool + * @var boolean */ protected static $simulate = false; /** * Stores information about the events * for display in the debug toolbar. + * * @var array */ protected static $performanceLog = []; /** * A list of found files. + * * @var array */ protected static $files = []; @@ -98,12 +100,12 @@ public static function initialize() $config = config('Modules'); - $files = [APPPATH.'Config/Events.php']; + $files = [APPPATH . 'Config/Events.php']; if ($config->shouldDiscover('events')) { $locator = Services::locator(); - $files = $locator->search('Config/Events.php'); + $files = $locator->search('Config/Events.php'); } static::$files = $files; @@ -132,23 +134,23 @@ public static function initialize() * Events::on('create', [$myInstance, 'myMethod']); // Method on an existing instance * Events::on('create', function() {}); // Closure * - * @param $event_name - * @param callable $callback - * @param int $priority + * @param $event_name + * @param callable $callback + * @param integer $priority */ public static function on($event_name, callable $callback, $priority = EVENT_PRIORITY_NORMAL) { - if ( ! isset(self::$listeners[$event_name])) + if (! isset(self::$listeners[$event_name])) { self::$listeners[$event_name] = [ - true, // If there's only 1 item, it's sorted. - [$priority], - [$callback], - ]; + true, // If there's only 1 item, it's sorted. + [$priority], + [$callback], + ]; } else { - self::$listeners[$event_name][0] = false; // Not sorted + self::$listeners[$event_name][0] = false; // Not sorted self::$listeners[$event_name][1][] = $priority; self::$listeners[$event_name][2][] = $callback; } @@ -165,12 +167,12 @@ public static function on($event_name, callable $callback, $priority = EVENT_PRI * @param $eventName * @param $arguments * - * @return bool + * @return boolean */ public static function trigger($eventName, ...$arguments): bool { // Read in our Config/events file so that we have them all! - if ( ! self::$initialized) + if (! self::$initialized) { self::initialize(); } @@ -189,8 +191,8 @@ public static function trigger($eventName, ...$arguments): bool { static::$performanceLog[] = [ 'start' => $start, - 'end' => microtime(true), - 'event' => strtolower($eventName) + 'end' => microtime(true), + 'event' => strtolower($eventName), ]; } @@ -218,13 +220,13 @@ public static function trigger($eventName, ...$arguments): bool */ public static function listeners($event_name): array { - if ( ! isset(self::$listeners[$event_name])) + if (! isset(self::$listeners[$event_name])) { return []; } // The list is not sorted - if ( ! self::$listeners[$event_name][0]) + if (! self::$listeners[$event_name][0]) { // Sort it! array_multisort(self::$listeners[$event_name][1], SORT_NUMERIC, self::$listeners[$event_name][2]); @@ -244,14 +246,14 @@ public static function listeners($event_name): array * If the listener couldn't be found, returns FALSE, else TRUE if * it was removed. * - * @param $event_name - * @param callable $listener + * @param $event_name + * @param callable $listener * - * @return bool + * @return boolean */ public static function removeListener($event_name, callable $listener): bool { - if ( ! isset(self::$listeners[$event_name])) + if (! isset(self::$listeners[$event_name])) { return false; } @@ -282,7 +284,7 @@ public static function removeListener($event_name, callable $listener): bool */ public static function removeAllListeners($event_name = null) { - if ( ! is_null($event_name)) + if (! is_null($event_name)) { unset(self::$listeners[$event_name]); } @@ -323,7 +325,7 @@ public function getFiles() * simply logged. Useful during testing when you don't actually want * the tests to run. * - * @param bool $choice + * @param boolean $choice */ public static function simulate(bool $choice = true) { diff --git a/system/Exceptions/AlertError.php b/system/Exceptions/AlertError.php index d229358bf90b..8dff43c53ed4 100644 --- a/system/Exceptions/AlertError.php +++ b/system/Exceptions/AlertError.php @@ -3,6 +3,7 @@ /** * Error: Action must be taken immediately (system/db down, etc) */ + class AlertError extends \Error { diff --git a/system/Exceptions/CastException.php b/system/Exceptions/CastException.php index b4cbbbbd55ec..a5bb06594e2e 100644 --- a/system/Exceptions/CastException.php +++ b/system/Exceptions/CastException.php @@ -3,38 +3,39 @@ /** * Cast Exceptions. */ + class CastException extends CriticalError { /** * Error code - * @var int + * + * @var integer */ protected $code = 3; public static function forInvalidJsonFormatException(int $error) - { + { switch($error) { case JSON_ERROR_DEPTH: throw new static(lang('Cast.jsonErrorDepth')); - break; + break; case JSON_ERROR_STATE_MISMATCH: throw new static(lang('Cast.jsonErrorStateMismatch')); - break; + break; case JSON_ERROR_CTRL_CHAR: throw new static(lang('Cast.jsonErrorCtrlChar')); - break; + break; case JSON_ERROR_SYNTAX: throw new static(lang('Cast.jsonErrorSyntax')); - break; + break; case JSON_ERROR_UTF8: throw new static(lang('Cast.jsonErrorUtf8')); - break; + break; default: throw new static(lang('Cast.jsonErrorUnknown')); } - } } diff --git a/system/Exceptions/ConfigException.php b/system/Exceptions/ConfigException.php index 038a7b52fe99..da76c9c4f812 100644 --- a/system/Exceptions/ConfigException.php +++ b/system/Exceptions/ConfigException.php @@ -3,12 +3,14 @@ /** * Exception for automatic logging. */ + class ConfigException extends CriticalError { /** * Error code - * @var int + * + * @var integer */ protected $code = 3; diff --git a/system/Exceptions/CriticalError.php b/system/Exceptions/CriticalError.php index b14302d30bc3..614bc140aafd 100644 --- a/system/Exceptions/CriticalError.php +++ b/system/Exceptions/CriticalError.php @@ -3,6 +3,7 @@ /** * Error: Critical conditions, like component unavailble, etc. */ + class CriticalError extends \Error { diff --git a/system/Exceptions/EmergencyError.php b/system/Exceptions/EmergencyError.php index 38aebabd7d93..832f135a0625 100644 --- a/system/Exceptions/EmergencyError.php +++ b/system/Exceptions/EmergencyError.php @@ -3,6 +3,7 @@ /** * Error: system is unusable */ + class EmergencyError extends \Error { diff --git a/system/Exceptions/ExceptionInterface.php b/system/Exceptions/ExceptionInterface.php index 48c716bf45fc..b36ebb027d78 100644 --- a/system/Exceptions/ExceptionInterface.php +++ b/system/Exceptions/ExceptionInterface.php @@ -6,6 +6,7 @@ * * catch (\CodeIgniter\Exceptions\ExceptionInterface) { ... } */ + interface ExceptionInterface { } diff --git a/system/Exceptions/FrameworkException.php b/system/Exceptions/FrameworkException.php index ee1890c532fa..567e0530beaf 100644 --- a/system/Exceptions/FrameworkException.php +++ b/system/Exceptions/FrameworkException.php @@ -8,6 +8,7 @@ * * @package CodeIgniter\Exceptions */ + class FrameworkException extends \RuntimeException implements ExceptionInterface { diff --git a/system/Exceptions/PageNotFoundException.php b/system/Exceptions/PageNotFoundException.php index 7bd3d58505b4..b70e440091aa 100644 --- a/system/Exceptions/PageNotFoundException.php +++ b/system/Exceptions/PageNotFoundException.php @@ -4,7 +4,8 @@ class PageNotFoundException extends \OutOfBoundsException implements ExceptionIn { /** * Error code - * @var int + * + * @var integer */ protected $code = 404; diff --git a/system/Files/File.php b/system/Files/File.php index d47ebb4b1de8..195d2ce2bb04 100644 --- a/system/Files/File.php +++ b/system/Files/File.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use SplFileInfo; use CodeIgniter\Files\Exceptions\FileException; use CodeIgniter\Files\Exceptions\FileNotFoundException; @@ -55,8 +56,8 @@ class File extends SplFileInfo * Run our SplFileInfo constructor with an optional verification * that the path is really a file. * - * @param string $path - * @param bool $checkFile + * @param string $path + * @param boolean $checkFile */ public function __construct(string $path, bool $checkFile = false) { @@ -82,7 +83,7 @@ public function __construct(string $path, bool $checkFile = false) * - kb Kilobytes * - mb Megabytes * - * @return int|null The file size in bytes or null if unknown. + * @return integer|null The file size in bytes or null if unknown. */ public function getSize(string $unit = 'b') { @@ -128,7 +129,7 @@ public function getMimeType(): string { if (function_exists('finfo_file')) { - $finfo = finfo_open(FILEINFO_MIME_TYPE); + $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $this->getRealPath()); finfo_close($finfo); } @@ -160,17 +161,17 @@ public function getRandomName(): string * * @param string $targetPath * @param string|null $name - * @param bool $overwrite + * @param boolean $overwrite * - * @return bool + * @return boolean */ public function move(string $targetPath, string $name = null, bool $overwrite = false) { - $targetPath = rtrim($targetPath, '/') . '/'; - $name = $name ?? $this->getBaseName(); + $targetPath = rtrim($targetPath, '/') . '/'; + $name = $name ?? $this->getBaseName(); $destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name); - if ( ! @rename($this->getPath(), $destination)) + if (! @rename($this->getPath(), $destination)) { $error = error_get_last(); throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message'])); @@ -190,9 +191,9 @@ public function move(string $targetPath, string $name = null, bool $overwrite = * last element is an integer as there may be cases that the delimiter may be present in the filename. * For the all other cases, it appends an integer starting from zero before the file's extension. * - * @param string $destination - * @param string $delimiter - * @param int $i + * @param string $destination + * @param string $delimiter + * @param integer $i * * @return string */ diff --git a/system/Filters/FilterInterface.php b/system/Filters/FilterInterface.php index f73750957e13..0baa131b4909 100644 --- a/system/Filters/FilterInterface.php +++ b/system/Filters/FilterInterface.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; diff --git a/system/Filters/Filters.php b/system/Filters/Filters.php index 75720867fdd0..fc9d0af61983 100644 --- a/system/Filters/Filters.php +++ b/system/Filters/Filters.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Config\BaseConfig; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; @@ -46,27 +47,31 @@ class Filters /** * The processed filters that will * be used to check against. + * * @var array */ protected $filters = [ 'before' => [], - 'after' => [] + 'after' => [], ]; /** * The original config file + * * @var BaseConfig */ protected $config; /** * The active IncomingRequest or CLIRequest + * * @var RequestInterface */ protected $request; /** * The active Response instance + * * @var ResponseInterface */ protected $response; @@ -74,7 +79,8 @@ class Filters /** * Whether we've done initial processing * on the filter lists. - * @var bool + * + * @var boolean */ protected $initialized = false; @@ -89,7 +95,7 @@ class Filters public function __construct($config, RequestInterface $request, ResponseInterface $response) { - $this->config = $config; + $this->config = $config; $this->request = & $request; $this->setResponse($response); } @@ -122,19 +128,19 @@ public function run(string $uri, $position = 'before') $alias = $rules; } - if ( ! array_key_exists($alias, $this->config->aliases)) + if (! array_key_exists($alias, $this->config->aliases)) { throw FilterException::forNoAlias($alias); } $class = new $this->config->aliases[$alias](); - if ( ! $class instanceof FilterInterface) + if (! $class instanceof FilterInterface) { throw FilterException::forIncorrectInterface(get_class($class)); } - if ($position == 'before') + if ($position === 'before') { $result = $class->before($this->request, $this->arguments[$alias] ?? null); @@ -160,7 +166,7 @@ public function run(string $uri, $position = 'before') return $result; } - elseif ($position == 'after') + elseif ($position === 'after') { $result = $class->after($this->request, $this->response); @@ -172,7 +178,7 @@ public function run(string $uri, $position = 'before') } } - return $position == 'before' ? $this->request : $this->response; + return $position === 'before' ? $this->request : $this->response; } //-------------------------------------------------------------------- @@ -279,7 +285,7 @@ public function enableFilter(string $name, string $when = 'before') list($name, $params) = explode(':', $name); $params = explode(',', $params); - array_walk($params, function(&$item){ + array_walk($params, function (&$item) { $item = trim($item); }); @@ -320,7 +326,7 @@ public function getArguments(string $key = null) protected function processGlobals(string $uri = null) { - if ( ! isset($this->config->globals) || ! is_array($this->config->globals)) + if (! isset($this->config->globals) || ! is_array($this->config->globals)) { return; } @@ -331,7 +337,7 @@ protected function processGlobals(string $uri = null) // Take any 'except' routes into consideration foreach ($this->config->globals['before'] as $alias => $rules) { - if ( ! is_array($rules) || ! array_key_exists('except', $rules)) + if (! is_array($rules) || ! array_key_exists('except', $rules)) { continue; } @@ -369,7 +375,7 @@ protected function processGlobals(string $uri = null) // Take any 'except' routes into consideration foreach ($this->config->globals['after'] as $alias => $rules) { - if ( ! is_array($rules) || ! array_key_exists('except', $rules)) + if (! is_array($rules) || ! array_key_exists('except', $rules)) { continue; } @@ -406,7 +412,7 @@ protected function processGlobals(string $uri = null) protected function processMethods() { - if ( ! isset($this->config->methods) || ! is_array($this->config->methods)) + if (! isset($this->config->methods) || ! is_array($this->config->methods)) { return; } @@ -425,7 +431,7 @@ protected function processMethods() protected function processFilters(string $uri = null) { - if ( ! isset($this->config->filters) || ! $this->config->filters) + if (! isset($this->config->filters) || ! $this->config->filters) { return; } @@ -454,7 +460,7 @@ protected function processFilters(string $uri = null) } $this->filters['before'] = array_merge($this->filters['before'], $matches); - $matches = []; + $matches = []; } // After diff --git a/system/Format/FormatterInterface.php b/system/Format/FormatterInterface.php index f7d1b979b30b..9a9e0c24d5ec 100644 --- a/system/Format/FormatterInterface.php +++ b/system/Format/FormatterInterface.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + interface FormatterInterface { diff --git a/system/Format/JSONFormatter.php b/system/Format/JSONFormatter.php index 241cdba6f3e7..4766da93ca37 100644 --- a/system/Format/JSONFormatter.php +++ b/system/Format/JSONFormatter.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ diff --git a/system/Format/XMLFormatter.php b/system/Format/XMLFormatter.php index 1c0ae0a43c43..a21f051e0bae 100644 --- a/system/Format/XMLFormatter.php +++ b/system/Format/XMLFormatter.php @@ -29,12 +29,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ class XMLFormatter implements FormatterInterface @@ -53,12 +53,12 @@ public function format(array $data) // SimpleXML is installed but default // but best to check, and then provide a fallback. - if ( ! extension_loaded('simplexml')) + if (! extension_loaded('simplexml')) { throw FormatException::forMissingExtension(); } - $output = new \SimpleXMLElement(""); + $output = new \SimpleXMLElement(''); $this->arrayToXML($data, $output); @@ -83,7 +83,7 @@ protected function arrayToXML(array $data, &$output) { if (is_array($value)) { - if ( ! is_numeric($key)) + if (! is_numeric($key)) { $subnode = $output->addChild("$key"); $this->arrayToXML($value, $subnode); diff --git a/system/HTTP/CLIRequest.php b/system/HTTP/CLIRequest.php index 18844a3c68b0..e194f8b753cc 100644 --- a/system/HTTP/CLIRequest.php +++ b/system/HTTP/CLIRequest.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\App; /** @@ -64,6 +65,7 @@ class CLIRequest extends Request /** * Command line options and their values. + * * @var array */ protected $options = []; @@ -213,11 +215,11 @@ protected function parseCommand() $argv = $this->getServer('argv'); // We start at 1 since we never want to include index.php - for ($i = 1; $i < $argc; $i ++ ) + for ($i = 1; $i < $argc; $i ++) { // If there's no '-' at the beginning of the argument // then add it to our segments. - if ( ! $options_found && strpos($argv[$i], '-') === false) + if (! $options_found && strpos($argv[$i], '-') === false) { $this->segments[] = filter_var($argv[$i], FILTER_SANITIZE_STRING); continue; @@ -230,7 +232,7 @@ protected function parseCommand() continue; } - $arg = filter_var(str_replace('-', '', $argv[$i]), FILTER_SANITIZE_STRING); + $arg = filter_var(str_replace('-', '', $argv[$i]), FILTER_SANITIZE_STRING); $value = null; // If the next item starts with a dash it's a value diff --git a/system/HTTP/CURLRequest.php b/system/HTTP/CURLRequest.php index ce7baaa33954..6cbbc17459ef 100644 --- a/system/HTTP/CURLRequest.php +++ b/system/HTTP/CURLRequest.php @@ -29,14 +29,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\Exceptions\HTTPException; use Config\App; @@ -46,7 +47,7 @@ * A lightweight HTTP client for sending synchronous HTTP requests * via cURL. * - * @todo Add a few helpers for dealing with JSON, forms, files, etc. + * @todo Add a few helpers for dealing with JSON, forms, files, etc. * * @package CodeIgniter\HTTP */ @@ -73,10 +74,10 @@ class CURLRequest extends Request * @var array */ protected $config = [ - 'timeout' => 0.0, + 'timeout' => 0.0, 'connect_timeout' => 150, - 'debug' => false, - 'verify' => true + 'debug' => false, + 'verify' => true, ]; /** @@ -86,14 +87,18 @@ class CURLRequest extends Request * @var array */ protected $redirectDefaults = [ - 'max' => 5, - 'strict' => true, - 'protocols' => ['http', 'https'], + 'max' => 5, + 'strict' => true, + 'protocols' => [ + 'http', + 'https', + ], ]; /** * The number of milliseconds to delay before * sending the request. + * * @var float */ protected $delay = 0.0; @@ -107,14 +112,14 @@ class CURLRequest extends Request * - timeout * - any other request options to use as defaults. * - * @param App $config - * @param URI $uri + * @param App $config + * @param URI $uri * @param ResponseInterface $response - * @param array $options + * @param array $options */ public function __construct(App $config, URI $uri, ResponseInterface $response = null, array $options = []) { - if ( ! function_exists('curl_version')) + if (! function_exists('curl_version')) { // we won't see this during travis-CI // @codeCoverageIgnoreStart @@ -125,7 +130,7 @@ public function __construct(App $config, URI $uri, ResponseInterface $response = parent::__construct($config); $this->response = $response; - $this->baseURI = $uri; + $this->baseURI = $uri; $this->parseOptions($options); } @@ -136,9 +141,9 @@ public function __construct(App $config, URI $uri, ResponseInterface $response = * Sends an HTTP request to the specified $url. If this is a relative * URL, it will be merged with $this->baseURI to form a complete URL. * - * @param $method - * @param string $url - * @param array $options + * @param $method + * @param string $url + * @param array $options * * @return \CodeIgniter\HTTP\ResponseInterface */ @@ -329,7 +334,7 @@ protected function prepareURL(string $url): string * Get the request method. Overrides the Request class' method * since users expect a different answer here. * - * @param bool|false $upper Whether to return in upper or lower case. + * @param boolean|false $upper Whether to return in upper or lower case. * * @return string */ @@ -353,7 +358,7 @@ public function send(string $method, string $url) // Reset our curl options so we're on a fresh slate. $curl_options = []; - if ( ! empty($this->config['query']) && is_array($this->config['query'])) + if (! empty($this->config['query']) && is_array($this->config['query'])) { // This is likely too naive a solution. // Should look into handling when $url already @@ -362,10 +367,10 @@ public function send(string $method, string $url) unset($this->config['query']); } - $curl_options[CURLOPT_URL] = $url; + $curl_options[CURLOPT_URL] = $url; $curl_options[CURLOPT_RETURNTRANSFER] = true; - $curl_options[CURLOPT_HEADER] = true; - $curl_options[CURLOPT_FRESH_CONNECT] = true; + $curl_options[CURLOPT_HEADER] = true; + $curl_options[CURLOPT_FRESH_CONNECT] = true; // Disable @file uploads in post data. $curl_options[CURLOPT_SAFE_UPLOAD] = true; @@ -448,13 +453,13 @@ protected function applyRequestHeaders(array $curl_options = []): array * @param string $method * @param array $curl_options * - * @return array|int + * @return array|integer */ protected function applyMethod($method, array $curl_options): array { $method = strtoupper($method); - $this->method = $method; + $this->method = $method; $curl_options[CURLOPT_CUSTOMREQUEST] = $method; $size = strlen($this->body); @@ -467,7 +472,7 @@ protected function applyMethod($method, array $curl_options): array return $curl_options; } - if ($method == 'PUT' || $method == 'POST') + if ($method === 'PUT' || $method === 'POST') { // See http://tools.ietf.org/html/rfc7230#section-3.3.2 if (is_null($this->getHeader('content-length'))) @@ -475,7 +480,7 @@ protected function applyMethod($method, array $curl_options): array $this->setHeader('Content-Length', 0); } } - else if ($method == 'HEAD') + else if ($method === 'HEAD') { $curl_options[CURLOPT_NOBODY] = 1; } @@ -494,7 +499,7 @@ protected function applyMethod($method, array $curl_options): array */ protected function applyBody(array $curl_options = []): array { - if ( ! empty($this->body)) + if (! empty($this->body)) { $curl_options[CURLOPT_POSTFIELDS] = (string) $this->getBody(); } @@ -543,19 +548,19 @@ protected function setResponseHeaders(array $headers = []) /** * Set CURL options * - * @param array $curl_options - * @param array $config + * @param array $curl_options + * @param array $config * @return array * @throws \InvalidArgumentException */ protected function setCURLOptions(array $curl_options = [], array $config = []) { // Auth Headers - if ( ! empty($config['auth'])) + if (! empty($config['auth'])) { $curl_options[CURLOPT_USERPWD] = $config['auth'][0] . ':' . $config['auth'][1]; - if ( ! empty($config['auth'][2]) && strtolower($config['auth'][2]) == 'digest') + if (! empty($config['auth'][2]) && strtolower($config['auth'][2]) === 'digest') { $curl_options[CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; } @@ -566,17 +571,17 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) } // Certificate - if ( ! empty($config['cert'])) + if (! empty($config['cert'])) { $cert = $config['cert']; if (is_array($cert)) { $curl_options[CURLOPT_SSLCERTPASSWD] = $cert[1]; - $cert = $cert[0]; + $cert = $cert[0]; } - if ( ! file_exists($cert)) + if (! file_exists($cert)) { throw HTTPException::forSSLCertNotFound($cert); } @@ -591,12 +596,12 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) { $file = realpath($config['ssl_key']); - if ( ! $file) + if (! $file) { throw HTTPException::forInvalidSSLKey($config['ssl_key']); } - $curl_options[CURLOPT_CAINFO] = $file; + $curl_options[CURLOPT_CAINFO] = $file; $curl_options[CURLOPT_SSL_VERIFYPEER] = 1; } else if (is_bool($config['verify'])) @@ -609,11 +614,11 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) if (isset($config['debug'])) { $curl_options[CURLOPT_VERBOSE] = $config['debug'] === true ? 1 : 0; - $curl_options[CURLOPT_STDERR] = is_bool($config['debug']) ? fopen('php://output', 'w+') : $config['debug']; + $curl_options[CURLOPT_STDERR] = is_bool($config['debug']) ? fopen('php://output', 'w+') : $config['debug']; } // Decode Content - if ( ! empty($config['decode_content'])) + if (! empty($config['decode_content'])) { $accept = $this->getHeaderLine('Accept-Encoding'); @@ -623,7 +628,7 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) } else { - $curl_options[CURLOPT_ENCODING] = ''; + $curl_options[CURLOPT_ENCODING] = ''; $curl_options[CURLOPT_HTTPHEADER] = 'Accept-Encoding'; } } @@ -645,7 +650,7 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) else { $curl_options[CURLOPT_FOLLOWLOCATION] = 1; - $curl_options[CURLOPT_MAXREDIRS] = $settings['max']; + $curl_options[CURLOPT_MAXREDIRS] = $settings['max']; if ($settings['strict'] === true) { @@ -669,9 +674,9 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) $curl_options[CURLOPT_CONNECTTIMEOUT_MS] = (float) $config['connect_timeout'] * 1000; // Post Data - application/x-www-form-urlencoded - if ( ! empty($config['form_params']) && is_array($config['form_params'])) + if (! empty($config['form_params']) && is_array($config['form_params'])) { - $postFields = http_build_query($config['form_params']); + $postFields = http_build_query($config['form_params']); $curl_options[CURLOPT_POSTFIELDS] = $postFields; // Ensure content-length is set, since CURL doesn't seem to @@ -681,7 +686,7 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) } // Post Data - multipart/form-data - if ( ! empty($config['multipart']) && is_array($config['multipart'])) + if (! empty($config['multipart']) && is_array($config['multipart'])) { // setting the POSTFIELDS option automatically sets multipart $curl_options[CURLOPT_POSTFIELDS] = $config['multipart']; @@ -700,13 +705,13 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) } // version - if ( ! empty($config['version'])) + if (! empty($config['version'])) { - if ($config['version'] == 1.0) + if ($config['version'] === 1.0) { $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; } - else if ($config['version'] == 1.1) + else if ($config['version'] === 1.1) { $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; } @@ -715,7 +720,7 @@ protected function setCURLOptions(array $curl_options = [], array $config = []) // Cookie if (isset($config['cookie'])) { - $curl_options[CURLOPT_COOKIEJAR] = $config['cookie']; + $curl_options[CURLOPT_COOKIEJAR] = $config['cookie']; $curl_options[CURLOPT_COOKIEFILE] = $config['cookie']; } diff --git a/system/HTTP/ContentSecurityPolicy.php b/system/HTTP/ContentSecurityPolicy.php index 33cc6325e84e..20f6c0facc8b 100644 --- a/system/HTTP/ContentSecurityPolicy.php +++ b/system/HTTP/ContentSecurityPolicy.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -53,120 +53,145 @@ class ContentSecurityPolicy /** * Used for security enforcement + * * @var array */ protected $baseURI = []; /** * Used for security enforcement + * * @var array */ protected $childSrc = []; /** * Used for security enforcement + * * @var array */ protected $connectSrc = []; /** * Used for security enforcement + * * @var array */ protected $defaultSrc = []; /** * Used for security enforcement + * * @var array */ protected $fontSrc = []; /** * Used for security enforcement + * * @var array */ protected $formAction = []; /** * Used for security enforcement + * * @var type */ protected $frameAncestors = null; /** * Used for security enforcement + * * @var array */ protected $imageSrc = []; /** * Used for security enforcement + * * @var array */ protected $mediaSrc = []; /** * Used for security enforcement + * * @var array */ protected $objectSrc = []; /** * Used for security enforcement + * * @var type */ protected $pluginTypes = null; /** * Used for security enforcement + * * @var string */ protected $reportURI = null; /** * Used for security enforcement - * @var bool + * + * @var boolean */ protected $sandbox = false; /** * Used for security enforcement + * * @var array */ protected $scriptSrc = []; /** * Used for security enforcement + * * @var array */ protected $styleSrc = []; - + /** * Used for security enforcement + * * @var array */ protected $manifestSrc = []; /** * Used for security enforcement - * @var bool + * + * @var boolean */ protected $upgradeInsecureRequests = false; /** * Used for security enforcement - * @var bool + * + * @var boolean */ protected $reportOnly = false; /** * Used for security enforcement + * * @var array */ - protected $validSources = ['self', 'none', 'unsafe-inline', 'unsafe-eval']; + protected $validSources = [ + 'self', + 'none', + 'unsafe-inline', + 'unsafe-eval', + ]; /** * Used for security enforcement + * * @var array */ protected $nonces = []; @@ -235,7 +260,7 @@ public function finalize(ResponseInterface &$response) * determine what errors need to be addressed before you turn on * all filtering. * - * @param bool|true $value + * @param boolean|true $value * * @return $this */ @@ -255,8 +280,8 @@ public function reportOnly(bool $value = true) * * @see http://www.w3.org/TR/CSP/#directive-base-uri * - * @param string $uri - * @param bool $reportOnly + * @param string $uri + * @param boolean $reportOnly * * @return $this */ @@ -279,8 +304,8 @@ public function setBaseURI($uri, bool $reportOnly) * * @see http://www.w3.org/TR/CSP/#directive-child-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -302,8 +327,8 @@ public function addChildSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-connect-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -325,8 +350,8 @@ public function addConnectSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-default-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -347,8 +372,8 @@ public function setDefaultSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-font-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -367,8 +392,8 @@ public function addFontSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-form-action * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -387,8 +412,8 @@ public function addFormAction($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-frame-ancestors * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -407,8 +432,8 @@ public function addFrameAncestor($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-img-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -427,8 +452,8 @@ public function addImageSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-media-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -438,7 +463,7 @@ public function addMediaSrc($uri, bool $reportOnly = false) return $this; } - + //-------------------------------------------------------------------- /** @@ -447,8 +472,8 @@ public function addMediaSrc($uri, bool $reportOnly = false) * * @see https://www.w3.org/TR/CSP/#directive-manifest-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -467,8 +492,8 @@ public function addManifestSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-object-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -487,8 +512,8 @@ public function addObjectSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-plugin-types * - * @param string $mime One or more plugin mime types, separate by spaces - * @param bool $reportOnly + * @param string $mime One or more plugin mime types, separate by spaces + * @param boolean $reportOnly * * @return $this */ @@ -526,8 +551,8 @@ public function setReportURI($uri) * * @see http://www.w3.org/TR/CSP/#directive-sandbox * - * @param bool $value - * @param array $flags An array of sandbox flags that can be added to the directive. + * @param boolean $value + * @param array $flags An array of sandbox flags that can be added to the directive. * * @return $this */ @@ -553,8 +578,8 @@ public function setSandbox(bool $value = true, array $flags = null) * * @see http://www.w3.org/TR/CSP/#directive-connect-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -573,8 +598,8 @@ public function addScriptSrc($uri, bool $reportOnly = false) * * @see http://www.w3.org/TR/CSP/#directive-connect-src * - * @param $uri - * @param bool $reportOnly + * @param $uri + * @param boolean $reportOnly * * @return $this */ @@ -591,7 +616,7 @@ public function addStyleSrc($uri, bool $reportOnly = false) * Sets whether the user agents should rewrite URL schemes, changing * HTTP to HTTPS. * - * @param bool|true $value + * @param boolean|true $value * * @return $this */ @@ -610,9 +635,9 @@ public function upgradeInsecureRequests(bool $value = true) /** * DRY method to add an string or array to a class property. * - * @param $options - * @param string $target - * @param bool $reportOnly If TRUE, this item will be reported, not restricted + * @param $options + * @param string $target + * @param boolean $reportOnly If TRUE, this item will be reported, not restricted */ protected function addOption($options, string $target, bool $reportOnly = false) { @@ -653,33 +678,39 @@ protected function generateNonces(ResponseInterface &$response) $body = $response->getBody(); if (empty($body)) + { return; + } - if ( ! is_array($this->styleSrc)) + if (! is_array($this->styleSrc)) + { $this->styleSrc = [$this->styleSrc]; - if ( ! is_array($this->scriptSrc)) + } + if (! is_array($this->scriptSrc)) + { $this->scriptSrc = [$this->scriptSrc]; + } // Replace style placeholders with nonces $body = preg_replace_callback( '/{csp-style-nonce}/', function ($matches) { - $nonce = bin2hex(random_bytes(12)); + $nonce = bin2hex(random_bytes(12)); - $this->styleSrc[] = 'nonce-' . $nonce; + $this->styleSrc[] = 'nonce-' . $nonce; - return "nonce={$nonce}"; - }, $body + return "nonce={$nonce}"; + }, $body ); // Replace script placeholders with nonces $body = preg_replace_callback( '/{csp-script-nonce}/', function ($matches) { - $nonce = bin2hex(random_bytes(12)); + $nonce = bin2hex(random_bytes(12)); - $this->scriptSrc[] = 'nonce-' . $nonce; + $this->scriptSrc[] = 'nonce-' . $nonce; - return "nonce={$nonce}"; - }, $body + return "nonce={$nonce}"; + }, $body ); $response->setBody($body); @@ -701,28 +732,28 @@ protected function buildHeaders(ResponseInterface &$response) $response->setHeader('Content-Security-Policy-Report-Only', []); $directives = [ - 'base-uri' => 'baseURI', - 'child-src' => 'childSrc', - 'connect-src' => 'connectSrc', - 'default-src' => 'defaultSrc', - 'font-src' => 'fontSrc', - 'form-action' => 'formAction', - 'frame-ancestors' => 'frameAncestors', - 'img-src' => 'imageSrc', - 'media-src' => 'mediaSrc', - 'object-src' => 'objectSrc', - 'plugin-types' => 'pluginTypes', - 'script-src' => 'scriptSrc', - 'style-src' => 'styleSrc', - 'manifest-src' => 'manifestSrc', - 'sandbox' => 'sandbox', - 'report-uri' => 'reportURI' + 'base-uri' => 'baseURI', + 'child-src' => 'childSrc', + 'connect-src' => 'connectSrc', + 'default-src' => 'defaultSrc', + 'font-src' => 'fontSrc', + 'form-action' => 'formAction', + 'frame-ancestors' => 'frameAncestors', + 'img-src' => 'imageSrc', + 'media-src' => 'mediaSrc', + 'object-src' => 'objectSrc', + 'plugin-types' => 'pluginTypes', + 'script-src' => 'scriptSrc', + 'style-src' => 'styleSrc', + 'manifest-src' => 'manifestSrc', + 'sandbox' => 'sandbox', + 'report-uri' => 'reportURI', ]; foreach ($directives as $name => $property) { // base_uri - if ( ! empty($this->{$property})) + if (! empty($this->{$property})) { $this->addToHeader($name, $this->{$property}); } @@ -751,7 +782,7 @@ protected function buildHeaders(ResponseInterface &$response) $response->appendHeader('Content-Security-Policy-Report-Only', $header); } - $this->tempHeaders = []; + $this->tempHeaders = []; $this->reportOnlyHeaders = []; } @@ -780,14 +811,14 @@ protected function addToHeader(string $name, $values = null) $values = [$values => 0]; } - $sources = []; + $sources = []; $reportSources = []; foreach ($values as $value => $reportOnly) { if (is_numeric($value) && is_string($reportOnly) && ! empty($reportOnly)) { - $value = $reportOnly; + $value = $reportOnly; $reportOnly = 0; } diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php index 42ff2b555c23..fe33c49fd523 100644 --- a/system/HTTP/DownloadResponse.php +++ b/system/HTTP/DownloadResponse.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 4.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 4.0.0 * @filesource */ + use CodeIgniter\Exceptions\DownloadException; use CodeIgniter\Files\File; use Config\Mimes; @@ -93,7 +94,7 @@ class DownloadResponse extends Message implements ResponseInterface public function __construct(string $filename, bool $setMime) { $this->filename = $filename; - $this->setMime = $setMime; + $this->setMime = $setMime; } /** @@ -129,7 +130,7 @@ public function setFilePath(string $filepath) /** * get content length. * - * @return int + * @return integer */ public function getContentLength() : int { @@ -152,22 +153,22 @@ public function getContentLength() : int */ private function setContentTypeByMimeType() { - $mime = null; + $mime = null; $charset = ''; if ($this->setMime === true) { if (($last_dot_position = strrpos($this->filename, '.')) !== false) { - $mime = Mimes::guessTypeFromExtension(substr($this->filename, $last_dot_position + 1)); + $mime = Mimes::guessTypeFromExtension(substr($this->filename, $last_dot_position + 1)); $charset = $this->charset; } } - if ( ! is_string($mime)) + if (! is_string($mime)) { // Set the default MIME type to send - $mime = 'application/octet-stream'; + $mime = 'application/octet-stream'; $charset = ''; } @@ -181,8 +182,8 @@ private function setContentTypeByMimeType() */ private function getDownloadFileName(): string { - $filename = $this->filename; - $x = explode('.', $this->filename); + $filename = $this->filename; + $x = explode('.', $this->filename); $extension = end($x); /* It was reported that browsers on Android 2.1 (and possibly older as well) @@ -195,8 +196,8 @@ private function getDownloadFileName(): string if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) { - $x[count($x)-1] = strtoupper($extension); - $filename = implode('.', $x); + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); } return $filename; @@ -213,14 +214,16 @@ private function getContentDisponsition() : string $utf8_filename = $download_filename; - if (strtoupper($this->charset) !== 'UTF-8') { + if (strtoupper($this->charset) !== 'UTF-8') + { $utf8_filename = mb_convert_encoding($download_filename, 'UTF-8', $this->charset); } $result = sprintf('attachment; filename="%s"', $download_filename); - if (isset($utf8_filename)) { - $result .= '; filename*=UTF-8\'\''.rawurlencode($utf8_filename); + if (isset($utf8_filename)) + { + $result .= '; filename*=UTF-8\'\'' . rawurlencode($utf8_filename); } return $result; @@ -238,6 +241,7 @@ public function getStatusCode(): int /** * {@inheritDoc} + * * @throws DownloadException */ public function setStatusCode(int $code, string $reason = '') @@ -267,7 +271,7 @@ public function setDate(\DateTime $date) { $date->setTimezone(new \DateTimeZone('UTC')); - $this->setHeader('Date', $date->format('D, d M Y H:i:s').' GMT'); + $this->setHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT'); return $this; } @@ -282,12 +286,13 @@ public function setContentType(string $mime, string $charset = 'UTF-8') // add charset attribute if not already there and provided as parm if ((strpos($mime, 'charset=') < 1) && ! empty($charset)) { - $mime .= '; charset='.$charset; + $mime .= '; charset=' . $charset; } $this->removeHeader('Content-Type'); // replace existing content type $this->setHeader('Content-Type', $mime); - if ( ! empty($charset)) { + if (! empty($charset)) + { $this->charset = $charset; } @@ -310,6 +315,7 @@ public function noCache(): self /** * {@inheritDoc} + * * @throws DownloadException */ public function setCache(array $options = []) @@ -327,7 +333,7 @@ public function setLastModified($date) if ($date instanceof \DateTime) { $date->setTimezone(new \DateTimeZone('UTC')); - $this->setHeader('Last-Modified', $date->format('D, d M Y H:i:s').' GMT'); + $this->setHeader('Last-Modified', $date->format('D, d M Y H:i:s') . ' GMT'); } elseif (is_string($date)) { @@ -366,7 +372,7 @@ public function send() */ public function buildHeaders() { - if ( ! $this->hasHeader('Content-Type')) + if (! $this->hasHeader('Content-Type')) { $this->setContentTypeByMimeType(); } @@ -405,7 +411,7 @@ public function sendHeaders() // Send all of our headers foreach ($this->getHeaders() as $name => $values) { - header($name.': '.$this->getHeaderLine($name), false, $this->getStatusCode()); + header($name . ': ' . $this->getHeaderLine($name), false, $this->getStatusCode()); } return $this; @@ -442,7 +448,7 @@ private function sendBodyByFilePath() $spl_file_object = $this->file->openFile('rb'); // Flush 1MB chunks of data - while ( ! $spl_file_object->eof() && ($data = $spl_file_object->fread(1048576)) !== false) + while (! $spl_file_object->eof() && ($data = $spl_file_object->fread(1048576)) !== false) { echo $data; } diff --git a/system/HTTP/Exceptions/HTTPException.php b/system/HTTP/Exceptions/HTTPException.php index 39c4ae81492d..0f3b22204096 100644 --- a/system/HTTP/Exceptions/HTTPException.php +++ b/system/HTTP/Exceptions/HTTPException.php @@ -10,10 +10,10 @@ class HTTPException extends FrameworkException implements ExceptionInterface /** * For CurlRequest * - * @return \CodeIgniter\HTTP\Exceptions\HTTPException - * + * @return \CodeIgniter\HTTP\Exceptions\HTTPException + * * Not testable with travis-ci - * @codeCoverageIgnore + * @codeCoverageIgnore */ public static function forMissingCurl() { @@ -50,10 +50,10 @@ public static function forInvalidSSLKey(string $key) * @param string $errorNum * @param string $error * - * @return \CodeIgniter\HTTP\Exceptions\HTTPException - * + * @return \CodeIgniter\HTTP\Exceptions\HTTPException + * * Not testable with travis-ci; we over-ride the method which triggers it - * @codeCoverageIgnore + * @codeCoverageIgnore */ public static function forCurlError(string $errorNum, string $error) { @@ -119,7 +119,7 @@ public static function forMissingResponseStatus() /** * For Response * - * @param int $code + * @param integer $code * * @return \CodeIgniter\HTTP\Exceptions\HTTPException */ @@ -131,7 +131,7 @@ public static function forInvalidStatusCode(int $code) /** * For Response * - * @param int $code + * @param integer $code * * @return \CodeIgniter\HTTP\Exceptions\HTTPException */ @@ -155,7 +155,7 @@ public static function forUnableToParseURI(string $uri) /** * For URI * - * @param int $segment + * @param integer $segment * * @return \CodeIgniter\HTTP\Exceptions\HTTPException */ @@ -167,7 +167,7 @@ public static function forURISegmentOutOfRange(int $segment) /** * For URI * - * @param int $port + * @param integer $port * * @return \CodeIgniter\HTTP\Exceptions\HTTPException */ @@ -203,7 +203,7 @@ public static function forAlreadyMoved() * * @return \CodeIgniter\HTTP\Exceptions\HTTPException */ - public static function forInvalidFile(string $path=null) + public static function forInvalidFile(string $path = null) { return new static(lang('HTTP.invalidFile')); } diff --git a/system/HTTP/Files/FileCollection.php b/system/HTTP/Files/FileCollection.php index c6460752dbc8..4f346cb1c85a 100644 --- a/system/HTTP/Files/FileCollection.php +++ b/system/HTTP/Files/FileCollection.php @@ -28,12 +28,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -88,10 +88,9 @@ public function getFile(string $name) if ($this->hasFile($name)) { - if (strpos($name, '.') !== false) { - $name = explode('.', $name); + $name = explode('.', $name); $uploadedFile = $this->getValueDotNotationSyntax($name, $this->files); if ($uploadedFile instanceof \CodeIgniter\HTTP\Files\UploadedFile) { @@ -126,7 +125,7 @@ public function getFile(string $name) * * @param string $fileID The name of the uploaded file (from the input) * - * @return bool + * @return boolean */ public function hasFile(string $fileID): bool { @@ -140,7 +139,7 @@ public function hasFile(string $fileID): bool foreach ($segments as $segment) { - if ( ! array_key_exists($segment, $el)) + if (! array_key_exists($segment, $el)) { return false; } @@ -196,13 +195,13 @@ protected function populateFiles() */ protected function createFileObject(array $array) { - if ( ! isset($array['name'])) + if (! isset($array['name'])) { $output = []; foreach ($array as $key => $values) { - if ( ! is_array($values)) + if (! is_array($values)) { continue; } @@ -243,13 +242,13 @@ protected function fixFilesArray(array $data): array { $pointer = &$output[$name]; - if ( ! is_array($value)) + if (! is_array($value)) { $pointer[$field] = $value; continue; } - $stack = [&$pointer]; + $stack = [&$pointer]; $iterator = new \RecursiveIteratorIterator( new \RecursiveArrayIterator($value), \RecursiveIteratorIterator::SELF_FIRST ); @@ -260,7 +259,7 @@ protected function fixFilesArray(array $data): array $pointer = &$stack[count($stack) - 1]; $pointer = &$pointer[$key]; $stack[] = &$pointer; - if ( ! $iterator->hasChildren()) + if (! $iterator->hasChildren()) { $pointer[$field] = $value; } diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index c3a7a69166f9..fb98b50295ae 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -29,12 +29,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ use CodeIgniter\Files\File; @@ -83,14 +83,14 @@ class UploadedFile extends File implements UploadedFileInterface * The error constant of the upload * (one of PHP's UPLOADERRXXX constants) * - * @var int + * @var integer */ protected $error; /** * Whether the file has been moved already or not. * - * @var bool + * @var boolean */ protected $hasMoved = false; @@ -99,20 +99,20 @@ class UploadedFile extends File implements UploadedFileInterface /** * Accepts the file information as would be filled in from the $_FILES array. * - * @param string $path The temporary location of the uploaded file. - * @param string $originalName The client-provided filename. - * @param string $mimeType The type of file as provided by PHP - * @param int $size The size of the file, in bytes - * @param int $error The error constant of the upload (one of PHP's UPLOADERRXXX constants) + * @param string $path The temporary location of the uploaded file. + * @param string $originalName The client-provided filename. + * @param string $mimeType The type of file as provided by PHP + * @param integer $size The size of the file, in bytes + * @param integer $error The error constant of the upload (one of PHP's UPLOADERRXXX constants) */ public function __construct(string $path, string $originalName, string $mimeType = null, int $size = null, int $error = null) { - $this->path = $path; - $this->name = $originalName; - $this->originalName = $originalName; - $this->originalMimeType = $mimeType; - $this->size = $size; - $this->error = $error; + $this->path = $path; + $this->name = $originalName; + $this->originalName = $originalName; + $this->originalMimeType = $mimeType; + $this->size = $size; + $this->error = $error; parent::__construct($path, false); } @@ -141,12 +141,12 @@ public function __construct(string $path, string $originalName, string $mimeType * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * - * @param string $targetPath Path to which to move the uploaded file. - * @param string $name the name to rename the file to. - * @param bool $overwrite State for indicating whether to overwrite the previously generated file with the same - * name or not. + * @param string $targetPath Path to which to move the uploaded file. + * @param string $name the name to rename the file to. + * @param boolean $overwrite State for indicating whether to overwrite the previously generated file with the same + * name or not. * - * @return bool + * @return boolean * * @throws \InvalidArgumentException if the $path specified is invalid. * @throws \RuntimeException on any error during the move operation. @@ -161,13 +161,13 @@ public function move(string $targetPath, string $name = null, bool $overwrite = throw HTTPException::forAlreadyMoved(); } - if ( ! $this->isValid()) + if (! $this->isValid()) { throw HTTPException::forInvalidFile(); } - $targetPath = rtrim($targetPath, '/') . '/'; - $name = is_null($name) ? $this->getName() : $name; + $targetPath = rtrim($targetPath, '/') . '/'; + $name = is_null($name) ? $this->getName() : $name; $destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name); try @@ -183,9 +183,9 @@ public function move(string $targetPath, string $name = null, bool $overwrite = @chmod($targetPath, 0777 & ~umask()); // Success, so store our new information - $this->path = $targetPath; - $this->name = basename($destination); - $this->hasMoved = true; + $this->path = $targetPath; + $this->name = basename($destination); + $this->hasMoved = true; return true; } @@ -200,11 +200,11 @@ public function move(string $targetPath, string $name = null, bool $overwrite = */ protected function setPath($path) { - if ( ! is_dir($path)) + if (! is_dir($path)) { mkdir($path, 0777, true); //create the index.html file - if ( ! file_exists($path . 'index.html')) + if (! file_exists($path . 'index.html')) { $file = fopen($path . 'index.html', 'x+'); fclose($file); @@ -220,7 +220,7 @@ protected function setPath($path) * the move() method will not work and certain properties, like * the tempName, will no longer be available. * - * @return bool + * @return boolean */ public function hasMoved(): bool { @@ -240,8 +240,8 @@ public function hasMoved(): bool * Implementations SHOULD return the value stored in the "error" key of * the file in the $_FILES array. * - * @see http://php.net/manual/en/features.file-upload.errors.php - * @return int One of PHP's UPLOAD_ERR_XXX constants. + * @see http://php.net/manual/en/features.file-upload.errors.php + * @return integer One of PHP's UPLOAD_ERR_XXX constants. */ public function getError(): int { @@ -265,14 +265,14 @@ public function getError(): int public function getErrorString() { static $errors = [ - UPLOAD_ERR_OK => 'The file uploaded with success.', - UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive.', - UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', - UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', - UPLOAD_ERR_NO_FILE => 'No file was uploaded.', - UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', - UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', - UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', + UPLOAD_ERR_OK => 'The file uploaded with success.', + UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive.', + UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', + UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', + UPLOAD_ERR_NO_FILE => 'No file was uploaded.', + UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', + UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', + UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.', ]; $error = is_null($this->error) ? UPLOAD_ERR_OK : $this->error; @@ -343,7 +343,7 @@ public function getTempName(): string * Is simply an alias for guessExtension for a safer method * than simply relying on the provided extension. * Additionaly it will return clientExtension in case if there are - * other extensions withe the same mime type. + * other extensions withe the same mime type. */ public function getExtension() : string { @@ -375,7 +375,7 @@ public function getClientExtension(): string * Returns whether the file was uploaded successfully, based on whether * it was uploaded via HTTP and has no errors. * - * @return bool + * @return boolean */ public function isValid(): bool { @@ -383,24 +383,25 @@ public function isValid(): bool } /** - * Save the uploaded file to a new location. - * - * By default, upload files are saved in writable/uploads directory. The YYYYMMDD folder - * and random file name will be created. - * - * @param string $folderName the folder name to writable/uploads directory. - * @param string $fileName the name to rename the file to. - * @return string file full path - */ - public function store($folderName = null, $fileName = null) : string - { - $folderName = $folderName ?? date('Ymd'); - $fileName = $fileName ?? $this->getRandomName(); - - // Move the uploaded file to a new location. - if ($this->move(WRITEPATH . 'uploads/' . $folderName, $fileName)) { - return $folderName . DIRECTORY_SEPARATOR . $this->name; - } + * Save the uploaded file to a new location. + * + * By default, upload files are saved in writable/uploads directory. The YYYYMMDD folder + * and random file name will be created. + * + * @param string $folderName the folder name to writable/uploads directory. + * @param string $fileName the name to rename the file to. + * @return string file full path + */ + public function store($folderName = null, $fileName = null) : string + { + $folderName = $folderName ?? date('Ymd'); + $fileName = $fileName ?? $this->getRandomName(); + + // Move the uploaded file to a new location. + if ($this->move(WRITEPATH . 'uploads/' . $folderName, $fileName)) + { + return $folderName . DIRECTORY_SEPARATOR . $this->name; + } } //-------------------------------------------------------------------- diff --git a/system/HTTP/Files/UploadedFileInterface.php b/system/HTTP/Files/UploadedFileInterface.php index 23e4f6964e6a..6548fa31eb74 100644 --- a/system/HTTP/Files/UploadedFileInterface.php +++ b/system/HTTP/Files/UploadedFileInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -51,11 +51,11 @@ interface UploadedFileInterface /** * Accepts the file information as would be filled in from the $_FILES array. * - * @param string $path The temporary location of the uploaded file. - * @param string $originalName The client-provided filename. - * @param string $mimeType The type of file as provided by PHP - * @param int $size The size of the file, in bytes - * @param int $error The error constant of the upload (one of PHP's UPLOADERRXXX constants) + * @param string $path The temporary location of the uploaded file. + * @param string $originalName The client-provided filename. + * @param string $mimeType The type of file as provided by PHP + * @param integer $size The size of the file, in bytes + * @param integer $error The error constant of the upload (one of PHP's UPLOADERRXXX constants) */ public function __construct(string $path, string $originalName, string $mimeType = null, int $size = null, int $error = null); @@ -99,7 +99,7 @@ public function move(string $targetPath, string $name = null); * the move() method will not work and certain properties, like * the tempName, will no longer be available. * - * @return bool + * @return boolean */ public function hasMoved(): bool; @@ -116,8 +116,8 @@ public function hasMoved(): bool; * Implementations SHOULD return the value stored in the "error" key of * the file in the $_FILES array. * - * @see http://php.net/manual/en/features.file-upload.errors.php - * @return int One of PHP's UPLOAD_ERR_XXX constants. + * @see http://php.net/manual/en/features.file-upload.errors.php + * @return integer One of PHP's UPLOAD_ERR_XXX constants. */ public function getError(): int; @@ -175,7 +175,7 @@ public function getClientMimeType(): string; * Returns whether the file was uploaded successfully, based on whether * it was uploaded via HTTP and has no errors. * - * @return bool + * @return boolean */ public function isValid(): bool; @@ -188,9 +188,9 @@ public function isValid(): bool; * last element is an integer as there may be cases that the delimiter may be present in the filename. * For the all other cases, it appends an integer starting from zero before the file's extension. * - * @param string $destination - * @param string $delimiter - * @param int $i + * @param string $destination + * @param string $delimiter + * @param integer $i * * @return string */ diff --git a/system/HTTP/Header.php b/system/HTTP/Header.php index fa9fe0b5860c..ad61057e2fd0 100644 --- a/system/HTTP/Header.php +++ b/system/HTTP/Header.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -66,12 +66,12 @@ class Header /** * Header constructor. name is mandatory, if a value is provided, it will be set. * - * @param string $name - * @param string|array|null $value + * @param string $name + * @param string|array|null $value */ public function __construct(string $name, $value = null) { - $this->name = $name; + $this->name = $name; $this->value = $value; } @@ -144,7 +144,7 @@ public function setValue($value = null) */ public function appendValue($value = null) { - if ( ! is_array($this->value)) + if (! is_array($this->value)) { $this->value = [$this->value]; } @@ -166,7 +166,7 @@ public function appendValue($value = null) */ public function prependValue($value = null) { - if ( ! is_array($this->value)) + if (! is_array($this->value)) { $this->value = [$this->value]; } @@ -193,7 +193,7 @@ public function getValueLine(): string { return $this->value; } - else if ( ! is_array($this->value)) + else if (! is_array($this->value)) { return ''; } @@ -208,7 +208,7 @@ public function getValueLine(): string } else if (is_array($value)) { - $key = key($value); + $key = key($value); $options[] = $key . '=' . $value[$key]; } else if (is_numeric($key)) diff --git a/system/HTTP/IncomingRequest.php b/system/HTTP/IncomingRequest.php index 75d9f60233b0..098bf892cfb5 100755 --- a/system/HTTP/IncomingRequest.php +++ b/system/HTTP/IncomingRequest.php @@ -29,14 +29,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\Exceptions\HTTPException; use CodeIgniter\HTTP\Files\FileCollection; use CodeIgniter\HTTP\Files\UploadedFile; @@ -76,7 +77,7 @@ class IncomingRequest extends Request * Enables a CSRF cookie token to be set. * Set automatically based on Config setting. * - * @var bool + * @var boolean */ protected $enableCSRF = false; @@ -131,6 +132,7 @@ class IncomingRequest extends Request /** * Holds the old data from a redirect. + * * @var array */ protected $oldInput = []; @@ -153,13 +155,13 @@ class IncomingRequest extends Request public function __construct($config, $uri = null, $body = 'php://input', UserAgent $userAgent) { // Get our body from php://input - if ($body == 'php://input') + if ($body === 'php://input') { $body = file_get_contents('php://input'); } - $this->body = $body; - $this->config = $config; + $this->body = $body; + $this->config = $config; $this->userAgent = $userAgent; parent::__construct($config); @@ -187,7 +189,7 @@ public function detectLocale($config) { $this->locale = $this->defaultLocale = $config->defaultLocale; - if ( ! $config->negotiateLocale) + if (! $config->negotiateLocale) { return; } @@ -233,7 +235,7 @@ public function setLocale(string $locale) { // If it's not a valid locale, set it // to the default locale for the site. - if ( ! in_array($locale, $this->validLocales)) + if (! in_array($locale, $this->validLocales)) { $locale = $this->defaultLocale; } @@ -251,9 +253,9 @@ public function setLocale(string $locale) { \Locale::setDefault($locale); } - } catch (\Exception $e) + } + catch (\Exception $e) { - } // @codeCoverageIgnoreEnd @@ -265,7 +267,7 @@ public function setLocale(string $locale) /** * Determines if this request was made from the command line (CLI). * - * @return bool + * @return boolean */ public function isCLI(): bool { @@ -277,7 +279,7 @@ public function isCLI(): bool /** * Test to see if a request contains the HTTP_X_REQUESTED_WITH header. * - * @return bool + * @return boolean */ public function isAJAX(): bool { @@ -291,11 +293,11 @@ public function isAJAX(): bool * Attempts to detect if the current connection is secure through * a few different methods. * - * @return bool + * @return boolean */ public function isSecure(): bool { - if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') + if (! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') { return true; } @@ -303,7 +305,7 @@ public function isSecure(): bool { return true; } - elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') + elseif (! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') { return true; } @@ -338,9 +340,9 @@ public function getVar($index = null, $filter = null, $flags = null) * If $assoc == true, then all objects in the response will be converted * to associative arrays. * - * @param bool $assoc Whether to return objects as associative arrays - * @param int $depth How many levels deep to decode - * @param int $options Bitmask of options + * @param boolean $assoc Whether to return objects as associative arrays + * @param integer $depth How many levels deep to decode + * @param integer $options Bitmask of options * * @see http://php.net/manual/en/function.json-decode.php * @@ -504,7 +506,7 @@ public function getOldInput(string $key) if (isset($_SESSION['_ci_old_input']['post'])) { $value = dot_array_search($key, $_SESSION['_ci_old_input']['post']); - if ( ! is_null($value)) + if (! is_null($value)) { return $value; } @@ -514,7 +516,7 @@ public function getOldInput(string $key) if (isset($_SESSION['_ci_old_input']['get'])) { $value = dot_array_search($key, $_SESSION['_ci_old_input']['get']); - if ( ! is_null($value)) + if (! is_null($value)) { return $value; } @@ -577,7 +579,7 @@ protected function detectURI($protocol, $baseURL) // Based on our baseURL provided by the developer (if set) // set our current domain name, scheme - if ( ! empty($baseURL)) + if (! empty($baseURL)) { // We cannot add the path here, otherwise it's possible // that the routing will not work correctly if we are @@ -591,7 +593,7 @@ protected function detectURI($protocol, $baseURL) else { // @codeCoverageIgnoreStart - if ( ! is_cli()) + if (! is_cli()) { die('You have an empty or invalid base URL. The baseURL value must be set in Config\App.php, or through the .env file.'); } @@ -639,9 +641,9 @@ public function detectPath($protocol = '') * Provides a convenient way to work with the Negotiate class * for content negotiation. * - * @param string $type - * @param array $supported - * @param bool $strictMatch + * @param string $type + * @param array $supported + * @param boolean $strictMatch * * @return string */ @@ -677,7 +679,7 @@ public function negotiate(string $type, array $supported, bool $strictMatch = fa */ protected function parseRequestURI(): string { - if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) + if (! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) { return ''; } @@ -686,27 +688,33 @@ protected function parseRequestURI(): string // contains a colon followed by a number $parts = parse_url('http://dummy' . $_SERVER['REQUEST_URI']); $query = $parts['query'] ?? ''; - $uri = $parts['path'] ?? ''; + $uri = $parts['path'] ?? ''; if (isset($_SERVER['SCRIPT_NAME'][0])) { // strip the script name from the beginning of the URI if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) + { $uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME'])); + } // if the script is nested, strip the parent folder & script from the URI elseif (strpos($uri, $_SERVER['SCRIPT_NAME']) > 0) + { $uri = (string) substr($uri, strpos($uri, $_SERVER['SCRIPT_NAME']) + strlen($_SERVER['SCRIPT_NAME'])); + } // or if index.php is implied elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) + { $uri = (string) substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME']))); + } } // This section ensures that even on servers that require the URI to contain the query string (Nginx) a correct // URI is found, and also fixes the QUERY_STRING getServer var and $_GET array. if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0) { - $query = explode('?', $query, 2); - $uri = $query[0]; + $query = explode('?', $query, 2); + $uri = $query[0]; $_SERVER['QUERY_STRING'] = $query[1] ?? ''; } else @@ -731,7 +739,7 @@ protected function parseRequestURI(): string * * Will parse QUERY_STRING and automatically detect the URI from it. * - * @return string + * @return string */ protected function parseQueryString(): string { @@ -743,9 +751,9 @@ protected function parseQueryString(): string } elseif (strncmp($uri, '/', 1) === 0) { - $uri = explode('?', $uri, 2); + $uri = explode('?', $uri, 2); $_SERVER['QUERY_STRING'] = $uri[1] ?? ''; - $uri = $uri[0]; + $uri = $uri[0]; } parse_str($_SERVER['QUERY_STRING'], $_GET); @@ -760,14 +768,14 @@ protected function parseQueryString(): string * * Do some final cleaning of the URI and return it, currently only used in self::_parse_request_uri() * - * @param string $uri + * @param string $uri * - * @return string + * @return string */ protected function removeRelativeDirectory($uri) { $uris = []; - $tok = strtok($uri, '/'); + $tok = strtok($uri, '/'); while ($tok !== false) { if (( ! empty($tok) || $tok === '0') && $tok !== '..') diff --git a/system/HTTP/Message.php b/system/HTTP/Message.php index 663255bc5208..1337f58caf9a 100644 --- a/system/HTTP/Message.php +++ b/system/HTTP/Message.php @@ -30,12 +30,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ class Message @@ -59,15 +59,21 @@ class Message /** * Protocol version + * * @var string */ protected $protocolVersion; /** * List of valid protocol versions + * * @var array */ - protected $validProtocolVersions = ['1.0', '1.1', '2']; + protected $validProtocolVersions = [ + '1.0', + '1.1', + '2', + ]; /** * Message body @@ -134,7 +140,7 @@ public function appendBody($data) public function populateHeaders() { $contentType = $_SERVER['CONTENT_TYPE'] ?? getenv('CONTENT_TYPE'); - if ( ! empty($contentType)) + if (! empty($contentType)) { $this->setHeader('Content-Type', $contentType); } @@ -182,7 +188,7 @@ public function getHeaders(): array * Returns a single header object. If multiple headers with the same * name exist, then will return an array of header objects. * - * @param string $name + * @param string $name * * @return array|\CodeIgniter\HTTP\Header */ @@ -190,9 +196,9 @@ public function getHeader($name) { $orig_name = $this->getHeaderName($name); - if ( ! isset($this->headers[$orig_name])) + if (! isset($this->headers[$orig_name])) { - return NULL; + return null; } return $this->headers[$orig_name]; @@ -205,7 +211,7 @@ public function getHeader($name) * * @param $name * - * @return bool + * @return boolean */ public function hasHeader($name): bool { @@ -235,7 +241,7 @@ public function getHeaderLine(string $name): string { $orig_name = $this->getHeaderName($name); - if ( ! array_key_exists($orig_name, $this->headers)) + if (! array_key_exists($orig_name, $this->headers)) { return ''; } @@ -255,7 +261,7 @@ public function getHeaderLine(string $name): string */ public function setHeader(string $name, $value) { - if ( ! isset($this->headers[$name])) + if (! isset($this->headers[$name])) { $this->headers[$name] = new Header($name, $value); @@ -264,7 +270,7 @@ public function setHeader(string $name, $value) return $this; } - if ( ! is_array($this->headers[$name])) + if (! is_array($this->headers[$name])) { $this->headers[$name] = [$this->headers[$name]]; } @@ -359,12 +365,12 @@ public function getProtocolVersion(): string */ public function setProtocolVersion(string $version) { - if ( ! is_numeric($version)) + if (! is_numeric($version)) { $version = substr($version, strpos($version, '/') + 1); } - if ( ! in_array($version, $this->validProtocolVersions)) + if (! in_array($version, $this->validProtocolVersions)) { throw HTTPException::forInvalidHTTPProtocol(implode(', ', $this->validProtocolVersions)); } diff --git a/system/HTTP/Negotiate.php b/system/HTTP/Negotiate.php index 1a0aa7be7e6b..383a2f8f9d15 100644 --- a/system/HTTP/Negotiate.php +++ b/system/HTTP/Negotiate.php @@ -29,14 +29,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\HTTP\Exceptions\HTTPException; /** @@ -46,7 +47,7 @@ * type match between what the application supports and what the requesting * getServer wants. * - * @see http://tools.ietf.org/html/rfc7231#section-5.3 + * @see http://tools.ietf.org/html/rfc7231#section-5.3 * @package CodeIgniter\HTTP */ class Negotiate @@ -68,7 +69,7 @@ class Negotiate */ public function __construct(\CodeIgniter\HTTP\RequestInterface $request = null) { - if ( ! is_null($request)) + if (! is_null($request)) { $this->request = $request; } @@ -100,9 +101,9 @@ public function setRequest(\CodeIgniter\HTTP\RequestInterface $request) * If no match is found, the first, highest-ranking client requested * type is returned. * - * @param array $supported - * @param bool $strictMatch If TRUE, will return an empty string when no match found. - * If FALSE, will return the first supported element. + * @param array $supported + * @param boolean $strictMatch If TRUE, will return an empty string when no match found. + * If FALSE, will return the first supported element. * * @return string */ @@ -190,11 +191,11 @@ public function language(array $supported): string * * Portions of this code base on Aura.Accept library. * - * @param array $supported App-supported values - * @param string $header header string - * @param bool $enforceTypes If TRUE, will compare media types and sub-types. - * @param bool $strictMatch If TRUE, will return empty string on no match. - * If FALSE, will return the first supported element. + * @param array $supported App-supported values + * @param string $header header string + * @param boolean $enforceTypes If TRUE, will compare media types and sub-types. + * @param boolean $strictMatch If TRUE, will return empty string on no match. + * If FALSE, will return the first supported element. * * @return string Best match */ @@ -215,13 +216,13 @@ protected function getBestMatch(array $supported, string $header = null, bool $e foreach ($acceptable as $accept) { // if acceptable quality is zero, skip it. - if ($accept['q'] == 0) + if ($accept['q'] === 0) { continue; } // if acceptable value is "anything", return the first available - if ($accept['value'] == '*' || $accept['value'] == '*/*') + if ($accept['value'] === '*' || $accept['value'] === '*/*') { return $supported[0]; } @@ -253,7 +254,7 @@ protected function getBestMatch(array $supported, string $header = null, bool $e */ public function parseHeader(string $header) { - $results = []; + $results = []; $acceptable = explode(',', $header); foreach ($acceptable as $value) @@ -284,15 +285,15 @@ public function parseHeader(string $header) } $results[] = [ - 'value' => trim($value), - 'q' => (float) $quality, - 'params' => $parameters + 'value' => trim($value), + 'q' => (float) $quality, + 'params' => $parameters, ]; } // Sort to get the highest results first usort($results, function ($a, $b) { - if ($a['q'] == $b['q']) + if ($a['q'] === $b['q']) { $a_ast = substr_count($a['value'], '*'); $b_ast = substr_count($b['value'], '*'); @@ -314,7 +315,7 @@ public function parseHeader(string $header) // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. - if ($a_ast == $b_ast) + if ($a_ast === $b_ast) { return count($b['params']) - count($a['params']); } @@ -334,21 +335,21 @@ public function parseHeader(string $header) /** * Match-maker * - * @param array $acceptable - * @param string $supported - * @param bool $enforceTypes + * @param array $acceptable + * @param string $supported + * @param boolean $enforceTypes * @return boolean */ protected function match(array $acceptable, string $supported, bool $enforceTypes = false) { $supported = $this->parseHeader($supported); - if (is_array($supported) && count($supported) == 1) + if (is_array($supported) && count($supported) === 1) { $supported = $supported[0]; } // Is it an exact match? - if ($acceptable['value'] == $supported['value']) + if ($acceptable['value'] === $supported['value']) { return $this->matchParameters($acceptable, $supported); } @@ -372,19 +373,19 @@ protected function match(array $acceptable, string $supported, bool $enforceType * @param array $acceptable * @param array $supported * - * @return bool + * @return boolean */ protected function matchParameters(array $acceptable, array $supported): bool { - if (count($acceptable['params']) != count($supported['params'])) + if (count($acceptable['params']) !== count($supported['params'])) { return false; } foreach ($supported['params'] as $label => $value) { - if ( ! isset($acceptable['params'][$label]) || - $acceptable['params'][$label] != $value) + if (! isset($acceptable['params'][$label]) || + $acceptable['params'][$label] !== $value) { return false; } @@ -402,7 +403,7 @@ protected function matchParameters(array $acceptable, array $supported): bool * @param array $acceptable * @param array $supported * - * @return bool + * @return boolean */ public function matchTypes(array $acceptable, array $supported): bool { @@ -410,19 +411,19 @@ public function matchTypes(array $acceptable, array $supported): bool list($sType, $sSubType) = explode('/', $supported['value']); // If the types don't match, we're done. - if ($aType != $sType) + if ($aType !== $sType) { return false; } // If there's an asterisk, we're cool - if ($aSubType == '*') + if ($aSubType === '*') { return true; } // Otherwise, subtypes must match also. - return $aSubType == $sSubType; + return $aSubType === $sSubType; } //-------------------------------------------------------------------- diff --git a/system/HTTP/RedirectResponse.php b/system/HTTP/RedirectResponse.php index cd12246995cc..a53495894da5 100644 --- a/system/HTTP/RedirectResponse.php +++ b/system/HTTP/RedirectResponse.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -46,13 +46,13 @@ class RedirectResponse extends Response * Sets the URI to redirect to and, optionally, the HTTP status code to use. * If no code is provided it will be automatically determined. * - * @param string $uri The URI to redirect to - * @param int|null $code HTTP status code - * @param string $method + * @param string $uri The URI to redirect to + * @param integer|null $code HTTP status code + * @param string $method * * @return $this */ - public function to(string $uri, int $code=null, string $method='auto') + public function to(string $uri, int $code = null, string $method = 'auto') { // If it appears to be a relative URL, then convert to full URL // for better security. @@ -69,14 +69,14 @@ public function to(string $uri, int $code=null, string $method='auto') * Sets the URI to redirect to but as a reverse-routed or named route * instead of a raw URI. * - * @param string $route - * @param array $params - * @param int|null $code - * @param string $method + * @param string $route + * @param array $params + * @param integer|null $code + * @param string $method * * @return $this */ - public function route(string $route, array $params=[], int $code=302, string $method='auto') + public function route(string $route, array $params = [], int $code = 302, string $method = 'auto') { $routes = Services::routes(true); @@ -96,19 +96,18 @@ public function route(string $route, array $params=[], int $code=302, string $me * Example: * return redirect()->back(); * - * @param int|null $code - * @param string $method + * @param integer|null $code + * @param string $method * * @return $this */ - public function back(int $code=null, string $method='auto') + public function back(int $code = null, string $method = 'auto') { $this->ensureSession(); return $this->redirect(previous_url(), $method, $code); } - /** * Specifies that the current $_GET and $_POST arrays should be * packaged up with the response. It will then be available via @@ -121,8 +120,8 @@ public function withInput() $session = $this->ensureSession(); $input = [ - 'get' => $_GET ?? [], - 'post' => $_POST ?? [], + 'get' => $_GET ?? [], + 'post' => $_POST ?? [], ]; $session->setFlashdata('_ci_old_input', $input); @@ -168,7 +167,7 @@ protected function ensureSession() // Ensure we have the session started up. // true for travis-ci, so not coverable // @codeCoverageIgnoreStart - if ( ! isset($_SESSION)) + if (! isset($_SESSION)) { $session->start(); } diff --git a/system/HTTP/Request.php b/system/HTTP/Request.php index 37fd8573a0d0..65bad042e289 100644 --- a/system/HTTP/Request.php +++ b/system/HTTP/Request.php @@ -27,18 +27,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ /** * Representation of an iHTTP request. - * */ class Request extends Message implements RequestInterface { @@ -67,6 +66,7 @@ class Request extends Message implements RequestInterface /** * Stores values we've retrieved from * PHP globals. + * * @var array */ protected $globals = []; @@ -94,13 +94,13 @@ public function __construct($config) */ public function getIPAddress(): string { - if ( ! empty($this->ipAddress)) + if (! empty($this->ipAddress)) { return $this->ipAddress; } $proxy_ips = $this->proxyIPs; - if ( ! empty($this->proxyIPs) && ! is_array($this->proxyIPs)) + if (! empty($this->proxyIPs) && ! is_array($this->proxyIPs)) { $proxy_ips = explode(',', str_replace(' ', '', $this->proxyIPs)); } @@ -111,16 +111,16 @@ public function getIPAddress(): string { foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'] as $header) { - if (($spoof = $this->getServer($header)) !== NULL) + if (($spoof = $this->getServer($header)) !== null) { // Some proxies typically list the whole chain of IP // addresses through which the client has reached us. // e.g. client_ip, proxy_ip1, proxy_ip2, etc. sscanf($spoof, '%[^,]', $spoof); - if ( ! $this->isValidIP($spoof)) + if (! $this->isValidIP($spoof)) { - $spoof = NULL; + $spoof = null; } else { @@ -131,10 +131,10 @@ public function getIPAddress(): string if ($spoof) { - for ($i = 0, $c = count($proxy_ips); $i < $c; $i ++ ) + for ($i = 0, $c = count($proxy_ips); $i < $c; $i ++) { // Check if we have an IP address or a subnet - if (strpos($proxy_ips[$i], '/') === FALSE) + if (strpos($proxy_ips[$i], '/') === false) { // An IP address (and not a subnet) is specified. // We can compare right away. @@ -151,13 +151,13 @@ public function getIPAddress(): string isset($separator) || $separator = $this->isValidIP($this->ipAddress, 'ipv6') ? ':' : '.'; // If the proxy entry doesn't match the IP protocol - skip it - if (strpos($proxy_ips[$i], $separator) === FALSE) + if (strpos($proxy_ips[$i], $separator) === false) { continue; } // Convert the REMOTE_ADDR IP address to binary, if needed - if ( ! isset($ip, $sprintf)) + if (! isset($ip, $sprintf)) { if ($separator === ':') { @@ -166,7 +166,7 @@ public function getIPAddress(): string ) ); - for ($j = 0; $j < 8; $j ++ ) + for ($j = 0; $j < 8; $j ++) { $ip[$j] = intval($ip[$j], 16); } @@ -175,7 +175,7 @@ public function getIPAddress(): string } else { - $ip = explode('.', $this->ipAddress); + $ip = explode('.', $this->ipAddress); $sprintf = '%08b%08b%08b%08b'; } @@ -189,7 +189,7 @@ public function getIPAddress(): string if ($separator === ':') { $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr)); - for ($i = 0; $i < 8; $i ++ ) + for ($i = 0; $i < 8; $i ++) { $netaddr[$i] = intval($netaddr[$i], 16); } @@ -209,7 +209,7 @@ public function getIPAddress(): string } } - if ( ! $this->isValidIP($this->ipAddress)) + if (! $this->isValidIP($this->ipAddress)) { return $this->ipAddress = '0.0.0.0'; } @@ -222,10 +222,10 @@ public function getIPAddress(): string /** * Validate an IP address * - * @param string $ip IP Address - * @param string $which IP protocol: 'ipv4' or 'ipv6' + * @param string $ip IP Address + * @param string $which IP protocol: 'ipv4' or 'ipv6' * - * @return bool + * @return boolean */ public function isValidIP(string $ip = null, string $which = null): bool { @@ -238,7 +238,7 @@ public function isValidIP(string $ip = null, string $which = null): bool $which = FILTER_FLAG_IPV6; break; default: - $which = NULL; + $which = null; break; } @@ -250,7 +250,7 @@ public function isValidIP(string $ip = null, string $which = null): bool /** * Get the request method. * - * @param bool $upper Whether to return in upper or lower case. + * @param boolean $upper Whether to return in upper or lower case. * * @return string */ @@ -280,9 +280,9 @@ public function setMethod(string $method) /** * Fetch an item from the $_SERVER array. * - * @param int|null $index Index for item to be fetched from $_SERVER - * @param int|null $filter A filter name to be applied - * @param null $flags + * @param integer|null $index Index for item to be fetched from $_SERVER + * @param integer|null $filter A filter name to be applied + * @param null $flags * * @return mixed */ @@ -313,7 +313,7 @@ public function getEnv($index = null, $filter = null, $flags = null) * Allows manually setting the value of PHP global, like $_GET, $_POST, etc. * * @param string $method - * @param $value + * @param $value * * @return $this */ @@ -336,14 +336,14 @@ public function setGlobal(string $method, $value) * * http://php.net/manual/en/filter.filters.sanitize.php * - * @param int $method Input filter constant + * @param integer $method Input filter constant * @param string|array $index - * @param int $filter Filter constant + * @param integer $filter Filter constant * @param null $flags * * @return mixed */ - public function fetchGlobal($method, $index = null, $filter = null, $flags = null ) + public function fetchGlobal($method, $index = null, $filter = null, $flags = null) { $method = strtolower($method); diff --git a/system/HTTP/RequestInterface.php b/system/HTTP/RequestInterface.php index 9306f518b0ad..df91206610d9 100644 --- a/system/HTTP/RequestInterface.php +++ b/system/HTTP/RequestInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -58,10 +58,10 @@ public function getIPAddress(): string; /** * Validate an IP address * - * @param string $ip IP Address - * @param string $which IP protocol: 'ipv4' or 'ipv6' + * @param string $ip IP Address + * @param string $which IP protocol: 'ipv4' or 'ipv6' * - * @return bool + * @return boolean */ public function isValidIP(string $ip, string $which = null): bool; @@ -70,7 +70,7 @@ public function isValidIP(string $ip, string $which = null): bool; /** * Get the request method. * - * @param bool $upper Whether to return in upper or lower case. + * @param boolean $upper Whether to return in upper or lower case. * * @return string */ @@ -81,8 +81,8 @@ public function getMethod($upper = false): string; /** * Fetch an item from the $_SERVER array. * - * @param string $index Index for item to be fetched from $_SERVER - * @param null $filter A filter name to be applied + * @param string $index Index for item to be fetched from $_SERVER + * @param null $filter A filter name to be applied * @return mixed */ public function getServer($index = null, $filter = null); diff --git a/system/HTTP/Response.php b/system/HTTP/Response.php index 127f667c21ce..fb160123d73e 100644 --- a/system/HTTP/Response.php +++ b/system/HTTP/Response.php @@ -27,21 +27,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\App; use Config\Format; use CodeIgniter\HTTP\Exceptions\HTTPException; /** * Redirect exception - * */ class RedirectException extends \Exception { @@ -120,8 +120,8 @@ class Response extends Message implements ResponseInterface 421 => 'Misdirected Request', // http://www.iana.org/go/rfc7540 Section 9.1.2 422 => 'Unprocessable Entity', // http://www.iana.org/go/rfc4918 423 => 'Locked', // http://www.iana.org/go/rfc4918 - 424 => 'Failed Dependency', // http://www.iana.org/go/rfc4918 - 425 => 'Too Early', // https://datatracker.ietf.org/doc/draft-ietf-httpbis-replay/ + 424 => 'Failed Dependency', // http://www.iana.org/go/rfc4918 + 425 => 'Too Early', // https://datatracker.ietf.org/doc/draft-ietf-httpbis-replay/ 426 => 'Upgrade Required', 428 => 'Precondition Required', // 1.1; http://www.ietf.org/rfc/rfc6585.txt 429 => 'Too Many Requests', // 1.1; http://www.ietf.org/rfc/rfc6585.txt @@ -154,14 +154,14 @@ class Response extends Message implements ResponseInterface /** * The current status code for this response. * - * @var int + * @var integer */ protected $statusCode = 200; /** * Whether Content Security Policy is being enforced. * - * @var bool + * @var boolean */ protected $CSPEnabled = false; @@ -196,14 +196,14 @@ class Response extends Message implements ResponseInterface /** * Cookie will only be set if a secure HTTPS connection exists. * - * @var bool + * @var boolean */ protected $cookieSecure = false; /** * Cookie will only be accessible via HTTP(S) (no javascript) * - * @var bool + * @var boolean */ protected $cookieHTTPOnly = false; @@ -217,7 +217,7 @@ class Response extends Message implements ResponseInterface /** * If true, will not write output. Useful during testing. * - * @var bool + * @var boolean */ protected $pretend = false; @@ -264,7 +264,7 @@ public function __construct($config) /** * Turns "pretend" mode on or off to aid in testing. * - * @param bool $pretend + * @param boolean $pretend * * @return $this */ @@ -281,7 +281,7 @@ public function pretend(bool $pretend = true) * The status code is a 3-digit integer result code of the getServer's attempt * to understand and satisfy the request. * - * @return int Status code. + * @return integer Status code. */ public function getStatusCode(): int { @@ -304,10 +304,10 @@ public function getStatusCode(): int * @see http://tools.ietf.org/html/rfc7231#section-6 * @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * - * @param int $code The 3-digit integer result code to set. - * @param string $reason The reason phrase to use with the - * provided status code; if none is provided, will - * default to the IANA name. + * @param integer $code The 3-digit integer result code to set. + * @param string $reason The reason phrase to use with the + * provided status code; if none is provided, will + * default to the IANA name. * * @return self * @throws \InvalidArgumentException For invalid status code arguments. @@ -376,7 +376,7 @@ public function setDate(\DateTime $date) { $date->setTimezone(new \DateTimeZone('UTC')); - $this->setHeader('Date', $date->format('D, d M Y H:i:s').' GMT'); + $this->setHeader('Date', $date->format('D, d M Y H:i:s') . ' GMT'); return $this; } @@ -397,7 +397,7 @@ public function setContentType(string $mime, string $charset = 'UTF-8') // add charset attribute if not already there and provided as parm if ((strpos($mime, 'charset=') < 1) && ! empty($charset)) { - $mime .= '; charset='.$charset; + $mime .= '; charset=' . $charset; } $this->removeHeader('Content-Type'); // replace existing content type @@ -433,9 +433,9 @@ public function getJSON() { $body = $this->body; - if ($this->bodyFormat != 'json') + if ($this->bodyFormat !== 'json') { - $config = config(Format::class); + $config = config(Format::class); $formatter = $config->getFormatter('application/json'); $body = $formatter->format($body); @@ -471,9 +471,9 @@ public function getXML() { $body = $this->body; - if ($this->bodyFormat != 'xml') + if ($this->bodyFormat !== 'xml') { - $config = config(Format::class); + $config = config(Format::class); $formatter = $config->getFormatter('application/xml'); $body = $formatter->format($body); @@ -488,7 +488,7 @@ public function getXML() * Handles conversion of the of the data into the appropriate format, * and sets the correct Content-Type header for our response. * - * @param $body + * @param $body * @param string $format Valid: json, xml * * @return mixed @@ -611,7 +611,7 @@ public function setLastModified($date) if ($date instanceof \DateTime) { $date->setTimezone(new \DateTimeZone('UTC')); - $this->setHeader('Last-Modified', $date->format('D, d M Y H:i:s').' GMT'); + $this->setHeader('Last-Modified', $date->format('D, d M Y H:i:s') . ' GMT'); } elseif (is_string($date)) { @@ -638,9 +638,10 @@ public function send() if ($this->CSPEnabled === true) { $this->CSP->finalize($this); - }else{ - - $this->body = str_replace(['{csp-style-nonce}','{csp-script-nonce}'], '', $this->body); + } + else + { + $this->body = str_replace(['{csp-style-nonce}', '{csp-script-nonce}'], '', $this->body); } $this->sendHeaders(); @@ -679,7 +680,7 @@ public function sendHeaders() // Send all of our headers foreach ($this->getHeaders() as $name => $values) { - header($name.': '.$this->getHeaderLine($name), false, $this->statusCode); + header($name . ': ' . $this->getHeaderLine($name), false, $this->statusCode); } return $this; @@ -714,9 +715,9 @@ public function getBody() /** * Perform a redirect to a new URL, in two flavors: header or location. * - * @param string $uri The URI to redirect to - * @param string $method - * @param int $code The type of redirection, defaults to 302 + * @param string $uri The URI to redirect to + * @param string $method + * @param integer $code The type of redirection, defaults to 302 * * @return $this * @throws \CodeIgniter\HTTP\RedirectException @@ -725,7 +726,7 @@ public function redirect(string $uri, string $method = 'auto', int $code = null) { // IIS environment likely? Use 'refresh' for better compatibility if ($method === 'auto' && isset($_SERVER['SERVER_SOFTWARE']) - && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) + && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) { $method = 'refresh'; } @@ -746,7 +747,7 @@ public function redirect(string $uri, string $method = 'auto', int $code = null) switch ($method) { case 'refresh': - $this->setHeader('Refresh', '0;url='.$uri); + $this->setHeader('Refresh', '0;url=' . $uri); break; default: $this->setHeader('Location', $uri); @@ -768,14 +769,14 @@ public function redirect(string $uri, string $method = 'auto', int $code = null) * Accepts an arbitrary number of binds (up to 7) or an associateive * array in the first parameter containing all the values. * - * @param string|array $name Cookie name or array containing binds - * @param string $value Cookie value - * @param string $expire Cookie expiration time in seconds - * @param string $domain Cookie domain (e.g.: '.yourdomain.com') - * @param string $path Cookie path (default: '/') - * @param string $prefix Cookie name prefix - * @param bool|false $secure Whether to only transfer cookies via SSL - * @param bool|false $httponly Whether only make the cookie accessible via HTTP (no javascript) + * @param string|array $name Cookie name or array containing binds + * @param string $value Cookie value + * @param string $expire Cookie expiration time in seconds + * @param string $domain Cookie domain (e.g.: '.yourdomain.com') + * @param string $path Cookie path (default: '/') + * @param string $prefix Cookie name prefix + * @param boolean|false $secure Whether to only transfer cookies via SSL + * @param boolean|false $httponly Whether only make the cookie accessible via HTTP (no javascript) */ public function setCookie( $name, @@ -786,7 +787,8 @@ public function setCookie( $prefix = '', $secure = false, $httponly = false - ) { + ) + { if (is_array($name)) { // always leave 'name' in last place, as the loop will break otherwise, due to $$item @@ -804,7 +806,7 @@ public function setCookie( $prefix = $this->cookiePrefix; } - if ($domain == '' && $this->cookieDomain != '') + if ($domain === '' && $this->cookieDomain !== '') { $domain = $this->cookieDomain; } @@ -826,15 +828,15 @@ public function setCookie( if (! is_numeric($expire)) { - $expire = time()-86500; + $expire = time() - 86500; } else { - $expire = ($expire > 0) ? time()+$expire : 0; + $expire = ($expire > 0) ? time() + $expire : 0; } $this->cookies[] = [ - 'name' => $prefix.$name, + 'name' => $prefix . $name, 'value' => $value, 'expires' => $expire, 'path' => $path, @@ -855,7 +857,7 @@ public function setCookie( * @param null $value * @param string $prefix * - * @return bool + * @return boolean */ public function hasCookie(string $name, $value = null, string $prefix = '') { @@ -864,11 +866,11 @@ public function hasCookie(string $name, $value = null, string $prefix = '') $prefix = $this->cookiePrefix; } - $name = $prefix.$name; + $name = $prefix . $name; foreach ($this->cookies as $cookie) { - if ($cookie['name'] != $prefix.$name) + if ($cookie['name'] !== $prefix . $name) { continue; } @@ -878,7 +880,7 @@ public function hasCookie(string $name, $value = null, string $prefix = '') return true; } - return $cookie['value'] == $value; + return $cookie['value'] === $value; } return false; @@ -899,11 +901,11 @@ public function getCookie(string $name, string $prefix = '') $prefix = $this->cookiePrefix; } - $name = $prefix.$name; + $name = $prefix . $name; foreach ($this->cookies as $cookie) { - if ($cookie['name'] == $name) + if ($cookie['name'] === $name) { return $cookie; } @@ -913,7 +915,7 @@ public function getCookie(string $name, string $prefix = '') /** * Sets a cookie to be deleted when the response is sent. * - * @param $name + * @param $name * @param string $domain * @param string $path * @param string $prefix @@ -925,13 +927,13 @@ public function deleteCookie($name, string $domain = '', string $path = '/', str $prefix = $this->cookiePrefix; } - $name = $prefix.$name; + $name = $prefix . $name; foreach ($this->cookies as &$cookie) { - if ($cookie['name'] == $name) + if ($cookie['name'] === $name) { - $cookie['value'] = ''; + $cookie['value'] = ''; $cookie['expires'] = ''; break; @@ -966,9 +968,9 @@ protected function sendCookies() * Generates the headers that force a download to happen. And * sends the file to the browser. * - * @param string $filename The path to the file to send - * @param string $data The data to be downloaded - * @param bool $setMime Whether to try and send the actual MIME type + * @param string $filename The path to the file to send + * @param string $data The data to be downloaded + * @param boolean $setMime Whether to try and send the actual MIME type */ public function download(string $filename = '', $data = '', bool $setMime = false) { diff --git a/system/HTTP/ResponseInterface.php b/system/HTTP/ResponseInterface.php index f1256dbd5e2b..e37adb1c7073 100644 --- a/system/HTTP/ResponseInterface.php +++ b/system/HTTP/ResponseInterface.php @@ -27,12 +27,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ @@ -48,7 +48,7 @@ * - Message body * * @package CodeIgniter\HTTP - * @mixin \CodeIgniter\HTTP\RedirectResponse + * @mixin \CodeIgniter\HTTP\RedirectResponse */ interface ResponseInterface { @@ -58,75 +58,75 @@ interface ResponseInterface * From https://en.wikipedia.org/wiki/List_of_HTTP_status_codes */ // Informational - const HTTP_CONTINUE = 100; + const HTTP_CONTINUE = 100; const HTTP_SWITCHING_PROTOCOLS = 101; - const HTTP_PROCESSING = 102; - const HTTP_EARLY_HINTS = 103; + const HTTP_PROCESSING = 102; + const HTTP_EARLY_HINTS = 103; // Success - const HTTP_OK = 200; - const HTTP_CREATED = 201; - const HTTP_ACCEPTED = 202; + const HTTP_OK = 200; + const HTTP_CREATED = 201; + const HTTP_ACCEPTED = 202; const HTTP_NONAUTHORITATIVE_INFORMATION = 203; - const HTTP_NO_CONTENT = 204; - const HTTP_RESET_CONTENT = 205; - const HTTP_PARTIAL_CONTENT = 206; - const HTTP_MULTI_STATUS = 207; - const HTTP_ALREADY_REPORTED = 208; - const HTTP_IM_USED = 226; + const HTTP_NO_CONTENT = 204; + const HTTP_RESET_CONTENT = 205; + const HTTP_PARTIAL_CONTENT = 206; + const HTTP_MULTI_STATUS = 207; + const HTTP_ALREADY_REPORTED = 208; + const HTTP_IM_USED = 226; // Redirection - const HTTP_MULTIPLE_CHOICES = 300; - const HTTP_MOVED_PERMANENTLY = 301; - const HTTP_FOUND = 302; - const HTTP_SEE_OTHER = 303; - const HTTP_NOT_MODIFIED = 304; - const HTTP_USE_PROXY = 305; - const HTTP_SWITCH_PROXY = 306; + const HTTP_MULTIPLE_CHOICES = 300; + const HTTP_MOVED_PERMANENTLY = 301; + const HTTP_FOUND = 302; + const HTTP_SEE_OTHER = 303; + const HTTP_NOT_MODIFIED = 304; + const HTTP_USE_PROXY = 305; + const HTTP_SWITCH_PROXY = 306; const HTTP_TEMPORARY_REDIRECT = 307; const HTTP_PERMANENT_REDIRECT = 308; // Client Error - const HTTP_BAD_REQUEST = 400; - const HTTP_UNAUTHORIZED = 401; - const HTTP_PAYMENT_REQUIRED = 402; - const HTTP_FORBIDDEN = 403; - const HTTP_NOT_FOUND = 404; - const HTTP_METHOD_NOT_ALLOWED = 405; - const HTTP_NOT_ACCEPTABLE = 406; - const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; - const HTTP_REQUEST_TIMEOUT = 408; - const HTTP_CONFLICT = 409; - const HTTP_GONE = 410; - const HTTP_LENGTH_REQUIRED = 411; - const HTTP_PRECONDITION_FAILED = 412; - const HTTP_PAYLOAD_TOO_LARGE = 413; - const HTTP_URI_TOO_LONG = 414; - const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; - const HTTP_RANGE_NOT_SATISFIABLE = 416; - const HTTP_EXPECTATION_FAILED = 417; - const HTTP_IM_A_TEAPOT = 418; - const HTTP_MISDIRECTED_REQUEST = 421; - const HTTP_UNPROCESSABLE_ENTITY = 422; - const HTTP_LOCKED = 423; - const HTTP_FAILED_DEPENDENCY = 424; - const HTTP_TOO_EARLY = 425; - const HTTP_UPGRADE_REQUIRED = 426; - const HTTP_PRECONDITION_REQUIRED = 428; - const HTTP_TOO_MANY_REQUESTS = 429; + const HTTP_BAD_REQUEST = 400; + const HTTP_UNAUTHORIZED = 401; + const HTTP_PAYMENT_REQUIRED = 402; + const HTTP_FORBIDDEN = 403; + const HTTP_NOT_FOUND = 404; + const HTTP_METHOD_NOT_ALLOWED = 405; + const HTTP_NOT_ACCEPTABLE = 406; + const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; + const HTTP_REQUEST_TIMEOUT = 408; + const HTTP_CONFLICT = 409; + const HTTP_GONE = 410; + const HTTP_LENGTH_REQUIRED = 411; + const HTTP_PRECONDITION_FAILED = 412; + const HTTP_PAYLOAD_TOO_LARGE = 413; + const HTTP_URI_TOO_LONG = 414; + const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; + const HTTP_RANGE_NOT_SATISFIABLE = 416; + const HTTP_EXPECTATION_FAILED = 417; + const HTTP_IM_A_TEAPOT = 418; + const HTTP_MISDIRECTED_REQUEST = 421; + const HTTP_UNPROCESSABLE_ENTITY = 422; + const HTTP_LOCKED = 423; + const HTTP_FAILED_DEPENDENCY = 424; + const HTTP_TOO_EARLY = 425; + const HTTP_UPGRADE_REQUIRED = 426; + const HTTP_PRECONDITION_REQUIRED = 428; + const HTTP_TOO_MANY_REQUESTS = 429; const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; - const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; - const HTTP_CLIENT_CLOSED_REQUEST = 499; + const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; + const HTTP_CLIENT_CLOSED_REQUEST = 499; // Server Error - const HTTP_INTERNAL_SERVER_ERROR = 500; - const HTTP_NOT_IMPLEMENTED = 501; - const HTTP_BAD_GATEWAY = 502; - const HTTP_SERVICE_UNAVAILABLE = 503; - const HTTP_GATEWAY_TIMEOUT = 504; - const HTTP_HTTP_VERSION_NOT_SUPPORTED = 505; - const HTTP_VARIANT_ALSO_NEGOTIATES = 506; - const HTTP_INSUFFICIENT_STORAGE = 507; - const HTTP_LOOP_DETECTED = 508; - const HTTP_NOT_EXTENDED = 510; + const HTTP_INTERNAL_SERVER_ERROR = 500; + const HTTP_NOT_IMPLEMENTED = 501; + const HTTP_BAD_GATEWAY = 502; + const HTTP_SERVICE_UNAVAILABLE = 503; + const HTTP_GATEWAY_TIMEOUT = 504; + const HTTP_HTTP_VERSION_NOT_SUPPORTED = 505; + const HTTP_VARIANT_ALSO_NEGOTIATES = 506; + const HTTP_INSUFFICIENT_STORAGE = 507; + const HTTP_LOOP_DETECTED = 508; + const HTTP_NOT_EXTENDED = 510; const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; - const HTTP_NETWORK_CONNECT_TIMEOUT_ERROR = 599; + const HTTP_NETWORK_CONNECT_TIMEOUT_ERROR = 599; /** * Gets the response status code. @@ -134,7 +134,7 @@ interface ResponseInterface * The status code is a 3-digit integer result code of the getServer's attempt * to understand and satisfy the request. * - * @return int Status code. + * @return integer Status code. */ public function getStatusCode(): int; @@ -149,10 +149,10 @@ public function getStatusCode(): int; * @see http://tools.ietf.org/html/rfc7231#section-6 * @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * - * @param int $code The 3-digit integer result code to set. - * @param string $reason The reason phrase to use with the - * provided status code; if none is provided, will - * default to the IANA name. + * @param integer $code The 3-digit integer result code to set. + * @param string $reason The reason phrase to use with the + * provided status code; if none is provided, will + * default to the IANA name. * * @return self * @throws \InvalidArgumentException For invalid status code arguments. diff --git a/system/HTTP/URI.php b/system/HTTP/URI.php index 80649dd13b16..d4f11013f494 100644 --- a/system/HTTP/URI.php +++ b/system/HTTP/URI.php @@ -30,12 +30,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ class URI @@ -133,17 +133,17 @@ class URI * @var array */ protected $defaultPorts = [ - 'http' => 80, - 'https' => 443, - 'ftp' => 21, - 'sftp' => 22, + 'http' => 80, + 'https' => 443, + 'ftp' => 21, + 'sftp' => 22, ]; /** * Whether passwords should be shown in userInfo/authority calls. * Default to false because URIs often show up in logs * - * @var bool + * @var boolean */ protected $showPassword = false; @@ -158,7 +158,7 @@ class URI */ public function __construct(string $uri = null) { - if ( ! is_null($uri)) + if (! is_null($uri)) { $this->setURI($uri); } @@ -175,7 +175,7 @@ public function __construct(string $uri = null) */ public function setURI(string $uri = null) { - if ( ! is_null($uri)) + if (! is_null($uri)) { $parts = parse_url($uri); @@ -203,7 +203,7 @@ public function setURI(string $uri = null) * The trailing ":" character is not part of the scheme and MUST NOT be * added. * - * @see https://tools.ietf.org/html/rfc3986#section-3.1 + * @see https://tools.ietf.org/html/rfc3986#section-3.1 * @return string The URI scheme. */ public function getScheme(): string @@ -230,7 +230,7 @@ public function getScheme(): string * * @see https://tools.ietf.org/html/rfc3986#section-3.2 * - * @param bool $ignorePort + * @param boolean $ignorePort * * @return string The URI authority, in "[user-info@]host[:port]" format. */ @@ -243,16 +243,16 @@ public function getAuthority(bool $ignorePort = false): string $authority = $this->host; - if ( ! empty($this->getUserInfo())) + if (! empty($this->getUserInfo())) { $authority = $this->getUserInfo() . '@' . $authority; } - if ( ! empty($this->port) && ! $ignorePort) + if (! empty($this->port) && ! $ignorePort) { // Don't add port if it's a standard port for // this scheme - if ($this->port != $this->defaultPorts[$this->scheme]) + if ($this->port !== $this->defaultPorts[$this->scheme]) { $authority .= ':' . $this->port; } @@ -303,7 +303,7 @@ public function getUserInfo() * Temporarily sets the URI to show a password in userInfo. Will * reset itself after the first call to authority(). * - * @param bool $val + * @param boolean $val * * @return URI */ @@ -324,7 +324,7 @@ public function showPassword(bool $val = true) * The value returned MUST be normalized to lowercase, per RFC 3986 * Section 3.2.2. * - * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 * @return string The URI host. */ public function getHost() @@ -347,7 +347,7 @@ public function getHost() * If no port is present, but a scheme is present, this method MAY return * the standard port for that scheme, but SHOULD return null. * - * @return null|int The URI port. + * @return null|integer The URI port. */ public function getPort() { @@ -377,8 +377,8 @@ public function getPort() * delimiter between path segments, that value MUST be passed in encoded * form (e.g., "%2F") to the instance. * - * @see https://tools.ietf.org/html/rfc3986#section-2 - * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 * @return string The URI path. */ public function getPath(): string @@ -463,7 +463,7 @@ public function getSegments(): array /** * Returns the value of a specific segment of the URI path. * - * @param int $number + * @param integer $number * * @return string The value of the segment. If no segment is found, * throws InvalidArgumentError @@ -482,13 +482,12 @@ public function getSegment(int $number): string return $this->segments[$number] ?? ''; } - /** * Set the value of a specific segment of the URI path. * Allows to set only existing segments or add new one. * - * @param int $number - * @param mixed $value (string or int) + * @param integer $number + * @param mixed $value (string or int) * * @return $this */ @@ -514,7 +513,7 @@ public function setSegment(int $number, $value) /** * Returns the total number of segments. * - * @return int + * @return integer */ public function getTotalSegments(): int { @@ -551,12 +550,12 @@ public function __toString() public static function createURIString($scheme = null, $authority = null, $path = null, $query = null, $fragment = null) { $uri = ''; - if ( ! empty($scheme)) + if (! empty($scheme)) { $uri .= $scheme . '://'; } - if ( ! empty($authority)) + if (! empty($authority)) { $uri .= $authority; } @@ -639,7 +638,7 @@ public function setScheme(string $str) */ public function setUserInfo(string $user, string $pass) { - $this->user = trim($user); + $this->user = trim($user); $this->password = trim($pass); return $this; @@ -666,7 +665,7 @@ public function setHost(string $str) /** * Sets the port portion of the URI. * - * @param int $port + * @param integer $port * * @return $this */ @@ -739,12 +738,12 @@ public function setQuery(string $query) } // Can't have leading ? - if ( ! empty($query) && strpos($query, '?') === 0) + if (! empty($query) && strpos($query, '?') === 0) { $query = substr($query, 1); } - $temp = explode('&', $query); + $temp = explode('&', $query); $parts = []; foreach ($temp as $index => $part) @@ -885,7 +884,7 @@ public function keepQuery(...$params) foreach ($this->query as $key => $value) { - if ( ! in_array($key, $params)) + if (! in_array($key, $params)) { continue; } @@ -950,10 +949,9 @@ protected function filterPath(string $path = null) // Encode characters $path = preg_replace_callback( - '/(?:[^' . self::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', function(array $matches) - { - return rawurlencode($matches[0]); - }, $path + '/(?:[^' . self::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', function (array $matches) { + return rawurlencode($matches[0]); + }, $path ); return $path; @@ -968,23 +966,23 @@ protected function filterPath(string $path = null) */ protected function applyParts($parts) { - if ( ! empty($parts['host'])) + if (! empty($parts['host'])) { $this->host = $parts['host']; } - if ( ! empty($parts['user'])) + if (! empty($parts['user'])) { $this->user = $parts['user']; } - if ( ! empty($parts['path'])) + if (! empty($parts['path'])) { $this->path = $this->filterPath($parts['path']); } - if ( ! empty($parts['query'])) + if (! empty($parts['query'])) { $this->setQuery($parts['query']); } - if ( ! empty($parts['fragment'])) + if (! empty($parts['fragment'])) { $this->fragment = $parts['fragment']; } @@ -1002,10 +1000,10 @@ protected function applyParts($parts) // Port if (isset($parts['port'])) { - if ( ! is_null($parts['port'])) + if (! is_null($parts['port'])) { // Valid port numbers are enforced by earlier parse_url or setPort() - $port = $parts['port']; + $port = $parts['port']; $this->port = $port; } } @@ -1016,7 +1014,7 @@ protected function applyParts($parts) } // Populate our segments array - if ( ! empty($parts['path'])) + if (! empty($parts['path'])) { $this->segments = explode('/', trim($parts['path'], '/')); } @@ -1043,7 +1041,7 @@ public function resolveRelativeURI(string $uri) $relative = new URI(); $relative->setURI($uri); - if ($relative->getScheme() == $this->getScheme()) + if ($relative->getScheme() === $this->getScheme()) { $relative->setScheme(''); } @@ -1051,7 +1049,7 @@ public function resolveRelativeURI(string $uri) $transformed = clone $relative; // 5.2.2 Transform References in a non-strict method (no scheme) - if ( ! empty($relative->getAuthority())) + if (! empty($relative->getAuthority())) { $transformed->setAuthority($relative->getAuthority()) ->setPath($relative->getPath()) @@ -1059,7 +1057,7 @@ public function resolveRelativeURI(string $uri) } else { - if ($relative->getPath() == '') + if ($relative->getPath() === '') { $transformed->setPath($this->getPath()); @@ -1111,7 +1109,7 @@ public function resolveRelativeURI(string $uri) */ protected function mergePaths(URI $base, URI $reference) { - if ( ! empty($base->getAuthority()) && empty($base->getPath())) + if (! empty($base->getAuthority()) && empty($base->getPath())) { return '/' . ltrim($reference->getPath(), '/ '); } @@ -1136,17 +1134,16 @@ protected function mergePaths(URI $base, URI $reference) * remove single and double dot segments from the path per * RFC 3986 Section 5.2.4 * - * @see http://tools.ietf.org/html/rfc3986#section-5.2.4 + * @see http://tools.ietf.org/html/rfc3986#section-5.2.4 * * @param string $path * - * @return string + * @return string * @internal param \CodeIgniter\HTTP\URI $uri - * */ public function removeDotSegments(string $path): string { - if (empty($path) || $path == '/') + if (empty($path) || $path === '/') { return $path; } @@ -1167,11 +1164,11 @@ public function removeDotSegments(string $path): string // for almost every real use case. foreach ($input as $segment) { - if ($segment == '..') + if ($segment === '..') { array_pop($output); } - else if ($segment != '.' && $segment != '') + else if ($segment !== '.' && $segment !== '') { array_push($output, $segment); } @@ -1180,7 +1177,7 @@ public function removeDotSegments(string $path): string $output = implode('/', $output); $output = ltrim($output, '/ '); - if ($output != '/') + if ($output !== '/') { // Add leading slash if necessary if (strpos($path, '/') === 0) @@ -1189,7 +1186,7 @@ public function removeDotSegments(string $path): string } // Add trailing slash if necessary - if (substr($path, -1, 1) == '/') + if (substr($path, -1, 1) === '/') { $output .= '/'; } diff --git a/system/HTTP/UserAgent.php b/system/HTTP/UserAgent.php index 91ab2609e9b9..1b8ecdb14100 100644 --- a/system/HTTP/UserAgent.php +++ b/system/HTTP/UserAgent.php @@ -14,21 +14,21 @@ class UserAgent /** * Flag for if the user-agent belongs to a browser * - * @var bool + * @var boolean */ protected $isBrowser = false; /** * Flag for if the user-agent is a robot * - * @var bool + * @var boolean */ protected $isRobot = false; /** * Flag for if the user-agent is a mobile browser * - * @var bool + * @var boolean */ protected $isMobile = false; @@ -77,7 +77,7 @@ class UserAgent /** * HTTP Referer * - * @var mixed + * @var mixed */ protected $referrer; @@ -109,9 +109,9 @@ public function __construct($config = null) /** * Is Browser * - * @param string $key + * @param string $key * - * @return bool + * @return boolean */ public function isBrowser($key = null) { @@ -135,9 +135,9 @@ public function isBrowser($key = null) /** * Is Robot * - * @param string $key + * @param string $key * - * @return bool + * @return boolean */ public function isRobot($key = null) { @@ -161,9 +161,9 @@ public function isRobot($key = null) /** * Is Mobile * - * @param string $key + * @param string $key * - * @return bool + * @return boolean */ public function isMobile($key = null) { @@ -187,7 +187,7 @@ public function isMobile($key = null) /** * Is this a referral from another site? * - * @return bool + * @return boolean */ public function isReferral() { @@ -214,7 +214,7 @@ public function isReferral() /** * Agent String * - * @return string + * @return string */ public function getAgentString() { @@ -226,7 +226,7 @@ public function getAgentString() /** * Get Platform * - * @return string + * @return string */ public function getPlatform() { @@ -238,7 +238,7 @@ public function getPlatform() /** * Get Browser Name * - * @return string + * @return string */ public function getBrowser() { @@ -250,7 +250,7 @@ public function getBrowser() /** * Get the Browser Version * - * @return string + * @return string */ public function getVersion() { @@ -262,7 +262,7 @@ public function getVersion() /** * Get The Robot Name * - * @return string + * @return string */ public function getRobot() { @@ -273,7 +273,7 @@ public function getRobot() /** * Get the Mobile Device * - * @return string + * @return string */ public function getMobile() { @@ -285,7 +285,7 @@ public function getMobile() /** * Get the referrer * - * @return bool + * @return boolean */ public function getReferrer() { @@ -297,9 +297,9 @@ public function getReferrer() /** * Parse a custom user-agent string * - * @param string $string + * @param string $string * - * @return void + * @return void */ public function parse($string) { @@ -325,7 +325,7 @@ public function parse($string) /** * Compile the User Agent Data * - * @return bool + * @return boolean */ protected function compileData() { @@ -345,7 +345,7 @@ protected function compileData() /** * Set the Platform * - * @return bool + * @return boolean */ protected function setPlatform() { @@ -353,7 +353,7 @@ protected function setPlatform() { foreach ($this->config->platforms as $key => $val) { - if (preg_match('|'.preg_quote($key).'|i', $this->agent)) + if (preg_match('|' . preg_quote($key) . '|i', $this->agent)) { $this->platform = $val; @@ -372,7 +372,7 @@ protected function setPlatform() /** * Set the Browser * - * @return bool + * @return boolean */ protected function setBrowser() { @@ -380,7 +380,7 @@ protected function setBrowser() { foreach ($this->config->browsers as $key => $val) { - if (preg_match('|'.$key.'.*?([0-9\.]+)|i', $this->agent, $match)) + if (preg_match('|' . $key . '.*?([0-9\.]+)|i', $this->agent, $match)) { $this->isBrowser = true; $this->version = $match[1]; @@ -400,7 +400,7 @@ protected function setBrowser() /** * Set the Robot * - * @return bool + * @return boolean */ protected function setRobot() { @@ -408,7 +408,7 @@ protected function setRobot() { foreach ($this->config->robots as $key => $val) { - if (preg_match('|'.preg_quote($key).'|i', $this->agent)) + if (preg_match('|' . preg_quote($key) . '|i', $this->agent)) { $this->isRobot = true; $this->robot = $val; @@ -427,7 +427,7 @@ protected function setRobot() /** * Set the Mobile Device * - * @return bool + * @return boolean */ protected function setMobile() { diff --git a/system/Helpers/cookie_helper.php b/system/Helpers/cookie_helper.php index 730339712349..907a29c376ce 100755 --- a/system/Helpers/cookie_helper.php +++ b/system/Helpers/cookie_helper.php @@ -34,39 +34,39 @@ * @since Version 3.0.0 * @filesource */ + // -------------------------------------------------------------------- /** * CodeIgniter Cookie Helpers * - * @package CodeIgniter - * @subpackage Helpers - * @category Helpers - * @author CodeIgniter Dev Team - * @link https://codeigniter.com/user_guide/helpers/cookie_helper.html + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author CodeIgniter Dev Team + * @link https://codeigniter.com/user_guide/helpers/cookie_helper.html */ -if ( ! function_exists('set_cookie')) +if (! function_exists('set_cookie')) { - /** * Set cookie * * Accepts seven parameters, or you can submit an associative * array in the first parameter containing all the values. * - * @param string|array $name Cookie name or array containing binds - * @param string $value The value of the cookie - * @param string $expire The number of seconds until expiration - * @param string $domain For site-wide cookie. + * @param string|array $name Cookie name or array containing binds + * @param string $value The value of the cookie + * @param string $expire The number of seconds until expiration + * @param string $domain For site-wide cookie. * Usually: .yourdomain.com - * @param string $path The cookie path - * @param string $prefix The cookie prefix - * @param bool $secure True makes the cookie secure - * @param bool $httpOnly True makes the cookie accessible via + * @param string $path The cookie path + * @param string $prefix The cookie prefix + * @param boolean $secure True makes the cookie secure + * @param boolean $httpOnly True makes the cookie accessible via * http(s) only (no javascript) * - * @see (\Config\Services::response())->setCookie() - * @see \CodeIgniter\HTTP\Response::setCookie() + * @see (\Config\Services::response())->setCookie() + * @see \CodeIgniter\HTTP\Response::setCookie() */ function set_cookie($name, string $value = '', string $expire = '', string $domain = '', string $path = '/', string $prefix = '', bool $secure = false, bool $httpOnly = false) { @@ -75,58 +75,53 @@ function set_cookie($name, string $value = '', string $expire = '', string $doma $response = \Config\Services::response(); $response->setcookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httpOnly); } - } //-------------------------------------------------------------------- -if ( ! function_exists('get_cookie')) +if (! function_exists('get_cookie')) { - /** * Fetch an item from the COOKIE array * - * @param string $index - * @param bool $xssClean + * @param string $index + * @param boolean $xssClean * - * @see (\Config\Services::request())->getCookie() - * @see \CodeIgniter\HTTP\IncomingRequest::getCookie() - * @return mixed + * @see (\Config\Services::request())->getCookie() + * @see \CodeIgniter\HTTP\IncomingRequest::getCookie() + * @return mixed */ function get_cookie($index, bool $xssClean = false) { - $app = config(\Config\App::class); + $app = config(\Config\App::class); $appCookiePrefix = $app->cookiePrefix; - $prefix = isset($_COOKIE[$index]) ? '' : $appCookiePrefix; + $prefix = isset($_COOKIE[$index]) ? '' : $appCookiePrefix; $request = \Config\Services::request(); - $filter = true === $xssClean ? FILTER_SANITIZE_STRING : null; - $cookie = $request->getCookie($prefix . $index, $filter); + $filter = true === $xssClean ? FILTER_SANITIZE_STRING : null; + $cookie = $request->getCookie($prefix . $index, $filter); return $cookie; } - } //-------------------------------------------------------------------- -if ( ! function_exists('delete_cookie')) +if (! function_exists('delete_cookie')) { - /** * Delete a COOKIE * - * @param mixed $name - * @param string $domain the cookie domain. Usually: .yourdomain.com - * @param string $path the cookie path - * @param string $prefix the cookie prefix - * @see (\Config\Services::response())->setCookie() - * @see \CodeIgniter\HTTP\Response::setcookie() - * @return void + * @param mixed $name + * @param string $domain the cookie domain. Usually: .yourdomain.com + * @param string $path the cookie path + * @param string $prefix the cookie prefix + * @see (\Config\Services::response())->setCookie() + * @see \CodeIgniter\HTTP\Response::setcookie() + * @return void */ function delete_cookie($name, string $domain = '', string $path = '/', string $prefix = '') { \Config\Services::response()->deleteCookie($name, $domain, $path, $prefix); } - } diff --git a/system/Helpers/date_helper.php b/system/Helpers/date_helper.php index 9bbf51dcbfb2..125654c52c20 100644 --- a/system/Helpers/date_helper.php +++ b/system/Helpers/date_helper.php @@ -34,18 +34,18 @@ * @since Version 3.0.0 * @filesource */ -if ( ! function_exists('now')) -{ +if (! function_exists('now')) +{ /** * Get "now" time * * Returns time() based on the timezone parameter or on the * app_timezone() setting * - * @param string $timezone + * @param string $timezone * - * @return int + * @return integer */ function now(string $timezone = null) { @@ -61,5 +61,4 @@ function now(string $timezone = null) return mktime($hour, $minute, $second, $month, $day, $year); } - } diff --git a/system/Helpers/filesystem_helper.php b/system/Helpers/filesystem_helper.php index f947305a10f2..c4389b4eb129 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -27,29 +27,29 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright 2008-2014 EllisLab, Inc. (https://ellislab.com/) - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright 2008-2014 EllisLab, Inc. (https://ellislab.com/) + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ + /** * CodeIgniter Directory Helpers * - * @package CodeIgniter - * @subpackage Helpers - * @category Helpers - * @author EllisLab Dev Team - * @link https://codeigniter.com/user_guide/helpers/directory_helper.html + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/directory_helper.html */ // ------------------------------------------------------------------------ -if ( ! function_exists('directory_map')) +if (! function_exists('directory_map')) { - /** * Create a Directory Map * @@ -57,12 +57,12 @@ * representation of it. Sub-folders contained with the * directory will be mapped as well. * - * @param string $source_dir Path to source - * @param int $directory_depth Depth of directories to traverse - * (0 = fully recursive, 1 = current dir, etc) - * @param bool $hidden Whether to show hidden files + * @param string $source_dir Path to source + * @param integer $directory_depth Depth of directories to traverse + * (0 = fully recursive, 1 = current dir, etc) + * @param boolean $hidden Whether to show hidden files * - * @return array + * @return array */ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidden = false): array { @@ -70,8 +70,8 @@ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidde { $fp = opendir($source_dir); - $filedata = []; - $new_depth = $directory_depth - 1; + $filedata = []; + $new_depth = $directory_depth - 1; $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; while (false !== ($file = readdir($fp))) @@ -102,25 +102,23 @@ function directory_map(string $source_dir, int $directory_depth = 0, bool $hidde return []; } } - } // ------------------------------------------------------------------------ -if ( ! function_exists('write_file')) +if (! function_exists('write_file')) { - /** * Write File * * Writes data to the file specified in the path. * Creates a new file if non-existent. * - * @param string $path File path - * @param string $data Data to write - * @param string $mode fopen() mode (default: 'wb') + * @param string $path File path + * @param string $data Data to write + * @param string $mode fopen() mode (default: 'wb') * - * @return bool + * @return boolean */ function write_file(string $path, string $data, string $mode = 'wb'): bool { @@ -148,14 +146,12 @@ function write_file(string $path, string $data, string $mode = 'wb'): bool return false; } } - } // ------------------------------------------------------------------------ -if ( ! function_exists('delete_files')) +if (! function_exists('delete_files')) { - /** * Delete Files * @@ -164,12 +160,12 @@ function write_file(string $path, string $data, string $mode = 'wb'): bool * 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) + * @param string $path File path + * @param boolean $delDir Whether to delete any directories found in the path + * @param boolean $htdocs Whether to skip deleting .htaccess and index page files + * @param integer $_level Current directory depth level (default: 0; internal use only) * - * @return bool + * @return boolean */ function delete_files(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool { @@ -204,25 +200,23 @@ function delete_files(string $path, bool $delDir = false, bool $htdocs = false, return false; } } - } // ------------------------------------------------------------------------ -if ( ! function_exists('get_filenames')) +if (! function_exists('get_filenames')) { - /** * Get Filenames * * Reads the specified directory and builds an array containing the filenames. * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param bool $include_path Whether to include the path as part of the filename - * @param bool $recursion Internal variable to determine recursion status - do not use in calls + * @param string $source_dir Path to source + * @param boolean $include_path Whether to include the path as part of the filename + * @param boolean $recursion Internal variable to determine recursion status - do not use in calls * - * @return array + * @return array */ function get_filenames(string $source_dir, bool $include_path = false, bool $recursion = false): array { @@ -234,7 +228,7 @@ function get_filenames(string $source_dir, bool $include_path = false, bool $rec // reset the array and make sure $source_dir has a trailing slash on the initial call if ($recursion === false) { - $filedata = []; + $filedata = []; $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } @@ -258,14 +252,12 @@ function get_filenames(string $source_dir, bool $include_path = false, bool $rec return []; } } - } // -------------------------------------------------------------------- -if ( ! function_exists('get_dir_file_info')) +if (! function_exists('get_dir_file_info')) { - /** * Get Directory File Information * @@ -274,40 +266,40 @@ function get_filenames(string $source_dir, bool $include_path = false, bool $rec * * Any sub-folders contained within the specified path are read as well. * - * @param string $source_dir Path to source - * @param bool $top_level_only Look only at the top level directory specified? - * @param bool $recursion Internal variable to determine recursion status - do not use in calls + * @param string $source_dir Path to source + * @param boolean $top_level_only Look only at the top level directory specified? + * @param boolean $recursion Internal variable to determine recursion status - do not use in calls * - * @return array + * @return array */ function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool $recursion = false): array { static $filedata = []; - $relative_path = $source_dir; + $relative_path = $source_dir; try { $fp = @opendir($source_dir); { // reset the array and make sure $source_dir has a trailing slash on the initial call - if ($recursion === false) + if ($recursion === false) { - $filedata = []; - $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - } + $filedata = []; + $source_dir = rtrim(realpath($source_dir), 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))) + while (false !== ($file = readdir($fp))) { - if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false) - { - get_dir_file_info($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true); - } - elseif ($file[0] !== '.') - { - $filedata[$file] = get_file_info($source_dir . $file); - $filedata[$file]['relative_path'] = $relative_path; - } + if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false) + { + get_dir_file_info($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true); + } + elseif ($file[0] !== '.') + { + $filedata[$file] = get_file_info($source_dir . $file); + $filedata[$file]['relative_path'] = $relative_path; } + } closedir($fp); return $filedata; @@ -318,14 +310,12 @@ function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool return []; } } - } // -------------------------------------------------------------------- -if ( ! function_exists('get_file_info')) +if (! function_exists('get_file_info')) { - /** * Get File Info * @@ -334,14 +324,14 @@ function get_dir_file_info(string $source_dir, bool $top_level_only = true, bool * 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 $returned_values Array or comma separated string of information returned + * @param string $file Path to file + * @param mixed $returned_values Array or comma separated string of information returned * - * @return array|null + * @return array|null */ function get_file_info(string $file, $returned_values = ['name', 'server_path', 'size', 'date']) { - if ( ! file_exists($file)) + if (! file_exists($file)) { return null; } @@ -383,22 +373,20 @@ function get_file_info(string $file, $returned_values = ['name', 'server_path', return $fileinfo; } - } // -------------------------------------------------------------------- -if ( ! function_exists('symbolic_permissions')) +if (! function_exists('symbolic_permissions')) { - /** * Symbolic Permissions * * Takes a numeric value representing a file's permissions and returns * standard symbolic notation representing that value * - * @param int $perms Permissions - * @return string + * @param integer $perms Permissions + * @return string */ function symbolic_permissions(int $perms): string { @@ -452,42 +440,38 @@ function symbolic_permissions(int $perms): string return $symbolic; } - } // -------------------------------------------------------------------- -if ( ! function_exists('octal_permissions')) +if (! function_exists('octal_permissions')) { - /** * Octal Permissions * * Takes a numeric value representing a file's permissions and returns * a three character string representing the file's octal permissions * - * @param int $perms Permissions - * @return string + * @param integer $perms Permissions + * @return string */ function octal_permissions(int $perms): string { return substr(sprintf('%o', $perms), -3); } - } // ------------------------------------------------------------------------ -if ( ! function_exists('set_realpath')) +if (! function_exists('set_realpath')) { - /** * Set Realpath * - * @param string $path - * @param bool $checkExistance Checks to see if the path exists + * @param string $path + * @param boolean $checkExistance Checks to see if the path exists * - * @return string + * @return string */ function set_realpath(string $path, bool $checkExistance = false): string { @@ -510,5 +494,4 @@ function set_realpath(string $path, bool $checkExistance = false): string // Add a trailing slash, if this is a directory return is_dir($path) ? rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $path; } - } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 3998c04ff836..da7edabd0099 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -27,36 +27,36 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use Config\Services; //-------------------------------------------------------------------- -if ( ! function_exists('form_open')) +if (! function_exists('form_open')) { - /** * Form Declaration * * Creates the opening portion of the form. * - * @param string $action the URI segments of the form destination - * @param array|string $attributes a key/value pair of attributes, or string representation - * @param array $hidden a key/value pair hidden data + * @param string $action the URI segments of the form destination + * @param array|string $attributes a key/value pair of attributes, or string representation + * @param array $hidden a key/value pair hidden data * - * @return string + * @return string */ function form_open(string $action = '', $attributes = [], array $hidden = []): string { // If no action is provided then set to the current url - if ( ! $action) + if (! $action) { $action = current_url(true); } // If an action is not a full URL then turn it into one @@ -73,7 +73,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s } if (stripos($attributes, 'accept-charset=') === false) { - $config = config(\Config\App::class); + $config = config(\Config\App::class); $attributes .= ' accept-charset="' . strtolower($config->charset) . '"'; } @@ -92,30 +92,28 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s { foreach ($hidden as $name => $value) { - $form .= '' . "\n"; + $form .= '' . "\n"; } } return $form; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_open_multipart')) +if (! function_exists('form_open_multipart')) { - /** * Form Declaration - Multipart type * * Creates the opening portion of the form, but with "multipart/form-data". * - * @param string $action The URI segments of the form destination - * @param array|string $attributes A key/value pair of attributes, or the same as a string - * @param array $hidden A key/value pair hidden data + * @param string $action The URI segments of the form destination + * @param array|string $attributes A key/value pair of attributes, or the same as a string + * @param array $hidden A key/value pair hidden data * - * @return string + * @return string */ function form_open_multipart(string $action = '', $attributes = [], array $hidden = []): string { @@ -130,25 +128,23 @@ function form_open_multipart(string $action = '', $attributes = [], array $hidde return form_open($action, $attributes, $hidden); } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_hidden')) +if (! function_exists('form_hidden')) { - /** * Hidden Input Field * * Generates hidden fields. You can pass a simple key/value string or * an associative array with multiple values. * - * @param string|array $name Field name or associative array to create multiple fields - * @param string|array $value Field value - * @param bool $recursing + * @param string|array $name Field name or associative array to create multiple fields + * @param string|array $value Field value + * @param boolean $recursing * - * @return string + * @return string */ function form_hidden($name, $value = '', bool $recursing = false): string { @@ -169,9 +165,9 @@ function form_hidden($name, $value = '', bool $recursing = false): string return $form; } - if ( ! is_array($value)) + if (! is_array($value)) { - $form .= '\n"; + $form .= '\n"; } else { @@ -184,104 +180,99 @@ function form_hidden($name, $value = '', bool $recursing = false): string return $form; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_input')) +if (! function_exists('form_input')) { - /** * Text Input Field. If 'type' is passed in the $type field, it will be * used as the input type, for making 'email', 'phone', etc input fields. * - * @param mixed $data - * @param string $value - * @param mixed $extra - * @param string $type + * @param mixed $data + * @param string $value + * @param mixed $extra + * @param string $type * - * @return string + * @return string */ function form_input($data = '', string $value = '', $extra = '', string $type = 'text'): string { $defaults = [ - 'type' => $type, - 'name' => is_array($data) ? '' : $data, + 'type' => $type, + 'name' => is_array($data) ? '' : $data, 'value' => $value, ]; return '\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_password')) +if (! function_exists('form_password')) { - /** * Password Field * * Identical to the input function but adds the "password" type * - * @param mixed $data - * @param string $value - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param mixed $extra * - * @return string + * @return string */ function form_password($data = '', string $value = '', $extra = ''): string { is_array($data) || $data = ['name' => $data]; - $data['type'] = 'password'; + $data['type'] = 'password'; return form_input($data, $value, $extra); } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_upload')) +if (! function_exists('form_upload')) { - /** * Upload Field * * Identical to the input function but adds the "file" type * - * @param mixed - * @param string - * @param mixed + * @param mixed + * @param string + * @param mixed * - * @return string + * @return string */ function form_upload($data = '', string $value = '', $extra = ''): string { - $defaults = ['type' => 'file', 'name' => '']; + $defaults = [ + 'type' => 'file', + 'name' => '', + ]; is_array($data) || $data = ['name' => $data]; - $data['type'] = 'file'; + $data['type'] = 'file'; return '\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_textarea')) +if (! function_exists('form_textarea')) { - /** * Textarea field * - * @param mixed $data - * @param string $value - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param mixed $extra * - * @return string + * @return string */ function form_textarea($data = '', string $value = '', $extra = ''): string { @@ -290,7 +281,7 @@ function form_textarea($data = '', string $value = '', $extra = ''): string 'cols' => '40', 'rows' => '10', ]; - if ( ! is_array($data) || ! isset($data['value'])) + if (! is_array($data) || ! isset($data['value'])) { $val = $value; } @@ -304,23 +295,21 @@ function form_textarea($data = '', string $value = '', $extra = ''): string . htmlspecialchars($val) . "\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_multiselect')) +if (! function_exists('form_multiselect')) { - /** * Multi-select menu * - * @param string - * @param array - * @param mixed - * @param mixed + * @param string + * @param array + * @param mixed + * @param mixed * - * @return string + * @return string */ function form_multiselect(string $name = '', array $options = [], array $selected = [], $extra = ''): string { @@ -333,23 +322,21 @@ function form_multiselect(string $name = '', array $options = [], array $selecte return form_dropdown($name, $options, $selected, $extra); } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_dropdown')) +if (! function_exists('form_dropdown')) { - /** * Drop-down Menu * - * @param mixed $data - * @param mixed $options - * @param mixed $selected - * @param mixed $extra + * @param mixed $data + * @param mixed $options + * @param mixed $selected + * @param mixed $extra * - * @return string + * @return string */ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): string { @@ -373,7 +360,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): } is_array($selected) || $selected = [$selected]; - is_array($options) || $options = [$options]; + is_array($options) || $options = [$options]; // If no selected state was submitted we will attempt to set it automatically if (empty($selected)) @@ -391,9 +378,9 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): } } - $extra = stringify_attributes($extra); + $extra = stringify_attributes($extra); $multiple = (count($selected) > 1 && stripos($extra, 'multiple') === false) ? ' multiple="multiple"' : ''; - $form = '\n"; foreach ($options as $key => $val) { $key = (string) $key; @@ -406,7 +393,7 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): $form .= '\n"; foreach ($val as $optgroup_key => $optgroup_val) { - $sel = in_array($optgroup_key, $selected) ? ' selected="selected"' : ''; + $sel = in_array($optgroup_key, $selected) ? ' selected="selected"' : ''; $form .= '\n"; } @@ -422,32 +409,34 @@ function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): return $form . "\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_checkbox')) +if (! function_exists('form_checkbox')) { - /** * Checkbox Field * - * @param mixed $data - * @param string $value - * @param bool $checked - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param boolean $checked + * @param mixed $extra * - * @return string + * @return string */ function form_checkbox($data = '', string $value = '', bool $checked = false, $extra = ''): string { - $defaults = ['type' => 'checkbox', 'name' => ( ! is_array($data) ? $data : ''), 'value' => $value]; + $defaults = [ + 'type' => 'checkbox', + 'name' => ( ! is_array($data) ? $data : ''), + 'value' => $value, + ]; if (is_array($data) && array_key_exists('checked', $data)) { $checked = $data['checked']; - if ($checked == false) + if ($checked === false) { unset($data['checked']); } @@ -457,7 +446,7 @@ function form_checkbox($data = '', string $value = '', bool $checked = false, $e } } - if ($checked == true) + if ($checked === true) { $defaults['checked'] = 'checked'; } @@ -468,101 +457,93 @@ function form_checkbox($data = '', string $value = '', bool $checked = false, $e return '\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_radio')) +if (! function_exists('form_radio')) { - /** * Radio Button * - * @param mixed $data - * @param string $value - * @param bool $checked - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param boolean $checked + * @param mixed $extra * - * @return string + * @return string */ function form_radio($data = '', string $value = '', bool $checked = false, $extra = ''): string { is_array($data) || $data = ['name' => $data]; - $data['type'] = 'radio'; + $data['type'] = 'radio'; return form_checkbox($data, $value, $checked, $extra); } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_submit')) +if (! function_exists('form_submit')) { - /** * Submit Button * - * @param mixed $data - * @param string $value - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param mixed $extra * - * @return string + * @return string */ function form_submit($data = '', string $value = '', $extra = ''): string { $defaults = [ - 'type' => 'submit', - 'name' => is_array($data) ? '' : $data, + 'type' => 'submit', + 'name' => is_array($data) ? '' : $data, 'value' => $value, ]; return '\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_reset')) +if (! function_exists('form_reset')) { - /** * Reset Button * - * @param mixed $data - * @param string $value - * @param mixed $extra + * @param mixed $data + * @param string $value + * @param mixed $extra * - * @return string + * @return string */ function form_reset($data = '', string $value = '', $extra = ''): string { $defaults = [ - 'type' => 'reset', - 'name' => is_array($data) ? '' : $data, + 'type' => 'reset', + 'name' => is_array($data) ? '' : $data, 'value' => $value, ]; return '\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_button')) +if (! function_exists('form_button')) { - /** * Form Button * - * @param mixed $data - * @param string $content - * @param mixed $extra + * @param mixed $data + * @param string $content + * @param mixed $extra * - * @return string + * @return string */ function form_button($data = '', string $content = '', $extra = ''): string { @@ -581,22 +562,20 @@ function form_button($data = '', string $content = '', $extra = ''): string . $content . "\n"; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_label')) +if (! function_exists('form_label')) { - /** * Form Label Tag * - * @param string $label_text The text to appear onscreen - * @param string $id The id the label applies to - * @param array $attributes Additional attributes + * @param string $label_text The text to appear onscreen + * @param string $id The id the label applies to + * @param array $attributes Additional attributes * - * @return string + * @return string */ function form_label(string $label_text = '', string $id = '', array $attributes = []): string { @@ -617,14 +596,12 @@ function form_label(string $label_text = '', string $id = '', array $attributes return $label . '>' . $label_text . ''; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_datalist')) +if (! function_exists('form_datalist')) { - /** * Datalist * @@ -641,13 +618,13 @@ function form_label(string $label_text = '', string $id = '', array $attributes function form_datalist($name, $value, $options) { $data = [ - 'type' => 'text', - 'name' => $name, - 'list' => $name . '_list', + 'type' => 'text', + 'name' => $name, + 'list' => $name . '_list', 'value' => $value, ]; - $out = form_input($data) . "\n"; + $out = form_input($data) . "\n"; $out .= ""; foreach ($options as $option) @@ -655,28 +632,26 @@ function form_datalist($name, $value, $options) $out .= "" . "\n"; + $out .= '' . "\n"; return $out; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_fieldset')) +if (! function_exists('form_fieldset')) { - /** * Fieldset Tag * * Used to produce
text. To close fieldset * use form_fieldset_close() * - * @param string $legend_text The legend text - * @param array $attributes Additional attributes + * @param string $legend_text The legend text + * @param array $attributes Additional attributes * - * @return string + * @return string */ function form_fieldset(string $legend_text = '', array $attributes = []): string { @@ -689,63 +664,57 @@ function form_fieldset(string $legend_text = '', array $attributes = []): string return $fieldset; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_fieldset_close')) +if (! function_exists('form_fieldset_close')) { - /** * Fieldset Close Tag * - * @param string $extra + * @param string $extra * - * @return string + * @return string */ function form_fieldset_close(string $extra = ''): string { return '
' . $extra; } - } //-------------------------------------------------------------------- -if ( ! function_exists('form_close')) +if (! function_exists('form_close')) { - /** * Form Close Tag * - * @param string $extra + * @param string $extra * - * @return string + * @return string */ function form_close(string $extra = ''): string { return '' . $extra; } - } //-------------------------------------------------------------------- -if ( ! function_exists('set_value')) +if (! function_exists('set_value')) { - /** * Form Value * * Grabs a value from the POST array for the specified field so you can * re-populate an input field or textarea * - * @param string $field Field name - * @param string $default Default value - * @param bool $html_escape Whether to escape HTML special characters or not + * @param string $field Field name + * @param string $default Default value + * @param boolean $html_escape Whether to escape HTML special characters or not * - * @return string + * @return string */ function set_value(string $field, string $default = '', bool $html_escape = true): string { @@ -761,25 +730,23 @@ function set_value(string $field, string $default = '', bool $html_escape = true return ($html_escape) ? esc($value, 'html') : $value; } - } //-------------------------------------------------------------------- -if ( ! function_exists('set_select')) +if (! function_exists('set_select')) { - /** * Set Select * * Let's you set the selected value of a