diff --git a/.editorconfig b/.editorconfig index 23a7072c587b..6de2d73170b0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,9 +4,11 @@ root = true ; Unix-style newlines [*] end_of_line = lf +insert_final_newline = true [*.php] -indent_style = tab +indent_style = space +indent_size = 4 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true diff --git a/application/Config/App.php b/application/Config/App.php index 94a2bab44abf..1078e2ae4bec 100644 --- a/application/Config/App.php +++ b/application/Config/App.php @@ -5,301 +5,301 @@ class App extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Base Site URL - |-------------------------------------------------------------------------- - | - | URL to your CodeIgniter root. Typically this will be your base URL, - | WITH a trailing slash: - | - | http://example.com/ - | - | If this is not set then CodeIgniter will try guess the protocol, domain - | and path to your installation. However, you should always configure this - | explicitly and never rely on auto-guessing, especially in production - | environments. - | - */ - public $baseURL = ''; + /* + |-------------------------------------------------------------------------- + | Base Site URL + |-------------------------------------------------------------------------- + | + | URL to your CodeIgniter root. Typically this will be your base URL, + | WITH a trailing slash: + | + | http://example.com/ + | + | If this is not set then CodeIgniter will try guess the protocol, domain + | and path to your installation. However, you should always configure this + | explicitly and never rely on auto-guessing, especially in production + | environments. + | + */ + public $baseURL = ''; - /* - |-------------------------------------------------------------------------- - | Index File - |-------------------------------------------------------------------------- - | - | Typically this will be your index.php file, unless you've renamed it to - | something else. If you are using mod_rewrite to remove the page set this - | variable so that it is blank. - | - */ - public $indexPage = 'index.php'; + /* + |-------------------------------------------------------------------------- + | Index File + |-------------------------------------------------------------------------- + | + | Typically this will be your index.php file, unless you've renamed it to + | something else. If you are using mod_rewrite to remove the page set this + | variable so that it is blank. + | + */ + public $indexPage = 'index.php'; - /* - |-------------------------------------------------------------------------- - | URI PROTOCOL - |-------------------------------------------------------------------------- - | - | This item determines which getServer global should be used to retrieve the - | URI string. The default setting of 'REQUEST_URI' works for most servers. - | If your links do not seem to work, try one of the other delicious flavors: - | - | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] - | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] - | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] - | - | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! - */ - public $uriProtocol = 'REQUEST_URI'; + /* + |-------------------------------------------------------------------------- + | URI PROTOCOL + |-------------------------------------------------------------------------- + | + | This item determines which getServer global should be used to retrieve the + | URI string. The default setting of 'REQUEST_URI' works for most servers. + | If your links do not seem to work, try one of the other delicious flavors: + | + | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] + | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] + | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] + | + | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! + */ + public $uriProtocol = 'REQUEST_URI'; - /* - |-------------------------------------------------------------------------- - | Default Locale - |-------------------------------------------------------------------------- - | - | The Locale roughly represents the language and location that your visitor - | is viewing the site from. It affects the language strings and other - | strings (like currency markers, numbers, etc), that your program - | should run under for this request. - | - */ - public $defaultLocale = 'en'; + /* + |-------------------------------------------------------------------------- + | Default Locale + |-------------------------------------------------------------------------- + | + | The Locale roughly represents the language and location that your visitor + | is viewing the site from. It affects the language strings and other + | strings (like currency markers, numbers, etc), that your program + | should run under for this request. + | + */ + public $defaultLocale = 'en'; - /* - |-------------------------------------------------------------------------- - | Negotiate Locale - |-------------------------------------------------------------------------- - | - | If true, the current Request object will automatically determine the - | language to use based on the value of the Accept-Language header. - | - | If false, no automatic detection will be performed. - | - */ - public $negotiateLocale = false; + /* + |-------------------------------------------------------------------------- + | Negotiate Locale + |-------------------------------------------------------------------------- + | + | If true, the current Request object will automatically determine the + | language to use based on the value of the Accept-Language header. + | + | If false, no automatic detection will be performed. + | + */ + public $negotiateLocale = false; - /* - |-------------------------------------------------------------------------- - | Supported Locales - |-------------------------------------------------------------------------- - | - | If $negotiateLocale is true, this array lists the locales supported - | by the application in descending order of priority. If no match is - | found, the first locale will be used. - | - */ - public $supportedLocales = ['en']; + /* + |-------------------------------------------------------------------------- + | Supported Locales + |-------------------------------------------------------------------------- + | + | If $negotiateLocale is true, this array lists the locales supported + | by the application in descending order of priority. If no match is + | found, the first locale will be used. + | + */ + public $supportedLocales = ['en']; - /* - |-------------------------------------------------------------------------- - | Application Timezone - |-------------------------------------------------------------------------- - | - | The default timezone that will be used in your application to display - | dates with the date helper, and can be retrieved through app_timezone() - | - */ - public $appTimezone = 'America/Chicago'; + /* + |-------------------------------------------------------------------------- + | Application Timezone + |-------------------------------------------------------------------------- + | + | The default timezone that will be used in your application to display + | dates with the date helper, and can be retrieved through app_timezone() + | + */ + public $appTimezone = 'America/Chicago'; - /* - |-------------------------------------------------------------------------- - | Default Character Set - |-------------------------------------------------------------------------- - | - | This determines which character set is used by default in various methods - | that require a character set to be provided. - | - | See http://php.net/htmlspecialchars for a list of supported charsets. - | - */ - public $charset = 'UTF-8'; + /* + |-------------------------------------------------------------------------- + | Default Character Set + |-------------------------------------------------------------------------- + | + | This determines which character set is used by default in various methods + | that require a character set to be provided. + | + | See http://php.net/htmlspecialchars for a list of supported charsets. + | + */ + public $charset = 'UTF-8'; - /* - |-------------------------------------------------------------------------- - | URI PROTOCOL - |-------------------------------------------------------------------------- - | - | If true, this will force every request made to this application to be - | made via a secure connection (HTTPS). If the incoming request is not - | secure, the user will be redirected to a secure version of the page - | and the HTTP Strict Transport Security header will be set. - */ - public $forceGlobalSecureRequests = false; + /* + |-------------------------------------------------------------------------- + | URI PROTOCOL + |-------------------------------------------------------------------------- + | + | If true, this will force every request made to this application to be + | made via a secure connection (HTTPS). If the incoming request is not + | secure, the user will be redirected to a secure version of the page + | and the HTTP Strict Transport Security header will be set. + */ + public $forceGlobalSecureRequests = false; - /* - |-------------------------------------------------------------------------- - | Session Variables - |-------------------------------------------------------------------------- - | - | 'sessionDriver' - | - | The storage driver to use: files, database, redis, memcached - | - CodeIgniter\Session\Handlers\FileHandler - | - CodeIgniter\Session\Handlers\DatabaseHandler - | - CodeIgniter\Session\Handlers\MemcachedHandler - | - CodeIgniter\Session\Handlers\RedisHandler - | - | 'sessionCookieName' - | - | The session cookie name, must contain only [0-9a-z_-] characters - | - | 'sessionExpiration' - | - | The number of SECONDS you want the session to last. - | Setting to 0 (zero) means expire when the browser is closed. - | - | 'sessionSavePath' - | - | The location to save sessions to, driver dependent. - | - | For the 'files' driver, it's a path to a writable directory. - | WARNING: Only absolute paths are supported! - | - | For the 'database' driver, it's a table name. - | Please read up the manual for the format with other session drivers. - | - | IMPORTANT: You are REQUIRED to set a valid save path! - | - | 'sessionMatchIP' - | - | Whether to match the user's IP address when reading the session data. - | - | WARNING: If you're using the database driver, don't forget to update - | your session table's PRIMARY KEY when changing this setting. - | - | 'sessionTimeToUpdate' - | - | How many seconds between CI regenerating the session ID. - | - | 'sessionRegenerateDestroy' - | - | Whether to destroy session data associated with the old session ID - | when auto-regenerating the session ID. When set to FALSE, the data - | will be later deleted by the garbage collector. - | - | Other session cookie settings are shared with the rest of the application, - | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. - | - */ - public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'; - public $sessionCookieName = 'ci_session'; - public $sessionExpiration = 7200; - public $sessionSavePath = null; - public $sessionMatchIP = false; - public $sessionTimeToUpdate = 300; - public $sessionRegenerateDestroy = false; + /* + |-------------------------------------------------------------------------- + | Session Variables + |-------------------------------------------------------------------------- + | + | 'sessionDriver' + | + | The storage driver to use: files, database, redis, memcached + | - CodeIgniter\Session\Handlers\FileHandler + | - CodeIgniter\Session\Handlers\DatabaseHandler + | - CodeIgniter\Session\Handlers\MemcachedHandler + | - CodeIgniter\Session\Handlers\RedisHandler + | + | 'sessionCookieName' + | + | The session cookie name, must contain only [0-9a-z_-] characters + | + | 'sessionExpiration' + | + | The number of SECONDS you want the session to last. + | Setting to 0 (zero) means expire when the browser is closed. + | + | 'sessionSavePath' + | + | The location to save sessions to, driver dependent. + | + | For the 'files' driver, it's a path to a writable directory. + | WARNING: Only absolute paths are supported! + | + | For the 'database' driver, it's a table name. + | Please read up the manual for the format with other session drivers. + | + | IMPORTANT: You are REQUIRED to set a valid save path! + | + | 'sessionMatchIP' + | + | Whether to match the user's IP address when reading the session data. + | + | WARNING: If you're using the database driver, don't forget to update + | your session table's PRIMARY KEY when changing this setting. + | + | 'sessionTimeToUpdate' + | + | How many seconds between CI regenerating the session ID. + | + | 'sessionRegenerateDestroy' + | + | Whether to destroy session data associated with the old session ID + | when auto-regenerating the session ID. When set to FALSE, the data + | will be later deleted by the garbage collector. + | + | Other session cookie settings are shared with the rest of the application, + | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. + | + */ + public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'; + public $sessionCookieName = 'ci_session'; + public $sessionExpiration = 7200; + public $sessionSavePath = null; + public $sessionMatchIP = false; + public $sessionTimeToUpdate = 300; + public $sessionRegenerateDestroy = false; - /* - |-------------------------------------------------------------------------- - | Cookie Related Variables - |-------------------------------------------------------------------------- - | - | 'cookiePrefix' = Set a cookie name prefix if you need to avoid collisions - | 'cookieDomain' = Set to .your-domain.com for site-wide cookies - | 'cookiePath' = Typically will be a forward slash - | 'cookieSecure' = Cookie will only be set if a secure HTTPS connection exists. - | 'cookieHTTPOnly' = Cookie will only be accessible via HTTP(S) (no javascript) - | - | Note: These settings (with the exception of 'cookie_prefix' and - | 'cookie_httponly') will also affect sessions. - | - */ - public $cookiePrefix = ''; - public $cookieDomain = ''; - public $cookiePath = '/'; - public $cookieSecure = false; - public $cookieHTTPOnly = false; + /* + |-------------------------------------------------------------------------- + | Cookie Related Variables + |-------------------------------------------------------------------------- + | + | 'cookiePrefix' = Set a cookie name prefix if you need to avoid collisions + | 'cookieDomain' = Set to .your-domain.com for site-wide cookies + | 'cookiePath' = Typically will be a forward slash + | 'cookieSecure' = Cookie will only be set if a secure HTTPS connection exists. + | 'cookieHTTPOnly' = Cookie will only be accessible via HTTP(S) (no javascript) + | + | Note: These settings (with the exception of 'cookie_prefix' and + | 'cookie_httponly') will also affect sessions. + | + */ + public $cookiePrefix = ''; + public $cookieDomain = ''; + public $cookiePath = '/'; + public $cookieSecure = false; + public $cookieHTTPOnly = false; - /* - |-------------------------------------------------------------------------- - | Reverse Proxy IPs - |-------------------------------------------------------------------------- - | - | If your getServer is behind a reverse proxy, you must whitelist the proxy - | IP addresses from which CodeIgniter should trust headers such as - | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify - | the visitor's IP address. - | - | You can use both an array or a comma-separated list of proxy addresses, - | as well as specifying whole subnets. Here are a few examples: - | - | Comma-separated: '10.0.1.200,192.168.5.0/24' - | Array: array('10.0.1.200', '192.168.5.0/24') - */ - public $proxyIPs = ''; + /* + |-------------------------------------------------------------------------- + | Reverse Proxy IPs + |-------------------------------------------------------------------------- + | + | If your getServer is behind a reverse proxy, you must whitelist the proxy + | IP addresses from which CodeIgniter should trust headers such as + | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify + | the visitor's IP address. + | + | You can use both an array or a comma-separated list of proxy addresses, + | as well as specifying whole subnets. Here are a few examples: + | + | Comma-separated: '10.0.1.200,192.168.5.0/24' + | Array: array('10.0.1.200', '192.168.5.0/24') + */ + public $proxyIPs = ''; - /* - |-------------------------------------------------------------------------- - | Cross Site Request Forgery - |-------------------------------------------------------------------------- - | Enables a CSRF cookie token to be set. When set to TRUE, token will be - | checked on a submitted form. If you are accepting user data, it is strongly - | recommended CSRF protection be enabled. - | - | CSRFTokenName = The token name - | CSRFCookieName = The cookie name - | CSRFExpire = The number in seconds the token should expire. - | CSRFRegenerate = Regenerate token on every submission - */ - public $CSRFTokenName = 'csrf_test_name'; - public $CSRFCookieName = 'csrf_cookie_name'; - public $CSRFExpire = 7200; - public $CSRFRegenerate = true; + /* + |-------------------------------------------------------------------------- + | Cross Site Request Forgery + |-------------------------------------------------------------------------- + | Enables a CSRF cookie token to be set. When set to TRUE, token will be + | checked on a submitted form. If you are accepting user data, it is strongly + | recommended CSRF protection be enabled. + | + | CSRFTokenName = The token name + | CSRFCookieName = The cookie name + | CSRFExpire = The number in seconds the token should expire. + | CSRFRegenerate = Regenerate token on every submission + */ + public $CSRFTokenName = 'csrf_test_name'; + public $CSRFCookieName = 'csrf_cookie_name'; + public $CSRFExpire = 7200; + public $CSRFRegenerate = true; - /* - |-------------------------------------------------------------------------- - | Content Security Policy - |-------------------------------------------------------------------------- - | Enables the Response's Content Secure Policy to restrict the sources that - | can be used for images, scripts, CSS files, audio, video, etc. If enabled, - | the Response object will populate default values for the policy from the - | ContentSecurityPolicy.php file. Controllers can always add to those - | restrictions at run time. - | - | For a better understanding of CSP, see these documents: - | - http://www.html5rocks.com/en/tutorials/security/content-security-policy/ - | - http://www.w3.org/TR/CSP/ - */ - public $CSPEnabled = false; + /* + |-------------------------------------------------------------------------- + | Content Security Policy + |-------------------------------------------------------------------------- + | Enables the Response's Content Secure Policy to restrict the sources that + | can be used for images, scripts, CSS files, audio, video, etc. If enabled, + | the Response object will populate default values for the policy from the + | ContentSecurityPolicy.php file. Controllers can always add to those + | restrictions at run time. + | + | For a better understanding of CSP, see these documents: + | - http://www.html5rocks.com/en/tutorials/security/content-security-policy/ + | - http://www.w3.org/TR/CSP/ + */ + public $CSPEnabled = false; - /* - |-------------------------------------------------------------------------- - | Debug Toolbar - |-------------------------------------------------------------------------- - | The Debug Toolbar provides a way to see information about the performance - | and state of your application during that page display. By default it will - | NOT be displayed under production environments, and will only display if - | CI_DEBUG is true, since if it's not, there's not much to display anyway. - | - | toolbarMaxHistory = Number of history files, 0 for none or -1 for unlimited - | - */ - public $toolbarCollectors = [ - 'CodeIgniter\Debug\Toolbar\Collectors\Timers', - 'CodeIgniter\Debug\Toolbar\Collectors\Database', - 'CodeIgniter\Debug\Toolbar\Collectors\Logs', - 'CodeIgniter\Debug\Toolbar\Collectors\Views', -// 'CodeIgniter\Debug\Toolbar\Collectors\Cache', - 'CodeIgniter\Debug\Toolbar\Collectors\Files', - 'CodeIgniter\Debug\Toolbar\Collectors\Routes', - 'CodeIgniter\Debug\Toolbar\Collectors\Events', - ]; - public $toolbarMaxHistory = 20; + /* + |-------------------------------------------------------------------------- + | Debug Toolbar + |-------------------------------------------------------------------------- + | The Debug Toolbar provides a way to see information about the performance + | and state of your application during that page display. By default it will + | NOT be displayed under production environments, and will only display if + | CI_DEBUG is true, since if it's not, there's not much to display anyway. + | + | toolbarMaxHistory = Number of history files, 0 for none or -1 for unlimited + | + */ + public $toolbarCollectors = [ + 'CodeIgniter\Debug\Toolbar\Collectors\Timers', + 'CodeIgniter\Debug\Toolbar\Collectors\Database', + 'CodeIgniter\Debug\Toolbar\Collectors\Logs', + 'CodeIgniter\Debug\Toolbar\Collectors\Views', +// 'CodeIgniter\Debug\Toolbar\Collectors\Cache', + 'CodeIgniter\Debug\Toolbar\Collectors\Files', + 'CodeIgniter\Debug\Toolbar\Collectors\Routes', + 'CodeIgniter\Debug\Toolbar\Collectors\Events', + ]; + public $toolbarMaxHistory = 20; - /* - |-------------------------------------------------------------------------- - | Application Salt - |-------------------------------------------------------------------------- - | - | The $salt can be used anywhere within the application that you need - | to provide secure data. It should be different for every application - | and can be of any length, though the more random the characters - | the better. - | - */ - public $salt = ''; + /* + |-------------------------------------------------------------------------- + | Application Salt + |-------------------------------------------------------------------------- + | + | The $salt can be used anywhere within the application that you need + | to provide secure data. It should be different for every application + | and can be of any length, though the more random the characters + | the better. + | + */ + public $salt = ''; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Config/Autoload.php b/application/Config/Autoload.php index 0dab676ce660..734c18443cbe 100644 --- a/application/Config/Autoload.php +++ b/application/Config/Autoload.php @@ -11,79 +11,79 @@ */ class Autoload extends \CodeIgniter\Config\AutoloadConfig { - public $psr4 = []; + public $psr4 = []; - public $classmap = []; + public $classmap = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Collects the application-specific autoload settings and merges - * them with the framework's required settings. - * - * NOTE: If you use an identical key in $psr4 or $classmap, then - * the values in this file will overwrite the framework's values. - */ - public function __construct() - { - parent::__construct(); + /** + * Collects the application-specific autoload settings and merges + * them with the framework's required settings. + * + * NOTE: If you use an identical key in $psr4 or $classmap, then + * the values in this file will overwrite the framework's values. + */ + public function __construct() + { + parent::__construct(); - /** - * ------------------------------------------------------------------- - * Namespaces - * ------------------------------------------------------------------- - * This maps the locations of any namespaces in your application - * to their location on the file system. These are used by the - * Autoloader to locate files the first time they have been instantiated. - * - * The '/application' and '/system' directories are already mapped for - * you. You may change the name of the 'App' namespace if you wish, - * but this should be done prior to creating any namespaced classes, - * else you will need to modify all of those classes for this to work. - * - * DO NOT change the name of the CodeIgniter namespace or your application - * WILL break. * - * Prototype: - * - * $Config['psr4'] = [ - * 'CodeIgniter' => SYSPATH - * `]; - */ - $psr4 = [ - 'Config' => APPPATH.'Config', - APP_NAMESPACE => APPPATH, // For custom namespace - 'App' => APPPATH, // To ensure filters, etc still found, - 'Tests\Support' => TESTPATH.'_support', // So custom migrations can run during testing - ]; + /** + * ------------------------------------------------------------------- + * Namespaces + * ------------------------------------------------------------------- + * This maps the locations of any namespaces in your application + * to their location on the file system. These are used by the + * Autoloader to locate files the first time they have been instantiated. + * + * The '/application' and '/system' directories are already mapped for + * you. You may change the name of the 'App' namespace if you wish, + * but this should be done prior to creating any namespaced classes, + * else you will need to modify all of those classes for this to work. + * + * DO NOT change the name of the CodeIgniter namespace or your application + * WILL break. * + * Prototype: + * + * $Config['psr4'] = [ + * 'CodeIgniter' => SYSPATH + * `]; + */ + $psr4 = [ + 'Config' => APPPATH.'Config', + APP_NAMESPACE => APPPATH, // For custom namespace + 'App' => APPPATH, // To ensure filters, etc still found, + 'Tests\Support' => TESTPATH.'_support', // So custom migrations can run during testing + ]; - /** - * ------------------------------------------------------------------- - * Class Map - * ------------------------------------------------------------------- - * The class map provides a map of class names and their exact - * location on the drive. Classes loaded in this manner will have - * slightly faster performance because they will not have to be - * searched for within one or more directories as they would if they - * were being autoloaded through a namespace. - * - * Prototype: - * - * $Config['classmap'] = [ - * 'MyClass' => '/path/to/class/file.php' - * ]; - */ - $classmap = []; + /** + * ------------------------------------------------------------------- + * Class Map + * ------------------------------------------------------------------- + * The class map provides a map of class names and their exact + * location on the drive. Classes loaded in this manner will have + * slightly faster performance because they will not have to be + * searched for within one or more directories as they would if they + * were being autoloaded through a namespace. + * + * Prototype: + * + * $Config['classmap'] = [ + * 'MyClass' => '/path/to/class/file.php' + * ]; + */ + $classmap = []; - //-------------------------------------------------------------------- - // Do Not Edit Below This Line - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // Do Not Edit Below This Line + //-------------------------------------------------------------------- - $this->psr4 = array_merge($this->psr4, $psr4); - $this->classmap = array_merge($this->classmap, $classmap); + $this->psr4 = array_merge($this->psr4, $psr4); + $this->classmap = array_merge($this->classmap, $classmap); - unset($psr4, $classmap); - } + unset($psr4, $classmap); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Config/Cache.php b/application/Config/Cache.php index 781432aae7ab..0a76d50985bd 100644 --- a/application/Config/Cache.php +++ b/application/Config/Cache.php @@ -4,116 +4,116 @@ class Cache extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Primary Handler - |-------------------------------------------------------------------------- - | - | The name of the preferred handler that should be used. If for some reason - | it is not available, the $backupHandler will be used in its place. - | - */ - public $handler = 'file'; + /* + |-------------------------------------------------------------------------- + | Primary Handler + |-------------------------------------------------------------------------- + | + | The name of the preferred handler that should be used. If for some reason + | it is not available, the $backupHandler will be used in its place. + | + */ + public $handler = 'file'; - /* - |-------------------------------------------------------------------------- - | Backup Handler - |-------------------------------------------------------------------------- - | - | The name of the handler that will be used in case the first one is - | unreachable. Often, 'file' is used here since the filesystem is - | always available, though that's not always practical for the app. - | - */ - public $backupHandler = 'dummy'; + /* + |-------------------------------------------------------------------------- + | Backup Handler + |-------------------------------------------------------------------------- + | + | The name of the handler that will be used in case the first one is + | unreachable. Often, 'file' is used here since the filesystem is + | always available, though that's not always practical for the app. + | + */ + public $backupHandler = 'dummy'; - /* - |-------------------------------------------------------------------------- - | Cache Directory Path - |-------------------------------------------------------------------------- - | - | The path to where cache files should be stored, if using a file-based - | system. - | - */ - public $storePath = WRITEPATH.'cache/'; + /* + |-------------------------------------------------------------------------- + | Cache Directory Path + |-------------------------------------------------------------------------- + | + | The path to where cache files should be stored, if using a file-based + | system. + | + */ + public $storePath = WRITEPATH.'cache/'; - /* - |-------------------------------------------------------------------------- - | Cache Include Query String - |-------------------------------------------------------------------------- - | - | Whether to take the URL query string into consideration when generating - | output cache files. Valid options are: - | - | false = Disabled - | true = Enabled, take all query parameters into account. - | Please be aware that this may result in numerous cache - | files generated for the same page over and over again. - | array('q') = Enabled, but only take into account the specified list - | of query parameters. - | - */ - public $cacheQueryString = false; + /* + |-------------------------------------------------------------------------- + | Cache Include Query String + |-------------------------------------------------------------------------- + | + | Whether to take the URL query string into consideration when generating + | output cache files. Valid options are: + | + | false = Disabled + | true = Enabled, take all query parameters into account. + | Please be aware that this may result in numerous cache + | files generated for the same page over and over again. + | array('q') = Enabled, but only take into account the specified list + | of query parameters. + | + */ + public $cacheQueryString = false; - /* - |-------------------------------------------------------------------------- - | Key Prefix - |-------------------------------------------------------------------------- - | - | This string is added to all cache item names to help avoid collisions - | if you run multiple applications with the same cache engine. - | - */ - public $prefix = ''; + /* + |-------------------------------------------------------------------------- + | Key Prefix + |-------------------------------------------------------------------------- + | + | This string is added to all cache item names to help avoid collisions + | if you run multiple applications with the same cache engine. + | + */ + public $prefix = ''; - /* - | ------------------------------------------------------------------------- - | Memcached settings - | ------------------------------------------------------------------------- - | Your Memcached servers can be specified below, if you are using - | the Memcached drivers. - | - | See: https://codeigniter.com/user_guide/libraries/caching.html#memcached - | - */ - public $memcached = [ - 'host' => '127.0.0.1', - 'port' => 11211, - 'weight' => 1, - 'raw' => false, - ]; + /* + | ------------------------------------------------------------------------- + | Memcached settings + | ------------------------------------------------------------------------- + | Your Memcached servers can be specified below, if you are using + | the Memcached drivers. + | + | See: https://codeigniter.com/user_guide/libraries/caching.html#memcached + | + */ + public $memcached = [ + 'host' => '127.0.0.1', + 'port' => 11211, + 'weight' => 1, + 'raw' => false, + ]; - /* - | ------------------------------------------------------------------------- - | Redis settings - | ------------------------------------------------------------------------- - | Your Redis server can be specified below, if you are using - | the Redis or Predis drivers. - | - */ - public $redis = [ - 'host' => '127.0.0.1', - 'password' => null, - 'port' => 6379, - 'timeout' => 0, - ]; + /* + | ------------------------------------------------------------------------- + | Redis settings + | ------------------------------------------------------------------------- + | Your Redis server can be specified below, if you are using + | the Redis or Predis drivers. + | + */ + public $redis = [ + 'host' => '127.0.0.1', + 'password' => null, + 'port' => 6379, + 'timeout' => 0, + ]; - /* - |-------------------------------------------------------------------------- - | Available Cache Handlers - |-------------------------------------------------------------------------- - | - | This is an array of cache engine alias' and class names. Only engines - | that are listed here are allowed to be used. - | - */ - public $validHandlers = [ - 'dummy' => \CodeIgniter\Cache\Handlers\DummyHandler::class, - 'file' => \CodeIgniter\Cache\Handlers\FileHandler::class, - 'memcached' => \CodeIgniter\Cache\Handlers\MemcachedHandler::class, - 'predis' => \CodeIgniter\Cache\Handlers\PredisHandler::class, - 'redis' => \CodeIgniter\Cache\Handlers\RedisHandler::class, - 'wincache' => \CodeIgniter\Cache\Handlers\WincacheHandler::class, - ]; + /* + |-------------------------------------------------------------------------- + | Available Cache Handlers + |-------------------------------------------------------------------------- + | + | This is an array of cache engine alias' and class names. Only engines + | that are listed here are allowed to be used. + | + */ + public $validHandlers = [ + 'dummy' => \CodeIgniter\Cache\Handlers\DummyHandler::class, + 'file' => \CodeIgniter\Cache\Handlers\FileHandler::class, + 'memcached' => \CodeIgniter\Cache\Handlers\MemcachedHandler::class, + 'predis' => \CodeIgniter\Cache\Handlers\PredisHandler::class, + 'redis' => \CodeIgniter\Cache\Handlers\RedisHandler::class, + 'wincache' => \CodeIgniter\Cache\Handlers\WincacheHandler::class, + ]; } diff --git a/application/Config/ContentSecurityPolicy.php b/application/Config/ContentSecurityPolicy.php index 6a79136c1ebb..22c0ad17a51f 100644 --- a/application/Config/ContentSecurityPolicy.php +++ b/application/Config/ContentSecurityPolicy.php @@ -13,37 +13,37 @@ */ class ContentSecurityPolicy extends BaseConfig { - public $reportOnly = false; + public $reportOnly = false; - public $defaultSrc = 'none'; + public $defaultSrc = 'none'; - public $scriptSrc = 'self'; + public $scriptSrc = 'self'; - public $styleSrc = 'self'; + public $styleSrc = 'self'; - public $imageSrc = 'self'; + public $imageSrc = 'self'; - public $base_uri = null; + public $base_uri = null; - public $childSrc = null; + public $childSrc = null; - public $connectSrc = 'self'; + public $connectSrc = 'self'; - public $fontSrc = null; + public $fontSrc = null; - public $formAction = null; + public $formAction = null; - public $frameAncestors = null; + public $frameAncestors = null; - public $mediaSrc = null; + public $mediaSrc = null; - public $objectSrc = null; + public $objectSrc = null; - public $pluginTypes = null; + public $pluginTypes = null; - public $reportURI = null; + public $reportURI = null; - public $sandbox = false; + public $sandbox = false; - public $upgradeInsecureRequests = false; + public $upgradeInsecureRequests = false; } diff --git a/application/Config/Database.php b/application/Config/Database.php index f6c867c878c8..839186347179 100644 --- a/application/Config/Database.php +++ b/application/Config/Database.php @@ -7,107 +7,107 @@ */ class Database extends \CodeIgniter\Database\Config { - /** - * The directory that holds the Migrations - * and Seeds directories. - * @var string - */ - public $filesPath = APPPATH.'Database/'; + /** + * The directory that holds the Migrations + * and Seeds directories. + * @var string + */ + public $filesPath = APPPATH.'Database/'; - /** - * Lets you choose which connection group to - * use if no other is specified. - * - * @var string - */ - public $defaultGroup = 'default'; + /** + * Lets you choose which connection group to + * use if no other is specified. + * + * @var string + */ + public $defaultGroup = 'default'; - /** - * The default database connection. - * - * @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 - ]; + /** + * The default database connection. + * + * @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 + ]; - /** - * This database connection is used when - * running PHPUnit database tests. - * - * @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 - ]; + /** + * This database connection is used when + * running PHPUnit database tests. + * + * @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 + ]; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function __construct() - { - parent::__construct(); + public function __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') - { - $this->defaultGroup = 'tests'; + // 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') + { + $this->defaultGroup = 'tests'; - // Under Travis-CI, we can set an ENV var named 'DB_GROUP' - // so that we can test against multiple databases. - if ($group = getenv('DB')) - { - if (is_file(TESTPATH.'travis/Database.php')) - { - require TESTPATH.'travis/Database.php'; + // Under Travis-CI, we can set an ENV var named 'DB_GROUP' + // so that we can test against multiple databases. + if ($group = getenv('DB')) + { + if (is_file(TESTPATH.'travis/Database.php')) + { + require TESTPATH.'travis/Database.php'; - if ( ! empty($dbconfig) && array_key_exists($group, $dbconfig)) - { - $this->tests = $dbconfig[$group]; - } - } - } - } - } + if ( ! empty($dbconfig) && array_key_exists($group, $dbconfig)) + { + $this->tests = $dbconfig[$group]; + } + } + } + } + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Config/DocTypes.php b/application/Config/DocTypes.php index 37830984c31f..91223ca06d2d 100755 --- a/application/Config/DocTypes.php +++ b/application/Config/DocTypes.php @@ -8,26 +8,26 @@ class DocTypes { - static $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' => '', - 'xhtml-math-svg-xh' => '', - 'xhtml-math-svg-sh' => '', - 'xhtml-rdfa-1' => '', - 'xhtml-rdfa-2' => '' - ]; -} \ No newline at end of file + static $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' => '', + 'xhtml-math-svg-xh' => '', + 'xhtml-math-svg-sh' => '', + 'xhtml-rdfa-1' => '', + 'xhtml-rdfa-2' => '' + ]; +} diff --git a/application/Config/Email.php b/application/Config/Email.php index c5dfd13ae70e..0e1e8e88f51d 100644 --- a/application/Config/Email.php +++ b/application/Config/Email.php @@ -2,139 +2,139 @@ class Email { - /** - * @var string - */ - public $fromEmail; - - /** - * @var string - */ - public $fromName; - - /** - * 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 - */ - public $SMTPPort = 25; - - /** - * SMTP Timeout (in seconds) - * @var int - */ - public $SMTPTimeout = 5; - - /** - * Enable persistent SMTP connections - * @var bool - */ - public $SMTPKeepAlive = false; - - /** - * SMTP Encryption. Either tls or ssl - * @var string - */ - public $SMTPCrypto = 'tls'; - - /** - * Enable word-wrap - * @var bool - */ - public $wordWrap = true; - - /** - * Character count to wrap at - * @var int - */ - 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 - */ - public $validate = false; - - /** - * Email Priority. 1 = highest. 5 = lowest. 3 = normal - * @var int - */ - 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 - */ - public $BCCBatchMode = false; - - /** - * Number of emails in each BCC batch - * @var int - */ - public $BCCBatchSize = 200; - - /** - * Enable notify message from server - * @var bool - */ - public $DSN = false; + /** + * @var string + */ + public $fromEmail; + + /** + * @var string + */ + public $fromName; + + /** + * 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 + */ + public $SMTPPort = 25; + + /** + * SMTP Timeout (in seconds) + * @var int + */ + public $SMTPTimeout = 5; + + /** + * Enable persistent SMTP connections + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * SMTP Encryption. Either tls or ssl + * @var string + */ + public $SMTPCrypto = 'tls'; + + /** + * Enable word-wrap + * @var bool + */ + public $wordWrap = true; + + /** + * Character count to wrap at + * @var int + */ + 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 + */ + public $validate = false; + + /** + * Email Priority. 1 = highest. 5 = lowest. 3 = normal + * @var int + */ + 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 + */ + public $BCCBatchMode = false; + + /** + * Number of emails in each BCC batch + * @var int + */ + public $BCCBatchSize = 200; + + /** + * Enable notify message from server + * @var bool + */ + public $DSN = false; } diff --git a/application/Config/Events.php b/application/Config/Events.php index 47781585a450..721cde7b35b9 100644 --- a/application/Config/Events.php +++ b/application/Config/Events.php @@ -29,8 +29,8 @@ */ if (ENVIRONMENT != 'production') { - Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect'); + Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect'); - // Handles the display of the toolbar itself. MUST remain here for toolbar to be displayed. - Events::on('pre_system', 'CodeIgniter\Debug\Toolbar::eventHandler'); + // Handles the display of the toolbar itself. MUST remain here for toolbar to be displayed. + Events::on('pre_system', 'CodeIgniter\Debug\Toolbar::eventHandler'); } diff --git a/application/Config/Exceptions.php b/application/Config/Exceptions.php index 3b3fa2779169..2c6a6b7f60b8 100644 --- a/application/Config/Exceptions.php +++ b/application/Config/Exceptions.php @@ -7,34 +7,34 @@ */ class Exceptions { - /* - |-------------------------------------------------------------------------- - | LOG EXCEPTIONS? - |-------------------------------------------------------------------------- - | If true, then exceptions will be logged - | through Services::Log. - | - | Default: true - */ - public $log = true; + /* + |-------------------------------------------------------------------------- + | LOG EXCEPTIONS? + |-------------------------------------------------------------------------- + | If true, then exceptions will be logged + | through Services::Log. + | + | Default: true + */ + public $log = true; - /* - |-------------------------------------------------------------------------- - | DO NOT LOG STATUS CODES - |-------------------------------------------------------------------------- - | Any status codes here will NOT be logged if logging is turned on. - | By default, only 404 (Page Not Found) exceptions are ignored. - */ - public $ignoreCodes = [ 404 ]; + /* + |-------------------------------------------------------------------------- + | DO NOT LOG STATUS CODES + |-------------------------------------------------------------------------- + | Any status codes here will NOT be logged if logging is turned on. + | By default, only 404 (Page Not Found) exceptions are ignored. + */ + public $ignoreCodes = [ 404 ]; - /* - |-------------------------------------------------------------------------- - | Error Views Path - |-------------------------------------------------------------------------- - | This is the path to the directory that contains the 'cli' and 'html' - | directories that hold the views used to generate errors. - | - | Default: APPPATH.'Views/errors' - */ - public $errorViewPath = APPPATH.'Views/errors'; + /* + |-------------------------------------------------------------------------- + | Error Views Path + |-------------------------------------------------------------------------- + | This is the path to the directory that contains the 'cli' and 'html' + | directories that hold the views used to generate errors. + | + | Default: APPPATH.'Views/errors' + */ + public $errorViewPath = APPPATH.'Views/errors'; } diff --git a/application/Config/Filters.php b/application/Config/Filters.php index cb16f8137b64..81219f480bd0 100644 --- a/application/Config/Filters.php +++ b/application/Config/Filters.php @@ -4,30 +4,30 @@ 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, - ]; + // 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, + ]; - // Always applied before every request - public $globals = [ - 'before' => [ - // 'csrf' - ], - 'after' => [ - 'toolbar' - ] - ]; + // Always applied before every request + public $globals = [ + 'before' => [ + // 'csrf' + ], + 'after' => [ + 'toolbar' + ] + ]; - // Works on all of a particular HTTP method - // (GET, POST, etc) as BEFORE filters only - // like: 'post' => ['CSRF', 'throttle'], - public $methods = []; + // Works on all of a particular HTTP method + // (GET, POST, etc) as BEFORE filters only + // like: 'post' => ['CSRF', 'throttle'], + public $methods = []; - // List filter aliases and any before/after uri patterns - // that they should run on, like: - // 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']], - public $filters = []; + // List filter aliases and any before/after uri patterns + // that they should run on, like: + // 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']], + public $filters = []; } diff --git a/application/Config/Format.php b/application/Config/Format.php index 57cb81ed82c0..88ceee8a8848 100644 --- a/application/Config/Format.php +++ b/application/Config/Format.php @@ -4,68 +4,68 @@ class Format extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Available Response Formats - |-------------------------------------------------------------------------- - | - | When you perform content negotiation with the request, these are the - | available formats that your application supports. This is currently - | only used with the API\ResponseTrait. A valid Formatter must exist - | for the specified format. - | - | These formats are only checked when the data passed to the respond() - | method is an array. - | - */ - public $supportedResponseFormats = [ - 'application/json', - 'application/xml', // machine-readable XML - 'text/xml' // human-readable XML - ]; + /* + |-------------------------------------------------------------------------- + | Available Response Formats + |-------------------------------------------------------------------------- + | + | When you perform content negotiation with the request, these are the + | available formats that your application supports. This is currently + | only used with the API\ResponseTrait. A valid Formatter must exist + | for the specified format. + | + | These formats are only checked when the data passed to the respond() + | method is an array. + | + */ + public $supportedResponseFormats = [ + 'application/json', + 'application/xml', // machine-readable XML + 'text/xml' // human-readable XML + ]; - /* - |-------------------------------------------------------------------------- - | Formatters - |-------------------------------------------------------------------------- - | - | Lists the class to use to format responses with of a particular type. - | For each mime type, list the class that should be used. Formatters - | can be retrieved through the getFormatter() method. - | - */ - public $formatters = [ - 'application/json' => \CodeIgniter\Format\JSONFormatter::class, - 'application/xml' => \CodeIgniter\Format\XMLFormatter::class, - 'text/xml' => \CodeIgniter\Format\XMLFormatter::class, - ]; + /* + |-------------------------------------------------------------------------- + | Formatters + |-------------------------------------------------------------------------- + | + | Lists the class to use to format responses with of a particular type. + | For each mime type, list the class that should be used. Formatters + | can be retrieved through the getFormatter() method. + | + */ + public $formatters = [ + 'application/json' => \CodeIgniter\Format\JSONFormatter::class, + 'application/xml' => \CodeIgniter\Format\XMLFormatter::class, + 'text/xml' => \CodeIgniter\Format\XMLFormatter::class, + ]; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * A Factory method to return the appropriate formatter for the given mime type. - * - * @param string $mime - * - * @return \CodeIgniter\Format\FormatterInterface - */ - public function getFormatter(string $mime) - { - if (! array_key_exists($mime, $this->formatters)) - { - throw new \InvalidArgumentException('No Formatter defined for mime type: '. $mime); - } + /** + * A Factory method to return the appropriate formatter for the given mime type. + * + * @param string $mime + * + * @return \CodeIgniter\Format\FormatterInterface + */ + public function getFormatter(string $mime) + { + if (! array_key_exists($mime, $this->formatters)) + { + throw new \InvalidArgumentException('No Formatter defined for mime type: '. $mime); + } - $class = $this->formatters[$mime]; + $class = $this->formatters[$mime]; - if (! class_exists($class)) - { - throw new \BadMethodCallException($class.' is not a valid Formatter.'); - } + if (! class_exists($class)) + { + throw new \BadMethodCallException($class.' is not a valid Formatter.'); + } - return new $class(); - } + return new $class(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Config/Images.php b/application/Config/Images.php index c819ba29c205..826d969db34b 100644 --- a/application/Config/Images.php +++ b/application/Config/Images.php @@ -4,28 +4,28 @@ class Images extends BaseConfig { - /** - * Default handler used if no other handler is specified. - * - * @var string - */ - public $defaultHandler = 'gd'; + /** + * Default handler used if no other handler is specified. + * + * @var string + */ + public $defaultHandler = 'gd'; - /** - * The path to the image library. - * Required for ImageMagick, GraphicsMagick, or NetPBM. - * - * @var string - */ - public $libraryPath = '/usr/local/bin/convert'; + /** + * The path to the image library. + * Required for ImageMagick, GraphicsMagick, or NetPBM. + * + * @var string + */ + public $libraryPath = '/usr/local/bin/convert'; - /** - * The available handler classes. - * - * @var array - */ - public $handlers = [ - 'gd' => \CodeIgniter\Images\Handlers\GDHandler::class, - 'imagick' => \CodeIgniter\Images\Handlers\ImageMagickHandler::class, - ]; + /** + * The available handler classes. + * + * @var array + */ + public $handlers = [ + '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 5a71085b2156..035c6b0c7fad 100644 --- a/application/Config/Logger.php +++ b/application/Config/Logger.php @@ -4,130 +4,130 @@ class Logger extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Error Logging Threshold - |-------------------------------------------------------------------------- - | - | You can enable error logging by setting a threshold over zero. The - | threshold determines what gets logged. Any values below or equal to the - | threshold will be logged. Threshold options are: - | - | 0 = Disables logging, Error logging TURNED OFF - | 1 = Emergency Messages - System is unusable - | 2 = Alert Messages - Action Must Be Taken Immediately - | 3 = Critical Messages - Application component unavailable, unexpected exception. - | 4 = Runtime Errors - Don't need immediate action, but should be monitored. - | 5 = Debug - Detailed debug information. - | 6 = Warnings - Exceptional occurrences that are not errors. - | 7 = Notices - Normal but significant events. - | 8 = Info - Interesting events, like user logging in, etc. - | 9 = All Messages - | - | You can also pass an array with threshold levels to show individual error types - | - | array(1, 2, 3, 5) = Emergency, Alert, Critical, and Debug messages - | - | For a live site you'll usually enable Critical or higher (3) to be logged otherwise - | your log files will fill up very fast. - | - */ - public $threshold = 3; + /* + |-------------------------------------------------------------------------- + | Error Logging Threshold + |-------------------------------------------------------------------------- + | + | You can enable error logging by setting a threshold over zero. The + | threshold determines what gets logged. Any values below or equal to the + | threshold will be logged. Threshold options are: + | + | 0 = Disables logging, Error logging TURNED OFF + | 1 = Emergency Messages - System is unusable + | 2 = Alert Messages - Action Must Be Taken Immediately + | 3 = Critical Messages - Application component unavailable, unexpected exception. + | 4 = Runtime Errors - Don't need immediate action, but should be monitored. + | 5 = Debug - Detailed debug information. + | 6 = Warnings - Exceptional occurrences that are not errors. + | 7 = Notices - Normal but significant events. + | 8 = Info - Interesting events, like user logging in, etc. + | 9 = All Messages + | + | You can also pass an array with threshold levels to show individual error types + | + | array(1, 2, 3, 5) = Emergency, Alert, Critical, and Debug messages + | + | For a live site you'll usually enable Critical or higher (3) to be logged otherwise + | your log files will fill up very fast. + | + */ + public $threshold = 3; - /* - |-------------------------------------------------------------------------- - | Error Logging Directory Path - |-------------------------------------------------------------------------- - | - | - | - */ - public $path = ''; + /* + |-------------------------------------------------------------------------- + | Error Logging Directory Path + |-------------------------------------------------------------------------- + | + | + | + */ + public $path = ''; - /* - |-------------------------------------------------------------------------- - | Date Format for Logs - |-------------------------------------------------------------------------- - | - | Each item that is logged has an associated date. You can use PHP date - | codes to set your own date formatting - | - */ - public $dateFormat = 'Y-m-d H:i:s'; + /* + |-------------------------------------------------------------------------- + | Date Format for Logs + |-------------------------------------------------------------------------- + | + | Each item that is logged has an associated date. You can use PHP date + | codes to set your own date formatting + | + */ + public $dateFormat = 'Y-m-d H:i:s'; - /* - |-------------------------------------------------------------------------- - | Log Handlers - |-------------------------------------------------------------------------- - | - | The logging system supports multiple actions to be taken when something - | is logged. This is done by allowing for multiple Handlers, special classes - | designed to write the log to their chosen destinations, whether that is - | a file on the getServer, a cloud-based service, or even taking actions such - | as emailing the dev team. - | - | Each handler is defined by the class name used for that handler, and it - | MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface. - | - | The value of each key is an array of configuration items that are sent - | to the constructor of each handler. The only required configuration item - | is the 'handles' element, which must be an array of integer log levels. - | This is most easily handled by using the constants defined in the - | Psr\Log\LogLevel class. - | - | Handlers are executed in the order defined in this array, starting with - | the handler on top and continuing down. - | - */ - public $handlers = [ + /* + |-------------------------------------------------------------------------- + | Log Handlers + |-------------------------------------------------------------------------- + | + | The logging system supports multiple actions to be taken when something + | is logged. This is done by allowing for multiple Handlers, special classes + | designed to write the log to their chosen destinations, whether that is + | a file on the getServer, a cloud-based service, or even taking actions such + | as emailing the dev team. + | + | Each handler is defined by the class name used for that handler, and it + | MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface. + | + | The value of each key is an array of configuration items that are sent + | to the constructor of each handler. The only required configuration item + | is the 'handles' element, which must be an array of integer log levels. + | This is most easily handled by using the constants defined in the + | Psr\Log\LogLevel class. + | + | Handlers are executed in the order defined in this array, starting with + | the handler on top and continuing down. + | + */ + public $handlers = [ - //-------------------------------------------------------------------- - // File Handler - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // File Handler + //-------------------------------------------------------------------- - 'CodeIgniter\Log\Handlers\FileHandler' => [ + 'CodeIgniter\Log\Handlers\FileHandler' => [ - /* - * The log levels that this handler will handle. - */ - 'handles' => ['critical', 'alert', 'emergency', 'debug', - 'error', 'info', 'notice', 'warning'], + /* + * The log levels that this handler will handle. + */ + '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/', + /* + * 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/', - /* - * 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'], -// ] - ]; + /** + * 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'], +// ] + ]; } diff --git a/application/Config/Migrations.php b/application/Config/Migrations.php index c746a22cba1b..d763e8dd8e0f 100644 --- a/application/Config/Migrations.php +++ b/application/Config/Migrations.php @@ -4,60 +4,60 @@ class Migrations extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Enable/Disable Migrations - |-------------------------------------------------------------------------- - | - | Migrations are disabled by default for security reasons. - | You should enable migrations whenever you intend to do a schema migration - | and disable it back when you're done. - | - */ - public $enabled = false; + /* + |-------------------------------------------------------------------------- + | Enable/Disable Migrations + |-------------------------------------------------------------------------- + | + | Migrations are disabled by default for security reasons. + | You should enable migrations whenever you intend to do a schema migration + | and disable it back when you're done. + | + */ + public $enabled = false; - /* - |-------------------------------------------------------------------------- - | Migration Type - |-------------------------------------------------------------------------- - | - | Migration file names may be based on a sequential identifier or on - | a timestamp. Options are: - | - | 'sequential' = Sequential migration naming (001_add_blog.php) - | 'timestamp' = Timestamp migration naming (20121031104401_add_blog.php) - | Use timestamp format YYYYMMDDHHIISS. - | - | Note: If this configuration value is missing the Migration library - | defaults to 'sequential' for backward compatibility with CI2. - | - */ - public $type = 'timestamp'; + /* + |-------------------------------------------------------------------------- + | Migration Type + |-------------------------------------------------------------------------- + | + | Migration file names may be based on a sequential identifier or on + | a timestamp. Options are: + | + | 'sequential' = Sequential migration naming (001_add_blog.php) + | 'timestamp' = Timestamp migration naming (20121031104401_add_blog.php) + | Use timestamp format YYYYMMDDHHIISS. + | + | Note: If this configuration value is missing the Migration library + | defaults to 'sequential' for backward compatibility with CI2. + | + */ + public $type = 'timestamp'; - /* - |-------------------------------------------------------------------------- - | Migrations table - |-------------------------------------------------------------------------- - | - | This is the name of the table that will store the current migrations state. - | When migrations runs it will store in a database table which migration - | level the system is at. It then compares the migration level in this - | table to the $config['migration_version'] if they are not the same it - | will migrate up. This must be set. - | - */ - public $table = 'migrations'; + /* + |-------------------------------------------------------------------------- + | Migrations table + |-------------------------------------------------------------------------- + | + | This is the name of the table that will store the current migrations state. + | When migrations runs it will store in a database table which migration + | level the system is at. It then compares the migration level in this + | table to the $config['migration_version'] if they are not the same it + | will migrate up. This must be set. + | + */ + public $table = 'migrations'; - /* - |-------------------------------------------------------------------------- - | Migrations version - |-------------------------------------------------------------------------- - | - | This is used to set migration version that the file system should be on. - | If you run $this->migration->current() this is the version that schema will - | be upgraded / downgraded to. - | - */ - public $currentVersion = 0; + /* + |-------------------------------------------------------------------------- + | Migrations version + |-------------------------------------------------------------------------- + | + | This is used to set migration version that the file system should be on. + | If you run $this->migration->current() this is the version that schema will + | be upgraded / downgraded to. + | + */ + public $currentVersion = 0; } diff --git a/application/Config/Mimes.php b/application/Config/Mimes.php index 25a9224f035c..f8029bf1d7ba 100644 --- a/application/Config/Mimes.php +++ b/application/Config/Mimes.php @@ -15,316 +15,316 @@ */ class Mimes { - /** - * Map of extensions to mime types. - * - * @var array - */ - public static $mimes = [ - 'hqx' => [ - 'application/mac-binhex40', - 'application/mac-binhex', - 'application/x-binhex40', - 'application/x-mac-binhex40', - ], - 'cpt' => 'application/mac-compactpro', - 'csv' => [ - 'text/csv', - 'text/x-comma-separated-values', - 'text/comma-separated-values', - 'application/octet-stream', - 'application/vnd.ms-excel', - 'application/x-csv', - 'text/x-csv', - 'application/csv', - 'application/excel', - 'application/vnd.msexcel', - 'text/plain', - ], - 'bin' => [ - 'application/macbinary', - 'application/mac-binary', - 'application/octet-stream', - 'application/x-binary', - 'application/x-macbinary', - ], - 'dms' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'exe' => ['application/octet-stream', 'application/x-msdownload'], - 'class' => 'application/octet-stream', - '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'], - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => [ - 'application/vnd.ms-excel', - 'application/msexcel', - 'application/x-msexcel', - 'application/x-ms-excel', - 'application/x-excel', - 'application/x-dos_ms_excel', - 'application/xls', - 'application/x-xls', - 'application/excel', - 'application/download', - 'application/vnd.ms-office', - 'application/msword', - ], - 'ppt' => [ - 'application/vnd.ms-powerpoint', - 'application/powerpoint', - 'application/vnd.ms-office', - 'application/msword', - ], - 'pptx' => [ - 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'application/x-zip', - 'application/zip', - ], - 'wbxml' => 'application/wbxml', - 'wmlc' => 'application/wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'gz' => 'application/x-gzip', - 'gzip' => 'application/x-gzip', - 'php' => [ - 'application/x-php', - 'application/x-httpd-php', - 'application/php', - 'text/php', - 'text/x-php', - 'application/x-httpd-php-source', - ], - 'php4' => 'application/x-httpd-php', - 'php3' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - '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'], - 'z' => 'application/x-compress', - 'xhtml' => 'application/xhtml+xml', - 'xht' => 'application/xhtml+xml', - 'zip' => [ - 'application/x-zip', - 'application/zip', - 'application/x-zip-compressed', - 'application/s-compressed', - 'multipart/x-zip', - ], - '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'], - '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'], - 'bmp' => [ - 'image/bmp', - 'image/x-bmp', - 'image/x-bitmap', - 'image/x-xbitmap', - 'image/x-win-bitmap', - 'image/x-windows-bmp', - 'image/ms-bmp', - 'image/x-ms-bmp', - 'application/bmp', - 'application/x-bmp', - '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'], - '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'], - 'txt' => 'text/plain', - 'text' => 'text/plain', - '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'], - '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'], - 'movie' => 'video/x-sgi-movie', - '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'], - 'dotx' => [ - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'application/zip', - 'application/msword', - ], - 'xlsx' => [ - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'application/zip', - 'application/vnd.ms-excel', - 'application/msword', - 'application/x-zip', - ], - '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'], - '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'], - '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'], - 'der' => 'application/x-x509-ca-cert', - 'kdb' => 'application/octet-stream', - 'pgp' => 'application/pgp', - 'gpg' => 'application/gpg-keys', - 'sst' => 'application/octet-stream', - 'csr' => 'application/octet-stream', - 'rsa' => 'application/x-pkcs7', - 'cer' => ['application/pkix-cert', 'application/x-x509-ca-cert'], - '3g2' => 'video/3gpp2', - '3gp' => ['video/3gp', 'video/3gpp'], - 'mp4' => 'video/mp4', - 'm4a' => 'audio/x-m4a', - 'f4v' => ['video/mp4', 'video/x-f4v'], - 'flv' => 'video/x-flv', - 'webm' => 'video/webm', - 'aac' => 'audio/x-acc', - 'm4u' => 'application/vnd.mpegurl', - 'm3u' => 'text/plain', - 'xspf' => 'application/xspf+xml', - 'vlc' => 'application/videolan', - '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'], - 'ics' => 'text/calendar', - 'ical' => 'text/calendar', - 'zsh' => 'text/x-scriptzsh', - '7zip' => ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'], - 'cdr' => [ - 'application/cdr', - 'application/coreldraw', - 'application/x-cdr', - 'application/x-coreldraw', - 'image/cdr', - 'image/x-cdr', - 'zz-application/zz-winassoc-cdr', - ], - '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'], - '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'], - ]; + /** + * Map of extensions to mime types. + * + * @var array + */ + public static $mimes = [ + 'hqx' => [ + 'application/mac-binhex40', + 'application/mac-binhex', + 'application/x-binhex40', + 'application/x-mac-binhex40', + ], + 'cpt' => 'application/mac-compactpro', + 'csv' => [ + 'text/csv', + 'text/x-comma-separated-values', + 'text/comma-separated-values', + 'application/octet-stream', + 'application/vnd.ms-excel', + 'application/x-csv', + 'text/x-csv', + 'application/csv', + 'application/excel', + 'application/vnd.msexcel', + 'text/plain', + ], + 'bin' => [ + 'application/macbinary', + 'application/mac-binary', + 'application/octet-stream', + 'application/x-binary', + 'application/x-macbinary', + ], + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => ['application/octet-stream', 'application/x-msdownload'], + 'class' => 'application/octet-stream', + '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'], + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => [ + 'application/vnd.ms-excel', + 'application/msexcel', + 'application/x-msexcel', + 'application/x-ms-excel', + 'application/x-excel', + 'application/x-dos_ms_excel', + 'application/xls', + 'application/x-xls', + 'application/excel', + 'application/download', + 'application/vnd.ms-office', + 'application/msword', + ], + 'ppt' => [ + 'application/vnd.ms-powerpoint', + 'application/powerpoint', + 'application/vnd.ms-office', + 'application/msword', + ], + 'pptx' => [ + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'application/x-zip', + 'application/zip', + ], + 'wbxml' => 'application/wbxml', + 'wmlc' => 'application/wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'gzip' => 'application/x-gzip', + 'php' => [ + 'application/x-php', + 'application/x-httpd-php', + 'application/php', + 'text/php', + 'text/x-php', + 'application/x-httpd-php-source', + ], + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + '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'], + 'z' => 'application/x-compress', + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => [ + 'application/x-zip', + 'application/zip', + 'application/x-zip-compressed', + 'application/s-compressed', + 'multipart/x-zip', + ], + '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'], + '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'], + 'bmp' => [ + 'image/bmp', + 'image/x-bmp', + 'image/x-bitmap', + 'image/x-xbitmap', + 'image/x-win-bitmap', + 'image/x-windows-bmp', + 'image/ms-bmp', + 'image/x-ms-bmp', + 'application/bmp', + 'application/x-bmp', + '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'], + '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'], + 'txt' => 'text/plain', + 'text' => 'text/plain', + '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'], + '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'], + 'movie' => 'video/x-sgi-movie', + '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'], + 'dotx' => [ + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/zip', + 'application/msword', + ], + 'xlsx' => [ + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/zip', + 'application/vnd.ms-excel', + 'application/msword', + 'application/x-zip', + ], + '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'], + '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'], + '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'], + 'der' => 'application/x-x509-ca-cert', + 'kdb' => 'application/octet-stream', + 'pgp' => 'application/pgp', + 'gpg' => 'application/gpg-keys', + 'sst' => 'application/octet-stream', + 'csr' => 'application/octet-stream', + 'rsa' => 'application/x-pkcs7', + 'cer' => ['application/pkix-cert', 'application/x-x509-ca-cert'], + '3g2' => 'video/3gpp2', + '3gp' => ['video/3gp', 'video/3gpp'], + 'mp4' => 'video/mp4', + 'm4a' => 'audio/x-m4a', + 'f4v' => ['video/mp4', 'video/x-f4v'], + 'flv' => 'video/x-flv', + 'webm' => 'video/webm', + 'aac' => 'audio/x-acc', + 'm4u' => 'application/vnd.mpegurl', + 'm3u' => 'text/plain', + 'xspf' => 'application/xspf+xml', + 'vlc' => 'application/videolan', + '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'], + 'ics' => 'text/calendar', + 'ical' => 'text/calendar', + 'zsh' => 'text/x-scriptzsh', + '7zip' => ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'], + 'cdr' => [ + 'application/cdr', + 'application/coreldraw', + 'application/x-cdr', + 'application/x-coreldraw', + 'image/cdr', + 'image/x-cdr', + 'zz-application/zz-winassoc-cdr', + ], + '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'], + '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'], + ]; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Attempts to determine the best mime type for the given file extension. - * - * @param string $extension - * - * @return string|null The mime type found, or none if unable to determine. - */ - public static function guessTypeFromExtension(string $extension) - { - $extension = trim(strtolower($extension), '. '); + /** + * Attempts to determine the best mime type for the given file extension. + * + * @param string $extension + * + * @return string|null The mime type found, or none if unable to determine. + */ + public static function guessTypeFromExtension(string $extension) + { + $extension = trim(strtolower($extension), '. '); - if (! array_key_exists($extension, self::$mimes)) - { - return null; - } + if (! array_key_exists($extension, self::$mimes)) + { + return null; + } - return is_array(self::$mimes[$extension]) ? self::$mimes[$extension][0] : self::$mimes[$extension]; - } + return is_array(self::$mimes[$extension]) ? self::$mimes[$extension][0] : self::$mimes[$extension]; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Attempts to determine the best file extension for a given mime type. - * - * @param string $type - * - * @return string|null The extension determined, or null if unable to match. - */ - public static function guessExtensionFromType(string $type) - { - $type = trim(strtolower($type), '. '); + /** + * Attempts to determine the best file extension for a given mime type. + * + * @param string $type + * + * @return string|null The extension determined, or null if unable to match. + */ + public static function guessExtensionFromType(string $type) + { + $type = trim(strtolower($type), '. '); - foreach (self::$mimes as $ext => $types) - { - if (is_string($types) && $types == $type) - { - return $ext; - } - else if (is_array($types) && in_array($type, $types)) - { - return $ext; - } - } + foreach (self::$mimes as $ext => $types) + { + if (is_string($types) && $types == $type) + { + return $ext; + } + else if (is_array($types) && in_array($type, $types)) + { + return $ext; + } + } - return null; - } + return null; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Config/Pager.php b/application/Config/Pager.php index bfb8ec554e4b..4d4750986b34 100644 --- a/application/Config/Pager.php +++ b/application/Config/Pager.php @@ -4,31 +4,31 @@ class Pager extends BaseConfig { - /* - |-------------------------------------------------------------------------- - | Templates - |-------------------------------------------------------------------------- - | - | Pagination links are rendered out using views to configure their - | appearance. This array contains aliases and the view names to - | use when rendering the links. - | - | Within each view, the Pager object will be available as $pager, - | and the desired group as $pagerGroup; - | - */ - public $templates = [ - 'default_full' => 'CodeIgniter\Pager\Views\default_full', - 'default_simple' => 'CodeIgniter\Pager\Views\default_simple' - ]; + /* + |-------------------------------------------------------------------------- + | Templates + |-------------------------------------------------------------------------- + | + | Pagination links are rendered out using views to configure their + | appearance. This array contains aliases and the view names to + | use when rendering the links. + | + | Within each view, the Pager object will be available as $pager, + | and the desired group as $pagerGroup; + | + */ + public $templates = [ + 'default_full' => 'CodeIgniter\Pager\Views\default_full', + 'default_simple' => 'CodeIgniter\Pager\Views\default_simple' + ]; - /* - |-------------------------------------------------------------------------- - | Items Per Page - |-------------------------------------------------------------------------- - | - | The default number of results shown in a single page. - | - */ - public $perPage = 20; + /* + |-------------------------------------------------------------------------- + | Items Per Page + |-------------------------------------------------------------------------- + | + | The default number of results shown in a single page. + | + */ + public $perPage = 20; } diff --git a/application/Config/Paths.php b/application/Config/Paths.php index c58f91a1adf2..cbfe72d705f4 100644 --- a/application/Config/Paths.php +++ b/application/Config/Paths.php @@ -10,69 +10,69 @@ */ class Paths { - /* - *--------------------------------------------------------------- - * SYSTEM FOLDER NAME - *--------------------------------------------------------------- - * - * This variable must contain the name of your "system" folder. - * Include the path if the folder is not in the same directory - * as this file. - */ - public $systemDirectory = '../system'; + /* + *--------------------------------------------------------------- + * SYSTEM FOLDER NAME + *--------------------------------------------------------------- + * + * This variable must contain the name of your "system" folder. + * Include the path if the folder is not in the same directory + * as this file. + */ + public $systemDirectory = '../system'; - /* - *--------------------------------------------------------------- - * APPLICATION FOLDER NAME - *--------------------------------------------------------------- - * - * If you want this front controller to use a different "application" - * folder than the default one you can set its name here. The folder - * can also be renamed or relocated anywhere on your getServer. If - * you do, use a full getServer path. For more info please see the user guide: - * http://codeigniter.com/user_guide/general/managing_apps.html - * - * NO TRAILING SLASH! - */ - public $applicationDirectory = '../application'; + /* + *--------------------------------------------------------------- + * APPLICATION FOLDER NAME + *--------------------------------------------------------------- + * + * If you want this front controller to use a different "application" + * folder than the default one you can set its name here. The folder + * can also be renamed or relocated anywhere on your getServer. If + * you do, use a full getServer path. For more info please see the user guide: + * http://codeigniter.com/user_guide/general/managing_apps.html + * + * NO TRAILING SLASH! + */ + public $applicationDirectory = '../application'; - /* - * --------------------------------------------------------------- - * WRITABLE DIRECTORY NAME - * --------------------------------------------------------------- - * - * This variable must contain the name of your "writable" directory. - * The writable directory allows you to group all directories that - * need write permission to a single place that can be tucked away - * for maximum security, keeping it out of the application and/or - * system directories. - */ - public $writableDirectory = '../writable'; + /* + * --------------------------------------------------------------- + * WRITABLE DIRECTORY NAME + * --------------------------------------------------------------- + * + * This variable must contain the name of your "writable" directory. + * The writable directory allows you to group all directories that + * need write permission to a single place that can be tucked away + * for maximum security, keeping it out of the application and/or + * system directories. + */ + public $writableDirectory = '../writable'; - /* - * --------------------------------------------------------------- - * TESTS DIRECTORY NAME - * --------------------------------------------------------------- - * - * This variable must contain the name of your "tests" directory. - * The writable directory allows you to group all directories that - * need write permission to a single place that can be tucked away - * for maximum security, keeping it out of the application and/or - * system directories. - */ - public $testsDirectory = '../tests'; + /* + * --------------------------------------------------------------- + * TESTS DIRECTORY NAME + * --------------------------------------------------------------- + * + * This variable must contain the name of your "tests" directory. + * The writable directory allows you to group all directories that + * need write permission to a single place that can be tucked away + * for maximum security, keeping it out of the application and/or + * system directories. + */ + public $testsDirectory = '../tests'; - /* - * --------------------------------------------------------------- - * PUBLIC DIRECTORY NAME - * --------------------------------------------------------------- - * - * This variable must contain the name of the directory that - * contains the main index.php front-controller. By default, - * this is the `public` directory, but some hosts may not - * be able to map a primary domain to a sub-directory so you - * can change this to `public_html`, for example, to comply - * with your host's needs. - */ - public $publicDirectory = 'public'; + /* + * --------------------------------------------------------------- + * PUBLIC DIRECTORY NAME + * --------------------------------------------------------------- + * + * This variable must contain the name of the directory that + * contains the main index.php front-controller. By default, + * this is the `public` directory, but some hosts may not + * be able to map a primary domain to a sub-directory so you + * can change this to `public_html`, for example, to comply + * with your host's needs. + */ + public $publicDirectory = 'public'; } diff --git a/application/Config/Routes.php b/application/Config/Routes.php index bbb60524799a..077553d87f0e 100644 --- a/application/Config/Routes.php +++ b/application/Config/Routes.php @@ -25,7 +25,7 @@ // can override as needed. if (file_exists(BASEPATH.'Config/Routes.php')) { - require BASEPATH.'Config/Routes.php'; + require BASEPATH.'Config/Routes.php'; } /** @@ -91,5 +91,5 @@ */ 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/UserAgents.php b/application/Config/UserAgents.php index f016a6e374d3..bec18c5e6952 100644 --- a/application/Config/UserAgents.php +++ b/application/Config/UserAgents.php @@ -4,216 +4,216 @@ class UserAgents extends BaseConfig { - /* - | ------------------------------------------------------------------- - | USER AGENT TYPES - | ------------------------------------------------------------------- - | This file contains four arrays of user agent data. It is used by the - | User Agent Class to help identify browser, platform, robot, and - | mobile device data. The array keys are used to identify the device - | and the array values are used to set the actual name of the item. - */ - public $platforms = [ - 'windows nt 10.0' => 'Windows 10', - 'windows nt 6.3' => 'Windows 8.1', - 'windows nt 6.2' => 'Windows 8', - 'windows nt 6.1' => 'Windows 7', - 'windows nt 6.0' => 'Windows Vista', - 'windows nt 5.2' => 'Windows 2003', - 'windows nt 5.1' => 'Windows XP', - 'windows nt 5.0' => 'Windows 2000', - 'windows nt 4.0' => 'Windows NT 4.0', - 'winnt4.0' => 'Windows NT 4.0', - 'winnt 4.0' => 'Windows NT', - 'winnt' => 'Windows NT', - 'windows 98' => 'Windows 98', - 'win98' => 'Windows 98', - 'windows 95' => 'Windows 95', - 'win95' => 'Windows 95', - 'windows phone' => 'Windows Phone', - 'windows' => 'Unknown Windows OS', - 'android' => 'Android', - 'blackberry' => 'BlackBerry', - 'iphone' => 'iOS', - 'ipad' => 'iOS', - 'ipod' => 'iOS', - 'os x' => 'Mac OS X', - 'ppc mac' => 'Power PC Mac', - 'freebsd' => 'FreeBSD', - 'ppc' => 'Macintosh', - 'linux' => 'Linux', - 'debian' => 'Debian', - 'sunos' => 'Sun Solaris', - 'beos' => 'BeOS', - 'apachebench' => 'ApacheBench', - 'aix' => 'AIX', - 'irix' => 'Irix', - 'osf' => 'DEC OSF', - 'hp-ux' => 'HP-UX', - 'netbsd' => 'NetBSD', - 'bsdi' => 'BSDi', - 'openbsd' => 'OpenBSD', - 'gnu' => 'GNU/Linux', - 'unix' => 'Unknown Unix OS', - 'symbian' => 'Symbian OS', - ]; + /* + | ------------------------------------------------------------------- + | USER AGENT TYPES + | ------------------------------------------------------------------- + | This file contains four arrays of user agent data. It is used by the + | User Agent Class to help identify browser, platform, robot, and + | mobile device data. The array keys are used to identify the device + | and the array values are used to set the actual name of the item. + */ + public $platforms = [ + 'windows nt 10.0' => 'Windows 10', + 'windows nt 6.3' => 'Windows 8.1', + 'windows nt 6.2' => 'Windows 8', + 'windows nt 6.1' => 'Windows 7', + 'windows nt 6.0' => 'Windows Vista', + 'windows nt 5.2' => 'Windows 2003', + 'windows nt 5.1' => 'Windows XP', + 'windows nt 5.0' => 'Windows 2000', + 'windows nt 4.0' => 'Windows NT 4.0', + 'winnt4.0' => 'Windows NT 4.0', + 'winnt 4.0' => 'Windows NT', + 'winnt' => 'Windows NT', + 'windows 98' => 'Windows 98', + 'win98' => 'Windows 98', + 'windows 95' => 'Windows 95', + 'win95' => 'Windows 95', + 'windows phone' => 'Windows Phone', + 'windows' => 'Unknown Windows OS', + 'android' => 'Android', + 'blackberry' => 'BlackBerry', + 'iphone' => 'iOS', + 'ipad' => 'iOS', + 'ipod' => 'iOS', + 'os x' => 'Mac OS X', + 'ppc mac' => 'Power PC Mac', + 'freebsd' => 'FreeBSD', + 'ppc' => 'Macintosh', + 'linux' => 'Linux', + 'debian' => 'Debian', + 'sunos' => 'Sun Solaris', + 'beos' => 'BeOS', + 'apachebench' => 'ApacheBench', + 'aix' => 'AIX', + 'irix' => 'Irix', + 'osf' => 'DEC OSF', + 'hp-ux' => 'HP-UX', + 'netbsd' => 'NetBSD', + 'bsdi' => 'BSDi', + 'openbsd' => 'OpenBSD', + 'gnu' => 'GNU/Linux', + 'unix' => 'Unknown Unix OS', + '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 = [ - 'OPR' => 'Opera', - 'Flock' => 'Flock', - 'Edge' => 'Spartan', - 'Chrome' => 'Chrome', - // Opera 10+ always reports Opera/9.80 and appends Version/ to the user agent string - 'Opera.*?Version' => 'Opera', - 'Opera' => 'Opera', - 'MSIE' => 'Internet Explorer', - 'Internet Explorer' => 'Internet Explorer', - 'Trident.* rv' => 'Internet Explorer', - 'Shiira' => 'Shiira', - 'Firefox' => 'Firefox', - 'Chimera' => 'Chimera', - 'Phoenix' => 'Phoenix', - 'Firebird' => 'Firebird', - 'Camino' => 'Camino', - 'Netscape' => 'Netscape', - 'OmniWeb' => 'OmniWeb', - 'Safari' => 'Safari', - 'Mozilla' => 'Mozilla', - 'Konqueror' => 'Konqueror', - 'icab' => 'iCab', - 'Lynx' => 'Lynx', - 'Links' => 'Links', - 'hotjava' => 'HotJava', - 'amaya' => 'Amaya', - 'IBrowse' => 'IBrowse', - 'Maxthon' => 'Maxthon', - 'Ubuntu' => 'Ubuntu Web Browser', - 'Vivaldi' => 'Vivaldi', - ]; + // 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 = [ + 'OPR' => 'Opera', + 'Flock' => 'Flock', + 'Edge' => 'Spartan', + 'Chrome' => 'Chrome', + // Opera 10+ always reports Opera/9.80 and appends Version/ to the user agent string + 'Opera.*?Version' => 'Opera', + 'Opera' => 'Opera', + 'MSIE' => 'Internet Explorer', + 'Internet Explorer' => 'Internet Explorer', + 'Trident.* rv' => 'Internet Explorer', + 'Shiira' => 'Shiira', + 'Firefox' => 'Firefox', + 'Chimera' => 'Chimera', + 'Phoenix' => 'Phoenix', + 'Firebird' => 'Firebird', + 'Camino' => 'Camino', + 'Netscape' => 'Netscape', + 'OmniWeb' => 'OmniWeb', + 'Safari' => 'Safari', + 'Mozilla' => 'Mozilla', + 'Konqueror' => 'Konqueror', + 'icab' => 'iCab', + 'Lynx' => 'Lynx', + 'Links' => 'Links', + 'hotjava' => 'HotJava', + 'amaya' => 'Amaya', + 'IBrowse' => 'IBrowse', + 'Maxthon' => 'Maxthon', + 'Ubuntu' => 'Ubuntu Web Browser', + 'Vivaldi' => 'Vivaldi', + ]; - public $mobiles = [ - // legacy array, old values commented out - 'mobileexplorer' => 'Mobile Explorer', - // 'openwave' => 'Open Wave', - // 'opera mini' => 'Opera Mini', - // 'operamini' => 'Opera Mini', - // 'elaine' => 'Palm', - 'palmsource' => 'Palm', - // 'digital paths' => 'Palm', - // 'avantgo' => 'Avantgo', - // 'xiino' => 'Xiino', - 'palmscape' => 'Palmscape', - // 'nokia' => 'Nokia', - // 'ericsson' => 'Ericsson', - // 'blackberry' => 'BlackBerry', - // 'motorola' => 'Motorola' + public $mobiles = [ + // legacy array, old values commented out + 'mobileexplorer' => 'Mobile Explorer', + // 'openwave' => 'Open Wave', + // 'opera mini' => 'Opera Mini', + // 'operamini' => 'Opera Mini', + // 'elaine' => 'Palm', + 'palmsource' => 'Palm', + // 'digital paths' => 'Palm', + // 'avantgo' => 'Avantgo', + // 'xiino' => 'Xiino', + 'palmscape' => 'Palmscape', + // 'nokia' => 'Nokia', + // 'ericsson' => 'Ericsson', + // 'blackberry' => 'BlackBerry', + // 'motorola' => 'Motorola' - // Phones and Manufacturers - 'motorola' => 'Motorola', - 'nokia' => 'Nokia', - 'palm' => 'Palm', - 'iphone' => 'Apple iPhone', - 'ipad' => 'iPad', - 'ipod' => 'Apple iPod Touch', - 'sony' => 'Sony Ericsson', - 'ericsson' => 'Sony Ericsson', - 'blackberry' => 'BlackBerry', - 'cocoon' => 'O2 Cocoon', - 'blazer' => 'Treo', - 'lg' => 'LG', - 'amoi' => 'Amoi', - 'xda' => 'XDA', - 'mda' => 'MDA', - 'vario' => 'Vario', - 'htc' => 'HTC', - 'samsung' => 'Samsung', - 'sharp' => 'Sharp', - 'sie-' => 'Siemens', - 'alcatel' => 'Alcatel', - 'benq' => 'BenQ', - 'ipaq' => 'HP iPaq', - 'mot-' => 'Motorola', - 'playstation portable' => 'PlayStation Portable', - 'playstation 3' => 'PlayStation 3', - 'playstation vita' => 'PlayStation Vita', - 'hiptop' => 'Danger Hiptop', - 'nec-' => 'NEC', - 'panasonic' => 'Panasonic', - 'philips' => 'Philips', - 'sagem' => 'Sagem', - 'sanyo' => 'Sanyo', - 'spv' => 'SPV', - 'zte' => 'ZTE', - 'sendo' => 'Sendo', - 'nintendo dsi' => 'Nintendo DSi', - 'nintendo ds' => 'Nintendo DS', - 'nintendo 3ds' => 'Nintendo 3DS', - 'wii' => 'Nintendo Wii', - 'open web' => 'Open Web', - 'openweb' => 'OpenWeb', + // Phones and Manufacturers + 'motorola' => 'Motorola', + 'nokia' => 'Nokia', + 'palm' => 'Palm', + 'iphone' => 'Apple iPhone', + 'ipad' => 'iPad', + 'ipod' => 'Apple iPod Touch', + 'sony' => 'Sony Ericsson', + 'ericsson' => 'Sony Ericsson', + 'blackberry' => 'BlackBerry', + 'cocoon' => 'O2 Cocoon', + 'blazer' => 'Treo', + 'lg' => 'LG', + 'amoi' => 'Amoi', + 'xda' => 'XDA', + 'mda' => 'MDA', + 'vario' => 'Vario', + 'htc' => 'HTC', + 'samsung' => 'Samsung', + 'sharp' => 'Sharp', + 'sie-' => 'Siemens', + 'alcatel' => 'Alcatel', + 'benq' => 'BenQ', + 'ipaq' => 'HP iPaq', + 'mot-' => 'Motorola', + 'playstation portable' => 'PlayStation Portable', + 'playstation 3' => 'PlayStation 3', + 'playstation vita' => 'PlayStation Vita', + 'hiptop' => 'Danger Hiptop', + 'nec-' => 'NEC', + 'panasonic' => 'Panasonic', + 'philips' => 'Philips', + 'sagem' => 'Sagem', + 'sanyo' => 'Sanyo', + 'spv' => 'SPV', + 'zte' => 'ZTE', + 'sendo' => 'Sendo', + 'nintendo dsi' => 'Nintendo DSi', + 'nintendo ds' => 'Nintendo DS', + 'nintendo 3ds' => 'Nintendo 3DS', + 'wii' => 'Nintendo Wii', + 'open web' => 'Open Web', + 'openweb' => 'OpenWeb', - // Operating Systems - 'android' => 'Android', - 'symbian' => 'Symbian', - 'SymbianOS' => 'SymbianOS', - 'elaine' => 'Palm', - 'series60' => 'Symbian S60', - 'windows ce' => 'Windows CE', + // Operating Systems + 'android' => 'Android', + 'symbian' => 'Symbian', + 'SymbianOS' => 'SymbianOS', + 'elaine' => 'Palm', + 'series60' => 'Symbian S60', + 'windows ce' => 'Windows CE', - // Browsers - 'obigo' => 'Obigo', - 'netfront' => 'Netfront Browser', - 'openwave' => 'Openwave Browser', - 'mobilexplorer' => 'Mobile Explorer', - 'operamini' => 'Opera Mini', - 'opera mini' => 'Opera Mini', - 'opera mobi' => 'Opera Mobile', - 'fennec' => 'Firefox Mobile', + // Browsers + 'obigo' => 'Obigo', + 'netfront' => 'Netfront Browser', + 'openwave' => 'Openwave Browser', + 'mobilexplorer' => 'Mobile Explorer', + 'operamini' => 'Opera Mini', + 'opera mini' => 'Opera Mini', + 'opera mobi' => 'Opera Mobile', + 'fennec' => 'Firefox Mobile', - // Other - 'digital paths' => 'Digital Paths', - 'avantgo' => 'AvantGo', - 'xiino' => 'Xiino', - 'novarra' => 'Novarra Transcoder', - 'vodafone' => 'Vodafone', - 'docomo' => 'NTT DoCoMo', - 'o2' => 'O2', + // Other + 'digital paths' => 'Digital Paths', + 'avantgo' => 'AvantGo', + 'xiino' => 'Xiino', + 'novarra' => 'Novarra Transcoder', + 'vodafone' => 'Vodafone', + 'docomo' => 'NTT DoCoMo', + 'o2' => 'O2', - // Fallback - 'mobile' => 'Generic Mobile', - 'wireless' => 'Generic Mobile', - 'j2me' => 'Generic Mobile', - 'midp' => 'Generic Mobile', - 'cldc' => 'Generic Mobile', - 'up.link' => 'Generic Mobile', - 'up.browser' => 'Generic Mobile', - 'smartphone' => 'Generic Mobile', - 'cellphone' => 'Generic Mobile', - ]; + // Fallback + 'mobile' => 'Generic Mobile', + 'wireless' => 'Generic Mobile', + 'j2me' => 'Generic Mobile', + 'midp' => 'Generic Mobile', + 'cldc' => 'Generic Mobile', + 'up.link' => 'Generic Mobile', + 'up.browser' => 'Generic Mobile', + 'smartphone' => 'Generic Mobile', + 'cellphone' => 'Generic Mobile', + ]; - // There are hundreds of bots but these are the most common. - public $robots = [ - 'googlebot' => 'Googlebot', - 'msnbot' => 'MSNBot', - 'baiduspider' => 'Baiduspider', - 'bingbot' => 'Bing', - 'slurp' => 'Inktomi Slurp', - 'yahoo' => 'Yahoo', - 'ask jeeves' => 'Ask Jeeves', - 'fastcrawler' => 'FastCrawler', - 'infoseek' => 'InfoSeek Robot 1.0', - 'lycos' => 'Lycos', - 'yandex' => 'YandexBot', - 'mediapartners-google' => 'MediaPartners Google', - 'CRAZYWEBCRAWLER' => 'Crazy Webcrawler', - 'adsbot-google' => 'AdsBot Google', - 'feedfetcher-google' => 'Feedfetcher Google', - 'curious george' => 'Curious George', - 'ia_archiver' => 'Alexa Crawler', - 'MJ12bot' => 'Majestic-12', - 'Uptimebot' => 'Uptimebot', - ]; + // There are hundreds of bots but these are the most common. + public $robots = [ + 'googlebot' => 'Googlebot', + 'msnbot' => 'MSNBot', + 'baiduspider' => 'Baiduspider', + 'bingbot' => 'Bing', + 'slurp' => 'Inktomi Slurp', + 'yahoo' => 'Yahoo', + 'ask jeeves' => 'Ask Jeeves', + 'fastcrawler' => 'FastCrawler', + 'infoseek' => 'InfoSeek Robot 1.0', + 'lycos' => 'Lycos', + 'yandex' => 'YandexBot', + 'mediapartners-google' => 'MediaPartners Google', + 'CRAZYWEBCRAWLER' => 'Crazy Webcrawler', + 'adsbot-google' => 'AdsBot Google', + 'feedfetcher-google' => 'Feedfetcher Google', + 'curious george' => 'Curious George', + 'ia_archiver' => 'Alexa Crawler', + 'MJ12bot' => 'Majestic-12', + 'Uptimebot' => 'Uptimebot', + ]; } diff --git a/application/Config/Validation.php b/application/Config/Validation.php index 1b45f4e90624..ed4d205ec038 100644 --- a/application/Config/Validation.php +++ b/application/Config/Validation.php @@ -2,35 +2,35 @@ class Validation { - //-------------------------------------------------------------------- - // Setup - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // Setup + //-------------------------------------------------------------------- - /** - * Stores the classes that contain the - * rules that are available. - * - * @var array - */ - public $ruleSets = [ - \CodeIgniter\Validation\Rules::class, - \CodeIgniter\Validation\FormatRules::class, - \CodeIgniter\Validation\FileRules::class, - \CodeIgniter\Validation\CreditCardRules::class, - ]; + /** + * Stores the classes that contain the + * rules that are available. + * + * @var array + */ + public $ruleSets = [ + \CodeIgniter\Validation\Rules::class, + \CodeIgniter\Validation\FormatRules::class, + \CodeIgniter\Validation\FileRules::class, + \CodeIgniter\Validation\CreditCardRules::class, + ]; - /** - * Specifies the views that are used to display the - * errors. - * - * @var array - */ - public $templates = [ - 'list' => 'CodeIgniter\Validation\Views\list', - 'single' => 'CodeIgniter\Validation\Views\single' - ]; + /** + * Specifies the views that are used to display the + * errors. + * + * @var array + */ + public $templates = [ + 'list' => 'CodeIgniter\Validation\Views\list', + 'single' => 'CodeIgniter\Validation\Views\single' + ]; - //-------------------------------------------------------------------- - // Rules - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // Rules + //-------------------------------------------------------------------- } diff --git a/application/Config/View.php b/application/Config/View.php index cacb57a97704..9e8f2a254262 100644 --- a/application/Config/View.php +++ b/application/Config/View.php @@ -2,33 +2,33 @@ class View extends \CodeIgniter\Config\View { - /** - * When false, the view method will clear the data between each - * call. This keeps your data safe and ensures there is no accidental - * leaking between calls, so you would need to explicitly pass the data - * to each view. You might prefer to have the data stick around between - * calls so that it is available to all views. If that is the case, - * set $saveData to true. - */ - public $saveData = true; + /** + * When false, the view method will clear the data between each + * call. This keeps your data safe and ensures there is no accidental + * leaking between calls, so you would need to explicitly pass the data + * to each view. You might prefer to have the data stick around between + * calls so that it is available to all views. If that is the case, + * set $saveData to true. + */ + public $saveData = true; - /** - * Parser Filters map a filter name with any PHP callable. When the - * Parser prepares a variable for display, it will chain it - * through the filters in the order defined, inserting any parameters. - * To prevent potential abuse, all filters MUST be defined here - * in order for them to be available for use within the Parser. - * - * Examples: - * { title|esc(js) } - * { created_on|date(Y-m-d)|esc(attr) } - */ - public $filters = []; + /** + * Parser Filters map a filter name with any PHP callable. When the + * Parser prepares a variable for display, it will chain it + * through the filters in the order defined, inserting any parameters. + * To prevent potential abuse, all filters MUST be defined here + * in order for them to be available for use within the Parser. + * + * Examples: + * { title|esc(js) } + * { created_on|date(Y-m-d)|esc(attr) } + */ + public $filters = []; /** * Parser Plugins provide a way to extend the functionality provided * by the core Parser by creating aliases that will be replaced with * any callable. Can be single or tag pair. */ - public $plugins = []; + public $plugins = []; } diff --git a/application/Controllers/Checks.php b/application/Controllers/Checks.php index 5fbd34cfb412..7db769673498 100644 --- a/application/Controllers/Checks.php +++ b/application/Controllers/Checks.php @@ -18,27 +18,27 @@ */ class Checks extends Controller { - use ResponseTrait; + use ResponseTrait; + + public function index() + { + session()->start(); + } - public function index() - { - session()->start(); - } - public function forge() { echo '

MySQL

'; - + log_message('debug', 'MYSQL TEST'); - + $forge_mysql = \Config\Database::forge(); - + $forge_mysql->getConnection()->query('SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;'); - + $forge_mysql->dropTable('users', true); - + $forge_mysql->getConnection()->query('SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;'); - + $forge_mysql->addField([ 'id' => [ 'type' => 'INTEGER', @@ -52,7 +52,7 @@ public function forge() $forge_mysql->addKey('id', true); $attributes = array('ENGINE' => 'InnoDB'); $forge_mysql->createTable('users', true, $attributes); - + $data_insert = array( 'id' => 1, 'name' => 'User 1', @@ -60,7 +60,7 @@ public function forge() $forge_mysql->getConnection()->table('users')->insert($data_insert); $drop = $forge_mysql->dropTable('invoices', true); - + $forge_mysql->addField([ 'id' => [ 'type' => 'INTEGER', @@ -87,19 +87,19 @@ public function forge() var_dump($forge_mysql->getConnection()->mysqli); }else{ echo '

OK'; - + var_dump($forge_mysql->getConnection()->getForeignKeyData('invoices')); } - + $res = $forge_mysql->dropForeignKey('invoices','invoices_other_id_foreign'); - - + + echo '

PostgreSQL

'; - + $forge_pgsql = \Config\Database::forge('pgsql'); $forge_pgsql->dropTable('users',true, true); - + $forge_pgsql->addField([ 'id' => [ 'type' => 'INTEGER', @@ -113,14 +113,14 @@ public function forge() ]); $forge_pgsql->addKey('id', true); $forge_pgsql->createTable('users', true); - - + + $data_insert = array( 'id' => 1, 'name' => 'User 1', ); $forge_pgsql->getConnection()->table('users')->insert($data_insert); - + $forge_pgsql->dropTable('invoices',true); $forge_pgsql->addField([ 'id' => [ @@ -143,7 +143,7 @@ public function forge() ]); $forge_pgsql->addKey('id', true); - $forge_pgsql->addForeignKey('users_id','users','id','CASCADE','CASCADE'); + $forge_pgsql->addForeignKey('users_id','users','id','CASCADE','CASCADE'); $forge_pgsql->addForeignKey('other_id','users','id'); $res = $forge_pgsql->createTable('invoices', true); @@ -154,134 +154,134 @@ public function forge() echo '

OK'; var_dump($forge_pgsql->getConnection()->getForeignKeyData('invoices')); } - + //$res = $forge_pgsql->dropForeignKey('invoices','invoices_other_id_foreign'); - + } - public function escape() - { - $db = Database::connect(); - $db->initialize(); - - $jobs = $db->table('job') - ->whereNotIn('name', ['Politician', 'Accountant']) - ->get() - ->getResult(); - - die(var_dump($jobs)); - } - - public function password() - { - $db = Database::connect(); - $db->initialize(); - - $result = $db->table('misc') - ->insert([ - 'key' => 'password', - 'value' => '$2y$10$ErQlCj/Mo10il.FthAm0WOjYdf3chZEGPFqaPzjqOX2aj2uYf5Ihq' - ]); - - die(var_dump($result)); - } - - - public function forms() - { - helper('form'); - - var_dump(form_open()); - } - - public function api() - { - $data = [ - "total_users" => 3, - "users" => [ - [ - "id" => 1, - "name" => "Nitya", - "address" => [ - "country" => "India", - "city" => "Kolkata", - "zip" => 700102, - ] - ], - [ - "id" => 2, - "name" => "John", - "address" => [ - "country" => "USA", - "city" => "Newyork", - "zip" => "NY1234", - ] - ], - [ - "id" => 3, - "name" => "Viktor", - "address" => [ - "country" => "Australia", - "city" => "Sydney", - "zip" => 123456, - ] - ], - ] - ]; - - return $this->respond($data); - } - - public function db() - { - $db = Database::connect(); - $db->initialize(); - - $query = $db->prepare(function($db){ - return $db->table('user')->insert([ - 'name' => 'a', - 'email' => 'b@example.com', - 'country' => 'x' - ]); - }); - - $query->execute('foo', 'foo@example.com', 'US'); - } - - public function db2() - { - $db = Database::connect(); - $db->initialize(); - - $db->table('user')->insert([ - 'name' => 'a', - 'email' => 'b@example.com', - 'country' => 'x' - ]); - } - - public function format() - { - echo '
';
-		var_dump($this->response->getHeaderLine('content-type'));
-	}
-
-	public function model()
-	{
-	    $model = new class() extends Model {
-	        protected $table = 'job';
+    public function escape()
+    {
+        $db = Database::connect();
+        $db->initialize();
+
+        $jobs = $db->table('job')
+                         ->whereNotIn('name', ['Politician', 'Accountant'])
+                         ->get()
+                         ->getResult();
+
+        die(var_dump($jobs));
+    }
+
+    public function password()
+    {
+        $db = Database::connect();
+        $db->initialize();
+
+        $result = $db->table('misc')
+                    ->insert([
+                        'key' => 'password',
+                        'value' => '$2y$10$ErQlCj/Mo10il.FthAm0WOjYdf3chZEGPFqaPzjqOX2aj2uYf5Ihq'
+                    ]);
+
+        die(var_dump($result));
+    }
+
+
+    public function forms()
+    {
+        helper('form');
+
+        var_dump(form_open());
+    }
+
+    public function api()
+    {
+        $data = [
+            "total_users" => 3,
+            "users" => [
+                [
+                    "id" => 1,
+                    "name" => "Nitya",
+                    "address" => [
+                        "country" => "India",
+                        "city" => "Kolkata",
+                        "zip" => 700102,
+                    ]
+                ],
+                [
+                    "id" => 2,
+                    "name" => "John",
+                    "address" => [
+                        "country" => "USA",
+                        "city" => "Newyork",
+                        "zip" => "NY1234",
+                    ]
+                ],
+                [
+                    "id" => 3,
+                    "name" => "Viktor",
+                    "address" => [
+                        "country" => "Australia",
+                        "city" => "Sydney",
+                        "zip" => 123456,
+                    ]
+                ],
+            ]
+        ];
+
+        return $this->respond($data);
+    }
+
+    public function db()
+    {
+        $db = Database::connect();
+        $db->initialize();
+
+        $query = $db->prepare(function($db){
+            return $db->table('user')->insert([
+                'name' => 'a',
+                'email' => 'b@example.com',
+                'country' => 'x'
+            ]);
+        });
+
+        $query->execute('foo', 'foo@example.com', 'US');
+    }
+
+    public function db2()
+    {
+        $db = Database::connect();
+        $db->initialize();
+
+        $db->table('user')->insert([
+                'name' => 'a',
+                'email' => 'b@example.com',
+                'country' => 'x'
+            ]);
+    }
+
+    public function format()
+    {
+        echo '
';
+        var_dump($this->response->getHeaderLine('content-type'));
+    }
+
+    public function model()
+    {
+        $model = new class() extends Model {
+            protected $table = 'job';
         };
 
-	    $results = $model->findAll();
+        $results = $model->findAll();
 
-	    $developer = $model->findWhere('name', 'Developer');
+        $developer = $model->findWhere('name', 'Developer');
 
-	    $politician = $model->find(3);
+        $politician = $model->find(3);
 
-	    dd($politician);
+        dd($politician);
 
-	}
+    }
 
     public function curl()
     {
@@ -303,137 +303,137 @@ public function catch()
         echo $body;
     }
 
-	public function redirect()
-	{
-		return redirect('/checks/model');
+    public function redirect()
+    {
+        return redirect('/checks/model');
+    }
+
+    public function image()
+    {
+        $info = Services::image('imagick')
+            ->withFile("/Users/kilishan/Documents/BobHeader.jpg")
+            ->getFile()
+            ->getProperties(true);
+
+        dd(ENVIRONMENT);
+
+        $images = Services::image('imagick')
+            ->getVersion();
+//          ->withFile("/Users/kilishan/Documents/BobHeader.jpg")
+//          ->resize(500, 100, true)
+//          ->crop(200, 75, 20, 0, false)
+//          ->rotate(90)
+//          ->save('/Users/kilishan/temp.jpg');
+
+//      $images = Services::image('imagick')
+//          ->withFile("/Users/kilishan/Documents/BobHeader.jpg")
+//          ->fit(500, 100, 'bottom-left')
+//          ->text('Bob is Back!', [
+//              'fontPath'  => '/Users/kilishan/Downloads/Calibri.ttf',
+//              'fontSize' => 40,
+//              'padding' => 0,
+//              'opacity'   => 0.5,
+//              'vAlign'    => 'top',
+//              'hAlign'    => 'right',
+//              'withShadow' => true,
+//          ])
+//          ->save('/Users/kilishan/temp.jpg', 100);
+
+
+        ddd($images);
+    }
+
+    public function time()
+    {
+        $time = new Time();
+
+        echo($time);
+        echo '
'; + echo Time::now(); + echo '
'; + echo Time::parse('First Monday of December'); + echo '
'; + + $time = new Time('Next Monday'); + die($time); } - public function image() - { - $info = Services::image('imagick') - ->withFile("/Users/kilishan/Documents/BobHeader.jpg") - ->getFile() - ->getProperties(true); - - dd(ENVIRONMENT); - - $images = Services::image('imagick') - ->getVersion(); -// ->withFile("/Users/kilishan/Documents/BobHeader.jpg") -// ->resize(500, 100, true) -// ->crop(200, 75, 20, 0, false) -// ->rotate(90) -// ->save('/Users/kilishan/temp.jpg'); - -// $images = Services::image('imagick') -// ->withFile("/Users/kilishan/Documents/BobHeader.jpg") -// ->fit(500, 100, 'bottom-left') -// ->text('Bob is Back!', [ -// 'fontPath' => '/Users/kilishan/Downloads/Calibri.ttf', -// 'fontSize' => 40, -// 'padding' => 0, -// 'opacity' => 0.5, -// 'vAlign' => 'top', -// 'hAlign' => 'right', -// 'withShadow' => true, -// ]) -// ->save('/Users/kilishan/temp.jpg', 100); - - - ddd($images); - } - - public function time() - { - $time = new Time(); - - echo($time); - echo '
'; - echo Time::now(); - echo '
'; - echo Time::parse('First Monday of December'); - echo '
'; - - $time = new Time('Next Monday'); - die($time); - } - - public function csp() - { -// $this->response->CSP->reportOnly(true); - $this->response->CSP->setDefaultSrc(base_url()); - $this->response->CSP->addStyleSrc('unsafe-inline'); - $this->response->CSP->addStyleSrc('https://maxcdn.bootstrapcdn.com'); - - echo <<response->CSP->reportOnly(true); + $this->response->CSP->setDefaultSrc(base_url()); + $this->response->CSP->addStyleSrc('unsafe-inline'); + $this->response->CSP->addStyleSrc('https://maxcdn.bootstrapcdn.com'); + + echo << - + EOF; - } - - public function upload() - { - if ($this->request->getMethod() == 'post') - { - $this->validate([ - 'avatar' => 'uploaded[avatar]|ext_in[avatar,png,jpg,jpeg,gif]' - ]); - - /** - * @var \CodeIgniter\HTTP\Files\UploadedFile - */ - $file = $this->request->getFile('avatar'); - - echo "Name: {$file->getName()}
"; - echo "Temp Name: {$file->getTempName()}
"; - echo "Original Name: {$file->getClientName()}
"; - echo "Random Name: {$file->getRandomName()}
"; - echo "Extension: {$file->getExtension()}
"; - echo "Client Extension: {$file->getClientExtension()}
"; - echo "Guessed Extension: {$file->guessExtension()}
"; - echo "MimeType: {$file->getMimeType()}
"; - echo "IsValid: {$file->isValid()}
"; - echo "Size (b): {$file->getSize()}
"; - echo "Size (kb): {$file->getSize('kb')}
"; - echo "Size (mb): {$file->getSize('mb')}
"; - echo "Size (mb): {$file->getSize('mb')}
"; - echo "Path: {$file->getPath()}
"; - echo "RealPath: {$file->getRealPath()}
"; - echo "Filename: {$file->getFilename()}
"; - echo "Basename: {$file->getBasename()}
"; - echo "Pathname: {$file->getPathname()}
"; - echo "Permissions: {$file->getPerms()}
"; - echo "Inode: {$file->getInode()}
"; - echo "Owner: {$file->getOwner()}
"; - echo "Group: {$file->getGroup()}
"; - echo "ATime: {$file->getATime()}
"; - echo "MTime: {$file->getMTime()}
"; - echo "CTime: {$file->getCTime()}
"; - - dd($file); - } - - echo <<request->getMethod() == 'post') + { + $this->validate([ + 'avatar' => 'uploaded[avatar]|ext_in[avatar,png,jpg,jpeg,gif]' + ]); + + /** + * @var \CodeIgniter\HTTP\Files\UploadedFile + */ + $file = $this->request->getFile('avatar'); + + echo "Name: {$file->getName()}
"; + echo "Temp Name: {$file->getTempName()}
"; + echo "Original Name: {$file->getClientName()}
"; + echo "Random Name: {$file->getRandomName()}
"; + echo "Extension: {$file->getExtension()}
"; + echo "Client Extension: {$file->getClientExtension()}
"; + echo "Guessed Extension: {$file->guessExtension()}
"; + echo "MimeType: {$file->getMimeType()}
"; + echo "IsValid: {$file->isValid()}
"; + echo "Size (b): {$file->getSize()}
"; + echo "Size (kb): {$file->getSize('kb')}
"; + echo "Size (mb): {$file->getSize('mb')}
"; + echo "Size (mb): {$file->getSize('mb')}
"; + echo "Path: {$file->getPath()}
"; + echo "RealPath: {$file->getRealPath()}
"; + echo "Filename: {$file->getFilename()}
"; + echo "Basename: {$file->getBasename()}
"; + echo "Pathname: {$file->getPathname()}
"; + echo "Permissions: {$file->getPerms()}
"; + echo "Inode: {$file->getInode()}
"; + echo "Owner: {$file->getOwner()}
"; + echo "Group: {$file->getGroup()}
"; + echo "ATime: {$file->getATime()}
"; + echo "MTime: {$file->getMTime()}
"; + echo "CTime: {$file->getCTime()}
"; + + dd($file); + } + + echo <<
- + - +
@@ -442,16 +442,16 @@ public function upload() EOF; ; - } + } - public function parser() - { - $this->parser = Services::parser(); - } + public function parser() + { + $this->parser = Services::parser(); + } - public function error() - { - throw new \RuntimeException('Oops!', 403); - } + public function error() + { + throw new \RuntimeException('Oops!', 403); + } } diff --git a/application/Controllers/Home.php b/application/Controllers/Home.php index 84b713505627..907ab5534325 100644 --- a/application/Controllers/Home.php +++ b/application/Controllers/Home.php @@ -4,11 +4,11 @@ class Home extends Controller { - public function index() - { - return view('welcome_message'); - } + public function index() + { + return view('welcome_message'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Filters/CSRF.php b/application/Filters/CSRF.php index 46f1582300a8..daead0216120 100644 --- a/application/Filters/CSRF.php +++ b/application/Filters/CSRF.php @@ -7,45 +7,45 @@ class CSRF implements FilterInterface { - /** - * Do whatever processing this filter needs to do. - * By default it should not return anything during - * normal execution. However, when an abnormal state - * is found, it should return an instance of - * CodeIgniter\HTTP\Response. If it does, script - * execution will end and that Response will be - * sent back to the client, allowing for error pages, - * redirects, etc. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * - * @return mixed - */ - public function before(RequestInterface $request) - { - if ($request->isCLI()) - { - return; - } + /** + * Do whatever processing this filter needs to do. + * By default it should not return anything during + * normal execution. However, when an abnormal state + * is found, it should return an instance of + * CodeIgniter\HTTP\Response. If it does, script + * execution will end and that Response will be + * sent back to the client, allowing for error pages, + * redirects, etc. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * + * @return mixed + */ + public function before(RequestInterface $request) + { + if ($request->isCLI()) + { + return; + } - $security = Services::security(); + $security = Services::security(); - $security->CSRFVerify($request); - } + $security->CSRFVerify($request); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * We don't have anything to do here. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response - * - * @return mixed - */ - public function after(RequestInterface $request, ResponseInterface $response) - { - } + /** + * We don't have anything to do here. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * + * @return mixed + */ + public function after(RequestInterface $request, ResponseInterface $response) + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Filters/DebugToolbar.php b/application/Filters/DebugToolbar.php index 945108013c47..bbeca2c187b1 100644 --- a/application/Filters/DebugToolbar.php +++ b/application/Filters/DebugToolbar.php @@ -8,84 +8,84 @@ class DebugToolbar implements FilterInterface { - /** - * We don't need to do anything here. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * - * @return mixed - */ - public function before(RequestInterface $request) - { - - } - - //-------------------------------------------------------------------- - - /** - * If the debug flag is set (CI_DEBUG) then collect performance - * and debug information and display it in a toolbar. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response - * - * @return mixed - */ - public function after(RequestInterface $request, ResponseInterface $response) - { - if ( ! is_cli() && CI_DEBUG) - { - global $app; - - $toolbar = Services::toolbar(new App()); - $stats = $app->getPerformanceStats(); - $data = $toolbar->run( - $stats['startTime'], - $stats['totalTime'], - $stats['startMemory'], - $request, - $response - ); - - helper('filesystem'); - - // Updated to time() so we can get history - $time = time(); - - if (! is_dir(WRITEPATH.'debugbar')) - { - mkdir(WRITEPATH.'debugbar', 0777); - } - - write_file(WRITEPATH .'debugbar/'.'debugbar_' . $time, $data, 'w+'); - - $format = $response->getHeaderLine('content-type'); - - // Non-HTML formats should not include the debugbar - // then we send headers saying where to find the debug data - // for this response - if ($request->isAJAX() || strpos($format, 'html') === false) - { - return $response->setHeader('Debugbar-Time', (string)$time) - ->setHeader('Debugbar-Link', site_url("?debugbar_time={$time}")) - ->getBody(); - } - - $script = PHP_EOL - . '' - . PHP_EOL; - - if (strpos($response->getBody(), '') !== false) - { - return $response->setBody(str_replace('', $script . '', - $response->getBody())); - } - - return $response->appendBody($script); - } - } - - //-------------------------------------------------------------------- + /** + * We don't need to do anything here. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * + * @return mixed + */ + public function before(RequestInterface $request) + { + + } + + //-------------------------------------------------------------------- + + /** + * If the debug flag is set (CI_DEBUG) then collect performance + * and debug information and display it in a toolbar. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * + * @return mixed + */ + public function after(RequestInterface $request, ResponseInterface $response) + { + if ( ! is_cli() && CI_DEBUG) + { + global $app; + + $toolbar = Services::toolbar(new App()); + $stats = $app->getPerformanceStats(); + $data = $toolbar->run( + $stats['startTime'], + $stats['totalTime'], + $stats['startMemory'], + $request, + $response + ); + + helper('filesystem'); + + // Updated to time() so we can get history + $time = time(); + + if (! is_dir(WRITEPATH.'debugbar')) + { + mkdir(WRITEPATH.'debugbar', 0777); + } + + write_file(WRITEPATH .'debugbar/'.'debugbar_' . $time, $data, 'w+'); + + $format = $response->getHeaderLine('content-type'); + + // Non-HTML formats should not include the debugbar + // then we send headers saying where to find the debug data + // for this response + if ($request->isAJAX() || strpos($format, 'html') === false) + { + return $response->setHeader('Debugbar-Time', (string)$time) + ->setHeader('Debugbar-Link', site_url("?debugbar_time={$time}")) + ->getBody(); + } + + $script = PHP_EOL + . '' + . PHP_EOL; + + if (strpos($response->getBody(), '') !== false) + { + return $response->setBody(str_replace('', $script . '', + $response->getBody())); + } + + return $response->appendBody($script); + } + } + + //-------------------------------------------------------------------- } diff --git a/application/Filters/Throttle.php b/application/Filters/Throttle.php index 02dda6032495..5cac7f9672ad 100644 --- a/application/Filters/Throttle.php +++ b/application/Filters/Throttle.php @@ -7,40 +7,40 @@ class Throttle implements FilterInterface { - /** - * This is a demo implementation of using the Throttler class - * to implement rate limiting for your application. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * - * @return mixed - */ - public function before(RequestInterface $request) - { - $throttler = Services::throttler(); + /** + * This is a demo implementation of using the Throttler class + * to implement rate limiting for your application. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * + * @return mixed + */ + public function before(RequestInterface $request) + { + $throttler = Services::throttler(); - // Restrict an IP address to no more - // than 1 request per second across the - // entire site. - if ($throttler->check($request->getIPAddress(), 60, MINUTE) === false) - { - return Services::response()->setStatusCode(429); - } - } + // Restrict an IP address to no more + // than 1 request per second across the + // entire site. + if ($throttler->check($request->getIPAddress(), 60, MINUTE) === false) + { + return Services::response()->setStatusCode(429); + } + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * We don't have anything to do here. - * - * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request - * @param ResponseInterface|\CodeIgniter\HTTP\Response $response - * - * @return mixed - */ - public function after(RequestInterface $request, ResponseInterface $response) - { - } + /** + * We don't have anything to do here. + * + * @param RequestInterface|\CodeIgniter\HTTP\IncomingRequest $request + * @param ResponseInterface|\CodeIgniter\HTTP\Response $response + * + * @return mixed + */ + public function after(RequestInterface $request, ResponseInterface $response) + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/application/Views/errors/cli/error_exception.php b/application/Views/errors/cli/error_exception.php index 43f3d6e42f7d..9f133efed8ff 100644 --- a/application/Views/errors/cli/error_exception.php +++ b/application/Views/errors/cli/error_exception.php @@ -9,11 +9,11 @@ - Backtrace: - getTrace() as $error): ?> - + Backtrace: + getTrace() as $error): ?> + - - + + diff --git a/application/Views/errors/html/error_404.php b/application/Views/errors/html/error_404.php index 47f238c96339..bff6bcd71776 100644 --- a/application/Views/errors/html/error_404.php +++ b/application/Views/errors/html/error_404.php @@ -3,84 +3,84 @@ ?> - - 404 Page Not Found + + 404 Page Not Found - -
-

404 - File Not Found

+
+

404 - File Not Found

-

- - - - Sorry! Cannot seem to find the page you were looking for. - -

-
+

+ + + + Sorry! Cannot seem to find the page you were looking for. + +

+
diff --git a/application/Views/errors/html/error_exception.php b/application/Views/errors/html/error_exception.php index 978e92c3bcf0..3a2c08cbee28 100644 --- a/application/Views/errors/html/error_exception.php +++ b/application/Views/errors/html/error_exception.php @@ -2,388 +2,388 @@ - - + + - <?= htmlspecialchars($title, ENT_SUBSTITUTE, 'UTF-8') ?> - + <?= htmlspecialchars($title, ENT_SUBSTITUTE, 'UTF-8') ?> + - + - -
-
-

getCode() ? ' #'.$exception->getCode() : '') ?>

-

- getMessage() ?> - getMessage())) ?>" - rel="noreferrer" target="_blank">search → -

-
-
- - -
-

at line

- - -
- -
- -
- -
- - - -
- - -
- -
    - $row) : ?> - -
  1. -

    - - - - - {PHP internal code} - - - - -   —   - - - ( arguments ) -

    - - - getParameters(); - } - foreach ($row['args'] as $key => $value) : ?> - - - - - - -
    name : "#$key", ENT_SUBSTITUTE, 'UTF-8') ?>
    -
    - - () - - - - -   —   () - -

    - - - -
    - -
    - -
  2. - - -
- -
- - -
- - - -

$

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - - '.print_r($value, true) ?> - -
- - - - - - -

Constants

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - - '.print_r($value, true) ?> - -
- -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pathuri ?>
HTTP MethodgetMethod(true) ?>
IP AddressgetIPAddress() ?>
Is AJAX Request?isAJAX() ? 'yes' : 'no' ?>
Is CLI Request?isCLI() ? 'yes' : 'no' ?>
Is Secure Request?isSecure() ? 'yes' : 'no' ?>
User AgentgetUserAgent()->getAgentString() ?>
- - - - - - - - -

$

- - - - - - - - - - $value) : ?> - - - - - - -
KeyValue
- - - - '.print_r($value, true) ?> - -
- - - - - -
- No $_GET, $_POST, or $_COOKIE Information to show. -
- - - - getHeaders(); ?> - - -

Headers

- - - - - - - - - - $value) : ?> - - - - - - - - - - -
HeaderValue
getName(), 'html') ?>getValueLine(), 'html') ?>
- - -
- - - setStatusCode(http_response_code()); - ?> -
- - - - - -
Response StatusgetStatusCode().' - '.$response->getReason() ?>
- - getHeaders(); ?> - - - -

Headers

- - - - - - - - - - $value) : ?> - - - - - - -
HeaderValue
getHeaderLine($name), 'html') ?>
- - -
- - -
- - -
    - -
  1. - -
-
- - -
- - - - - - - - - - - - - - - - -
Memory Usage
Peak Memory Usage:
Memory Limit:
- -
- -
- -
- - + +
+
+

getCode() ? ' #'.$exception->getCode() : '') ?>

+

+ getMessage() ?> + getMessage())) ?>" + rel="noreferrer" target="_blank">search → +

+
+
+ + +
+

at line

+ + +
+ +
+ +
+ +
+ + + +
+ + +
+ +
    + $row) : ?> + +
  1. +

    + + + + + {PHP internal code} + + + + +   —   + + + ( arguments ) +

    + + + getParameters(); + } + foreach ($row['args'] as $key => $value) : ?> + + + + + + +
    name : "#$key", ENT_SUBSTITUTE, 'UTF-8') ?>
    +
    + + () + + + + +   —   () + +

    + + + +
    + +
    + +
  2. + + +
+ +
+ + +
+ + + +

$

+ + + + + + + + + + $value) : ?> + + + + + + +
KeyValue
+ + + + '.print_r($value, true) ?> + +
+ + + + + + +

Constants

+ + + + + + + + + + $value) : ?> + + + + + + +
KeyValue
+ + + + '.print_r($value, true) ?> + +
+ +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pathuri ?>
HTTP MethodgetMethod(true) ?>
IP AddressgetIPAddress() ?>
Is AJAX Request?isAJAX() ? 'yes' : 'no' ?>
Is CLI Request?isCLI() ? 'yes' : 'no' ?>
Is Secure Request?isSecure() ? 'yes' : 'no' ?>
User AgentgetUserAgent()->getAgentString() ?>
+ + + + + + + + +

$

+ + + + + + + + + + $value) : ?> + + + + + + +
KeyValue
+ + + + '.print_r($value, true) ?> + +
+ + + + + +
+ No $_GET, $_POST, or $_COOKIE Information to show. +
+ + + + getHeaders(); ?> + + +

Headers

+ + + + + + + + + + $value) : ?> + + + + + + + + + + +
HeaderValue
getName(), 'html') ?>getValueLine(), 'html') ?>
+ + +
+ + + setStatusCode(http_response_code()); + ?> +
+ + + + + +
Response StatusgetStatusCode().' - '.$response->getReason() ?>
+ + getHeaders(); ?> + + + +

Headers

+ + + + + + + + + + $value) : ?> + + + + + + +
HeaderValue
getHeaderLine($name), 'html') ?>
+ + +
+ + +
+ + +
    + +
  1. + +
+
+ + +
+ + + + + + + + + + + + + + + + +
Memory Usage
Peak Memory Usage:
Memory Limit:
+ +
+ +
+ +
+ + diff --git a/application/Views/errors/html/production.php b/application/Views/errors/html/production.php index b912a0152c44..32767e497a81 100644 --- a/application/Views/errors/html/production.php +++ b/application/Views/errors/html/production.php @@ -1,24 +1,24 @@ - - + + - Whoops! + Whoops! - + -
+
-

Whoops!

+

Whoops!

-

We seem to have hit a snag. Please try again later...

+

We seem to have hit a snag. Please try again later...

-
+
diff --git a/application/Views/form.php b/application/Views/form.php index 5f7ad8ff97e4..23f992619777 100644 --- a/application/Views/form.php +++ b/application/Views/form.php @@ -3,7 +3,7 @@
- - - -
\ No newline at end of file + + + + diff --git a/application/Views/welcome_message.php b/application/Views/welcome_message.php index e8a576817d81..e20a09223bcc 100644 --- a/application/Views/welcome_message.php +++ b/application/Views/welcome_message.php @@ -1,139 +1,139 @@ - - Welcome to CodeIgniter - - - - - - - -
- -

Welcome to CodeIgniter

- -

version

- - - -
-

The page you are looking at is being generated dynamically by CodeIgniter.

- -

If you would like to edit this page you'll find it located at:

- -
-				
-					application/Views/welcome_message.php
-				
-				
- -

The corresponding controller for this page is found at:

- -
-				
-					application/Controllers/Home.php
-				
-				
- -

If you are exploring CodeIgniter for the very first time, you - should start by reading the (in progress) - User Guide.

- -
- - - -
- - + + Welcome to CodeIgniter + + + + + + + +
+ +

Welcome to CodeIgniter

+ +

version

+ + + +
+

The page you are looking at is being generated dynamically by CodeIgniter.

+ +

If you would like to edit this page you'll find it located at:

+ +
+                
+                    application/Views/welcome_message.php
+                
+                
+ +

The corresponding controller for this page is found at:

+ +
+                
+                    application/Controllers/Home.php
+                
+                
+ +

If you are exploring CodeIgniter for the very first time, you + should start by reading the (in progress) + User Guide.

+ +
+ + + +
+ + diff --git a/tests/_support/Autoloader/MockAutoloader.php b/tests/_support/Autoloader/MockAutoloader.php index a9b1fe097829..4510b214d6af 100644 --- a/tests/_support/Autoloader/MockAutoloader.php +++ b/tests/_support/Autoloader/MockAutoloader.php @@ -3,21 +3,21 @@ class MockAutoloader extends Autoloader { - protected $files = []; + protected $files = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setFiles($files) - { - $this->files = $files; - } + public function setFiles($files) + { + $this->files = $files; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - protected function requireFile($file) - { - return in_array($file, $this->files) ? $file : false; - } + protected function requireFile($file) + { + return in_array($file, $this->files) ? $file : false; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/Autoloader/MockFileLocator.php b/tests/_support/Autoloader/MockFileLocator.php index 00d2dbda6070..9e3bd8fe99e1 100644 --- a/tests/_support/Autoloader/MockFileLocator.php +++ b/tests/_support/Autoloader/MockFileLocator.php @@ -3,21 +3,21 @@ class MockFileLocator extends FileLocator { - protected $files = []; + protected $files = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setFiles($files) - { - $this->files = $files; - } + public function setFiles($files) + { + $this->files = $files; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - protected function requireFile(string $file): bool - { - return in_array($file, $this->files) ? $file : false; - } + protected function requireFile(string $file): bool + { + return in_array($file, $this->files) ? $file : false; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/CIDatabaseTestCase.php b/tests/_support/CIDatabaseTestCase.php index b3f1b729e4e8..1fc722b44d61 100644 --- a/tests/_support/CIDatabaseTestCase.php +++ b/tests/_support/CIDatabaseTestCase.php @@ -4,5 +4,5 @@ class CIDatabaseTestCase extends Test\CIDatabaseTestCase { - + } diff --git a/tests/_support/CIUnitTestCase.php b/tests/_support/CIUnitTestCase.php index 551d7eb57504..b475b62eca3e 100644 --- a/tests/_support/CIUnitTestCase.php +++ b/tests/_support/CIUnitTestCase.php @@ -4,5 +4,5 @@ class CIUnitTestCase extends Test\CIUnitTestCase { - + } diff --git a/tests/_support/Cache/Handlers/MockHandler.php b/tests/_support/Cache/Handlers/MockHandler.php index ddd3c3b53619..aacb16c57695 100644 --- a/tests/_support/Cache/Handlers/MockHandler.php +++ b/tests/_support/Cache/Handlers/MockHandler.php @@ -4,194 +4,194 @@ class MockHandler implements CacheInterface { - /** - * Prefixed to all cache names. - * - * @var string - */ - protected $prefix; - - /** - * Mock cache storage. - * @var array - */ - protected $cache = []; - - //-------------------------------------------------------------------- - - /** - * Takes care of any handler-specific setup that must be done. - */ - public function initialize() - { - // Not to see here... - } - - //-------------------------------------------------------------------- - - /** - * Attempts to fetch an item from the cache store. - * - * @param string $key Cache item name - * - * @return mixed - */ - public function get(string $key) - { - $key = $this->prefix.$key; - - return array_key_exists($key, $this->cache) - ? $this->cache[$key] - : false; - } - - //-------------------------------------------------------------------- - - /** - * Saves an item to the cache store. - * - * The $raw parameter is only utilized by Mamcache in order to - * allow usage of increment() and decrement(). - * - * @param string $key Cache item name - * @param $value the data to save - * @param null $ttl Time To Live, in seconds (default 60) - * @param bool $raw Whether to store the raw value. - * - * @return mixed - */ - public function save(string $key, $value, int $ttl = 60, bool $raw = false) - { - $key = $this->prefix.$key; - - $this->cache[$key] = $value; - - return true; - } - - //-------------------------------------------------------------------- - - /** - * Deletes a specific item from the cache store. - * - * @param string $key Cache item name - * - * @return mixed - */ - public function delete(string $key) - { - unset($this->cache[$key]); - } - - //-------------------------------------------------------------------- - - /** - * Performs atomic incrementation of a raw stored value. - * - * @param string $key Cache ID - * @param int $offset Step/value to increase by - * - * @return mixed - */ - public function increment(string $key, int $offset = 1) - { - $key = $this->prefix.$key; - - $data = $this->cache[$key] ?: null; - - if (empty($data)) - { - $data = 0; - } - elseif (! is_int($data)) - { - return false; - } - - return $this->save($key, $data+$offset); - } - - //-------------------------------------------------------------------- - - /** - * Performs atomic decrementation of a raw stored value. - * - * @param string $key Cache ID - * @param int $offset Step/value to increase by - * - * @return mixed - */ - public function decrement(string $key, int $offset = 1) - { - $key = $this->prefix.$key; - - $data = $this->cache[$key] ?: null; - - if (empty($data)) - { - $data = 0; - } - elseif (! is_int($data)) - { - return false; - } - - return $this->save($key, $data-$offset); - } - - //-------------------------------------------------------------------- - - /** - * Will delete all items in the entire cache. - * - * @return mixed - */ - public function clean() - { - $this->cache = []; - } - - //-------------------------------------------------------------------- - - /** - * Returns information on the entire cache. - * - * The information returned and the structure of the data - * varies depending on the handler. - * - * @return mixed - */ - public function getCacheInfo() - { - return []; - } - - //-------------------------------------------------------------------- - - /** - * Returns detailed information about the specific item in the cache. - * - * @param string $key Cache item name. - * - * @return mixed - */ - public function getMetaData(string $key) - { - return false; - } - - //-------------------------------------------------------------------- - - /** - * Determines if the driver is supported on this system. - * - * @return boolean - */ - public function isSupported(): bool - { - return true; - } - - //-------------------------------------------------------------------- + /** + * Prefixed to all cache names. + * + * @var string + */ + protected $prefix; + + /** + * Mock cache storage. + * @var array + */ + protected $cache = []; + + //-------------------------------------------------------------------- + + /** + * Takes care of any handler-specific setup that must be done. + */ + public function initialize() + { + // Not to see here... + } + + //-------------------------------------------------------------------- + + /** + * Attempts to fetch an item from the cache store. + * + * @param string $key Cache item name + * + * @return mixed + */ + public function get(string $key) + { + $key = $this->prefix.$key; + + return array_key_exists($key, $this->cache) + ? $this->cache[$key] + : false; + } + + //-------------------------------------------------------------------- + + /** + * Saves an item to the cache store. + * + * The $raw parameter is only utilized by Mamcache in order to + * allow usage of increment() and decrement(). + * + * @param string $key Cache item name + * @param $value the data to save + * @param null $ttl Time To Live, in seconds (default 60) + * @param bool $raw Whether to store the raw value. + * + * @return mixed + */ + public function save(string $key, $value, int $ttl = 60, bool $raw = false) + { + $key = $this->prefix.$key; + + $this->cache[$key] = $value; + + return true; + } + + //-------------------------------------------------------------------- + + /** + * Deletes a specific item from the cache store. + * + * @param string $key Cache item name + * + * @return mixed + */ + public function delete(string $key) + { + unset($this->cache[$key]); + } + + //-------------------------------------------------------------------- + + /** + * Performs atomic incrementation of a raw stored value. + * + * @param string $key Cache ID + * @param int $offset Step/value to increase by + * + * @return mixed + */ + public function increment(string $key, int $offset = 1) + { + $key = $this->prefix.$key; + + $data = $this->cache[$key] ?: null; + + if (empty($data)) + { + $data = 0; + } + elseif (! is_int($data)) + { + return false; + } + + return $this->save($key, $data+$offset); + } + + //-------------------------------------------------------------------- + + /** + * Performs atomic decrementation of a raw stored value. + * + * @param string $key Cache ID + * @param int $offset Step/value to increase by + * + * @return mixed + */ + public function decrement(string $key, int $offset = 1) + { + $key = $this->prefix.$key; + + $data = $this->cache[$key] ?: null; + + if (empty($data)) + { + $data = 0; + } + elseif (! is_int($data)) + { + return false; + } + + return $this->save($key, $data-$offset); + } + + //-------------------------------------------------------------------- + + /** + * Will delete all items in the entire cache. + * + * @return mixed + */ + public function clean() + { + $this->cache = []; + } + + //-------------------------------------------------------------------- + + /** + * Returns information on the entire cache. + * + * The information returned and the structure of the data + * varies depending on the handler. + * + * @return mixed + */ + public function getCacheInfo() + { + return []; + } + + //-------------------------------------------------------------------- + + /** + * Returns detailed information about the specific item in the cache. + * + * @param string $key Cache item name. + * + * @return mixed + */ + public function getMetaData(string $key) + { + return false; + } + + //-------------------------------------------------------------------- + + /** + * Determines if the driver is supported on this system. + * + * @return boolean + */ + public function isSupported(): bool + { + return true; + } + + //-------------------------------------------------------------------- } diff --git a/tests/_support/Config/BadRegistrar.php b/tests/_support/Config/BadRegistrar.php index 3ac14fe72cde..650f1df8af4c 100644 --- a/tests/_support/Config/BadRegistrar.php +++ b/tests/_support/Config/BadRegistrar.php @@ -9,9 +9,9 @@ class BadRegistrar { - public static function RegistrarConfig2() - { - return 'I am not worthy'; - } + public static function RegistrarConfig2() + { + return 'I am not worthy'; + } } diff --git a/tests/_support/Config/MockAppConfig.php b/tests/_support/Config/MockAppConfig.php index 6d01e02e2567..85cf63d26209 100644 --- a/tests/_support/Config/MockAppConfig.php +++ b/tests/_support/Config/MockAppConfig.php @@ -2,28 +2,28 @@ class MockAppConfig { - public $baseURL = 'http://example.com'; + public $baseURL = 'http://example.com'; - public $uriProtocol = 'REQUEST_URI'; + public $uriProtocol = 'REQUEST_URI'; - public $cookiePrefix = ''; - public $cookieDomain = ''; - public $cookiePath = '/'; - public $cookieSecure = false; - public $cookieHTTPOnly = false; + public $cookiePrefix = ''; + public $cookieDomain = ''; + public $cookiePath = '/'; + public $cookieSecure = false; + public $cookieHTTPOnly = false; - public $proxyIPs = ''; + public $proxyIPs = ''; - public $CSRFProtection = false; - public $CSRFTokenName = 'csrf_test_name'; - public $CSRFCookieName = 'csrf_cookie_name'; - public $CSRFExpire = 7200; - public $CSRFRegenerate = true; - public $CSRFExcludeURIs = ['http://example.com']; + public $CSRFProtection = false; + public $CSRFTokenName = 'csrf_test_name'; + public $CSRFCookieName = 'csrf_cookie_name'; + public $CSRFExpire = 7200; + public $CSRFRegenerate = true; + public $CSRFExcludeURIs = ['http://example.com']; - public $CSPEnabled = false; + public $CSPEnabled = false; - public $defaultLocale = 'en'; - public $negotiateLocale = false; - public $supportedLocales = ['en', 'es']; + public $defaultLocale = 'en'; + public $negotiateLocale = false; + public $supportedLocales = ['en', 'es']; } diff --git a/tests/_support/Config/MockAutoload.php b/tests/_support/Config/MockAutoload.php index 3954a3825771..f795970fc5fd 100644 --- a/tests/_support/Config/MockAutoload.php +++ b/tests/_support/Config/MockAutoload.php @@ -2,18 +2,18 @@ class MockAutoload extends Autoload { - public $psr4 = []; + public $psr4 = []; - public $classmap = []; + public $classmap = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function __construct() - { - // Don't call the parent since we don't want the default mappings. - // parent::__construct(); - } + public function __construct() + { + // Don't call the parent since we don't want the default mappings. + // parent::__construct(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/Config/MockLogger.php b/tests/_support/Config/MockLogger.php index f7e03d289001..7f63adf12f12 100644 --- a/tests/_support/Config/MockLogger.php +++ b/tests/_support/Config/MockLogger.php @@ -3,95 +3,95 @@ class MockLogger { - /* - |-------------------------------------------------------------------------- - | Error Logging Threshold - |-------------------------------------------------------------------------- - | - | You can enable error logging by setting a threshold over zero. The - | threshold determines what gets logged. Any values below or equal to the - | threshold will be logged. Threshold options are: - | - | 0 = Disables logging, Error logging TURNED OFF - | 1 = Emergency Messages - System is unusable - | 2 = Alert Messages - Action Must Be Taken Immediately - | 3 = Critical Messages - Application component unavailable, unexpected exception. - | 4 = Runtime Errors - Don't need immediate action, but should be monitored. - | 5 = Warnings - Exceptional occurrences that are not errors. - | 6 = Notices - Normal but significant events. - | 7 = Info - Interesting events, like user logging in, etc. - | 8 = Debug - Detailed debug information. - | 9 = All Messages - | - | You can also pass an array with threshold levels to show individual error types - | - | array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages - | - | For a live site you'll usually enable Critical or higher (3) to be logged otherwise - | your log files will fill up very fast. - | - */ - public $threshold = 9; + /* + |-------------------------------------------------------------------------- + | Error Logging Threshold + |-------------------------------------------------------------------------- + | + | You can enable error logging by setting a threshold over zero. The + | threshold determines what gets logged. Any values below or equal to the + | threshold will be logged. Threshold options are: + | + | 0 = Disables logging, Error logging TURNED OFF + | 1 = Emergency Messages - System is unusable + | 2 = Alert Messages - Action Must Be Taken Immediately + | 3 = Critical Messages - Application component unavailable, unexpected exception. + | 4 = Runtime Errors - Don't need immediate action, but should be monitored. + | 5 = Warnings - Exceptional occurrences that are not errors. + | 6 = Notices - Normal but significant events. + | 7 = Info - Interesting events, like user logging in, etc. + | 8 = Debug - Detailed debug information. + | 9 = All Messages + | + | You can also pass an array with threshold levels to show individual error types + | + | array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages + | + | For a live site you'll usually enable Critical or higher (3) to be logged otherwise + | your log files will fill up very fast. + | + */ + public $threshold = 9; - /* - |-------------------------------------------------------------------------- - | Error Logging Directory Path - |-------------------------------------------------------------------------- - | - | - | - */ - public $path = ''; + /* + |-------------------------------------------------------------------------- + | Error Logging Directory Path + |-------------------------------------------------------------------------- + | + | + | + */ + public $path = ''; - /* - |-------------------------------------------------------------------------- - | Date Format for Logs - |-------------------------------------------------------------------------- - | - | Each item that is logged has an associated date. You can use PHP date - | codes to set your own date formatting - | - */ - public $dateFormat = 'Y-m-d'; + /* + |-------------------------------------------------------------------------- + | Date Format for Logs + |-------------------------------------------------------------------------- + | + | Each item that is logged has an associated date. You can use PHP date + | codes to set your own date formatting + | + */ + public $dateFormat = 'Y-m-d'; - /* - |-------------------------------------------------------------------------- - | Log Handlers - |-------------------------------------------------------------------------- - | - | The logging system supports multiple actions to be taken when something - | is logged. This is done by allowing for multiple Handlers, special classes - | designed to write the log to their chosen destinations, whether that is - | a file on the getServer, a cloud-based service, or even taking actions such - | as emailing the dev team. - | - | Each handler is defined by the class name used for that handler, and it - | MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface. - | - | The value of each key is an array of configuration items that are sent - | to the constructor of each handler. The only required configuration item - | is the 'handles' element, which must be an array of integer log levels. - | This is most easily handled by using the constants defined in the - | Psr\Log\LogLevel class. - | - | Handlers are executed in the order defined in this array, starting with - | the handler on top and continuing down. - | - */ - public $handlers = [ + /* + |-------------------------------------------------------------------------- + | Log Handlers + |-------------------------------------------------------------------------- + | + | The logging system supports multiple actions to be taken when something + | is logged. This is done by allowing for multiple Handlers, special classes + | designed to write the log to their chosen destinations, whether that is + | a file on the getServer, a cloud-based service, or even taking actions such + | as emailing the dev team. + | + | Each handler is defined by the class name used for that handler, and it + | MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface. + | + | The value of each key is an array of configuration items that are sent + | to the constructor of each handler. The only required configuration item + | is the 'handles' element, which must be an array of integer log levels. + | This is most easily handled by using the constants defined in the + | Psr\Log\LogLevel class. + | + | Handlers are executed in the order defined in this array, starting with + | the handler on top and continuing down. + | + */ + public $handlers = [ - //-------------------------------------------------------------------- - // File Handler - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // File Handler + //-------------------------------------------------------------------- - 'CodeIgniter\Log\Handlers\TestHandler' => [ + 'CodeIgniter\Log\Handlers\TestHandler' => [ - /* - * The log levels that this handler will handle. - */ - 'handles' => ['critical', 'alert', 'emergency', 'debug', - 'error', 'info', 'notice', 'warning'], - ] - ]; + /* + * The log levels that this handler will handle. + */ + 'handles' => ['critical', 'alert', 'emergency', 'debug', + 'error', 'info', 'notice', 'warning'], + ] + ]; } diff --git a/tests/_support/Config/Registrar.php b/tests/_support/Config/Registrar.php index b571cdb3c22e..8e26de5c79db 100644 --- a/tests/_support/Config/Registrar.php +++ b/tests/_support/Config/Registrar.php @@ -8,13 +8,13 @@ class Registrar { - public static function RegistrarConfig() - { - return [ - 'bar' => ['first', 'second'], - 'format' => 'nice', - 'fruit' => ['apple', 'banana'] - ]; - } + public static function RegistrarConfig() + { + return [ + 'bar' => ['first', 'second'], + 'format' => 'nice', + 'fruit' => ['apple', 'banana'] + ]; + } } diff --git a/tests/_support/DOM/DOMParser.php b/tests/_support/DOM/DOMParser.php index d8154e7f37f0..a7b30921105d 100644 --- a/tests/_support/DOM/DOMParser.php +++ b/tests/_support/DOM/DOMParser.php @@ -2,290 +2,290 @@ class DOMParser { - /** - * @var \DOMDocument - */ - protected $dom; - - public function __construct() - { - if (! extension_loaded('DOM')) - { - throw new \BadMethodCallException('DOM extension is required, but not currently loaded.'); - } - - $this->dom = new \DOMDocument('1.0', 'utf-8'); - } - - /** - * Returns the body of the current document. - * - * @return string - */ - public function getBody(): string - { - return $this->dom->saveHTML(); - } - - /** - * Sets a string as the body that we want to work with. - * - * @param string $content - * - * @return $this - */ - public function withString(string $content) - { - // converts all special characters to utf-8 - $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'); - - //turning off some errors - libxml_use_internal_errors(true); - - if (! $this->dom->loadHTML($content)) - { - throw new \BadMethodCallException('Invalid HTML'); - } - - // ignore the whitespace. - $this->dom->preserveWhiteSpace = false; - - return $this; - } - - /** - * Loads the contents of a file as a string - * so that we can work with it. - * - * @param string $path - * - * @return \Tests\Support\DOM\DOMParser - */ - public function withFile(string $path) - { - if (! is_file($path)) - { - throw new \InvalidArgumentException(basename($path).' is not a valid file.'); - } - - $content = file_get_contents($path); - - return $this->withString($content); - } - - /** - * Checks to see if the text is found within the result. - * - * @param string $search - * - * @return bool - */ - public function see(string $search=null, string $element=null): bool - { - // If Element is null, we're just scanning for text - if (is_null($element)) - { - $content = $this->dom->saveHTML(); - return strpos($content, $search) !== false; - } - - $result = $this->doXPath($search, $element); - - return (bool)$result->length; - } - - /** - * Checks to see if the text is NOT found within the result. - * - * @param string $search - * @param string|null $element - * - * @return bool - */ - public function dontSee(string $search=null, string $element=null): bool - { - return ! $this->see($search, $element); - } - - /** - * Checks to see if an element with the matching CSS specifier - * is found within the current DOM. - * - * @param string $element - * - * @return bool - */ - public function seeElement(string $element): bool - { - return $this->see(null, $element); - } - - /** - * Checks to see if the element is available within the result. - * - * @param string $element - * - * @return bool - */ - public function dontSeeElement(string $element): bool - { - return $this->dontSee(null, $element); - } - - /** - * Determines if a link with the specified text is found - * within the results. - * - * @param string $text - * @param string|null $details - * - * @return bool - */ - public function seeLink(string $text, string $details=null): bool - { - return $this->see($text, 'a'.$details); - } - - /** - * Checks for an input named $field with a value of $value. - * - * @param string $field - * @param string $value - * - * @return bool - */ - public function seeInField(string $field, string $value): bool - { - $result = $this->doXPath(null, "input", ["[@value=\"{$value}\"][@name=\"{$field}\"]"]); - - return (bool)$result->length; - } - - /** - * Checks for checkboxes that are currently checked. - * - * @param string $element - * - * @return bool - */ - public function seeCheckboxIsChecked(string $element): bool - { - $result = $this->doXPath(null, "input".$element, [ - '[@type="checkbox"]', - '[@checked="checked"]' - ]); - - return (bool)$result->length; - } - - - //-------------------------------------------------------------------- - - protected function doXPath(string $search=null, string $element, array $paths=[]) - { - // Otherwise, grab any elements that match - // the selector - $selector = $this->parseSelector($element); - - $path = ''; - - // By ID - if (! empty($selector['id'])) - { - $path = empty($selector['tag']) - ? "id(\"{$selector['id']}\")" - : "//body//{$selector['tag']}[@id=\"{$selector['id']}\"]"; - } - // By Class - else if (! empty($selector['class'])) - { - $path = empty($selector['tag']) - ? "//*[@class=\"{$selector['class']}\"]" - : "//body//{$selector['tag']}[@class=\"{$selector['class']}\"]"; - } - // By tag only - else if (! empty($selector['tag'])) - { - $path = "//body//{$selector['tag']}"; - } - - if (! empty($selector['attr'])) - { - foreach ($selector['attr'] as $key => $value) - { - $path .= "[{$key}={$value}]"; - } - } - - // $paths might contain a number of different - // ready to go xpath portions to tack on. - if (! empty($paths) && is_array($paths)) - { - foreach ($paths as $extra) - { - $path .= $extra; - } - } - - if (! is_null($search)) - { - $path .= "[contains(., \"{$search}\")]"; - } - - $xpath = new \DOMXPath($this->dom); - - $result = $xpath->query($path); - - return $result; - } - - public function parseSelector(string $selector) - { - $tag = null; - $id = null; - $class = null; - $attr = null; - - // ID? - if ($pos = strpos($selector, '#') !== false) - { - list($tag, $id) = explode('#', $selector); - } - // Attribute - elseif (strpos($selector, '[') !== false && strpos($selector, ']') !== false) - { - $open = strpos($selector, '['); - $close = strpos($selector, ']'); - - $tag = substr($selector, 0, $open); - $text = substr($selector, $open+1, $close-2); - - // We only support a single attribute currently - $text = explode(',', $text); - $text = trim(array_shift($text)); - - list($name, $value) = explode('=', $text); - $name = trim($name); - $value = trim($value); - $attr = [$name => trim($value, '] ')]; - } - // Class? - elseif ($pos = strpos($selector, '.') !== false) - { - list($tag, $class) = explode('.', $selector); - } - // Otherwise, assume the entire string is our tag - else - { - $tag = $selector; - } - - return [ - 'tag' => $tag, - 'id' => $id, - 'class' => $class, - 'attr' => $attr - ]; - } + /** + * @var \DOMDocument + */ + protected $dom; + + public function __construct() + { + if (! extension_loaded('DOM')) + { + throw new \BadMethodCallException('DOM extension is required, but not currently loaded.'); + } + + $this->dom = new \DOMDocument('1.0', 'utf-8'); + } + + /** + * Returns the body of the current document. + * + * @return string + */ + public function getBody(): string + { + return $this->dom->saveHTML(); + } + + /** + * Sets a string as the body that we want to work with. + * + * @param string $content + * + * @return $this + */ + public function withString(string $content) + { + // converts all special characters to utf-8 + $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'); + + //turning off some errors + libxml_use_internal_errors(true); + + if (! $this->dom->loadHTML($content)) + { + throw new \BadMethodCallException('Invalid HTML'); + } + + // ignore the whitespace. + $this->dom->preserveWhiteSpace = false; + + return $this; + } + + /** + * Loads the contents of a file as a string + * so that we can work with it. + * + * @param string $path + * + * @return \Tests\Support\DOM\DOMParser + */ + public function withFile(string $path) + { + if (! is_file($path)) + { + throw new \InvalidArgumentException(basename($path).' is not a valid file.'); + } + + $content = file_get_contents($path); + + return $this->withString($content); + } + + /** + * Checks to see if the text is found within the result. + * + * @param string $search + * + * @return bool + */ + public function see(string $search=null, string $element=null): bool + { + // If Element is null, we're just scanning for text + if (is_null($element)) + { + $content = $this->dom->saveHTML(); + return strpos($content, $search) !== false; + } + + $result = $this->doXPath($search, $element); + + return (bool)$result->length; + } + + /** + * Checks to see if the text is NOT found within the result. + * + * @param string $search + * @param string|null $element + * + * @return bool + */ + public function dontSee(string $search=null, string $element=null): bool + { + return ! $this->see($search, $element); + } + + /** + * Checks to see if an element with the matching CSS specifier + * is found within the current DOM. + * + * @param string $element + * + * @return bool + */ + public function seeElement(string $element): bool + { + return $this->see(null, $element); + } + + /** + * Checks to see if the element is available within the result. + * + * @param string $element + * + * @return bool + */ + public function dontSeeElement(string $element): bool + { + return $this->dontSee(null, $element); + } + + /** + * Determines if a link with the specified text is found + * within the results. + * + * @param string $text + * @param string|null $details + * + * @return bool + */ + public function seeLink(string $text, string $details=null): bool + { + return $this->see($text, 'a'.$details); + } + + /** + * Checks for an input named $field with a value of $value. + * + * @param string $field + * @param string $value + * + * @return bool + */ + public function seeInField(string $field, string $value): bool + { + $result = $this->doXPath(null, "input", ["[@value=\"{$value}\"][@name=\"{$field}\"]"]); + + return (bool)$result->length; + } + + /** + * Checks for checkboxes that are currently checked. + * + * @param string $element + * + * @return bool + */ + public function seeCheckboxIsChecked(string $element): bool + { + $result = $this->doXPath(null, "input".$element, [ + '[@type="checkbox"]', + '[@checked="checked"]' + ]); + + return (bool)$result->length; + } + + + //-------------------------------------------------------------------- + + protected function doXPath(string $search=null, string $element, array $paths=[]) + { + // Otherwise, grab any elements that match + // the selector + $selector = $this->parseSelector($element); + + $path = ''; + + // By ID + if (! empty($selector['id'])) + { + $path = empty($selector['tag']) + ? "id(\"{$selector['id']}\")" + : "//body//{$selector['tag']}[@id=\"{$selector['id']}\"]"; + } + // By Class + else if (! empty($selector['class'])) + { + $path = empty($selector['tag']) + ? "//*[@class=\"{$selector['class']}\"]" + : "//body//{$selector['tag']}[@class=\"{$selector['class']}\"]"; + } + // By tag only + else if (! empty($selector['tag'])) + { + $path = "//body//{$selector['tag']}"; + } + + if (! empty($selector['attr'])) + { + foreach ($selector['attr'] as $key => $value) + { + $path .= "[{$key}={$value}]"; + } + } + + // $paths might contain a number of different + // ready to go xpath portions to tack on. + if (! empty($paths) && is_array($paths)) + { + foreach ($paths as $extra) + { + $path .= $extra; + } + } + + if (! is_null($search)) + { + $path .= "[contains(., \"{$search}\")]"; + } + + $xpath = new \DOMXPath($this->dom); + + $result = $xpath->query($path); + + return $result; + } + + public function parseSelector(string $selector) + { + $tag = null; + $id = null; + $class = null; + $attr = null; + + // ID? + if ($pos = strpos($selector, '#') !== false) + { + list($tag, $id) = explode('#', $selector); + } + // Attribute + elseif (strpos($selector, '[') !== false && strpos($selector, ']') !== false) + { + $open = strpos($selector, '['); + $close = strpos($selector, ']'); + + $tag = substr($selector, 0, $open); + $text = substr($selector, $open+1, $close-2); + + // We only support a single attribute currently + $text = explode(',', $text); + $text = trim(array_shift($text)); + + list($name, $value) = explode('=', $text); + $name = trim($name); + $value = trim($value); + $attr = [$name => trim($value, '] ')]; + } + // Class? + elseif ($pos = strpos($selector, '.') !== false) + { + list($tag, $class) = explode('.', $selector); + } + // Otherwise, assume the entire string is our tag + else + { + $tag = $selector; + } + + return [ + 'tag' => $tag, + 'id' => $id, + 'class' => $class, + 'attr' => $attr + ]; + } } diff --git a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php index fd430eafaf80..5d9a14cca83a 100644 --- a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php +++ b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php @@ -2,57 +2,57 @@ class Migration_Create_test_tables extends \CodeIgniter\Database\Migration { - public function up() - { - // User Table - $this->forge->addField([ - 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], - 'name' => ['type' => 'VARCHAR', 'constraint' => 80,], - 'email' => ['type' => 'VARCHAR', 'constraint' => 100], - 'country' => ['type' => 'VARCHAR', 'constraint' => 40,], - 'deleted' => ['type' => 'TINYINT', 'constraint' => 1, 'default' => '0'], - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('user', true); - - // Job Table - $this->forge->addField([ - 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], - 'name' => ['type' => 'VARCHAR', 'constraint' => 40], - 'description' => ['type' => 'TEXT'], - 'created_at' => ['type' => 'DATETIME', 'null' => true] - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('job', true); - - // Misc Table - $this->forge->addField([ - 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true ], - 'key' => ['type' => 'VARCHAR', 'constraint' => 40], - 'value' => ['type' => 'TEXT'], - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('misc', true); - - // Empty Table - $this->forge->addField([ - 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], - 'name' => ['type' => 'VARCHAR', 'constraint' => 40,], - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('empty', true); - } - - //-------------------------------------------------------------------- - - public function down() - { - $this->forge->dropTable('user'); - $this->forge->dropTable('job'); - $this->forge->dropTable('misc'); - $this->forge->dropTable('empty'); - } - - //-------------------------------------------------------------------- + public function up() + { + // User Table + $this->forge->addField([ + 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], + 'name' => ['type' => 'VARCHAR', 'constraint' => 80,], + 'email' => ['type' => 'VARCHAR', 'constraint' => 100], + 'country' => ['type' => 'VARCHAR', 'constraint' => 40,], + 'deleted' => ['type' => 'TINYINT', 'constraint' => 1, 'default' => '0'], + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('user', true); + + // Job Table + $this->forge->addField([ + 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], + 'name' => ['type' => 'VARCHAR', 'constraint' => 40], + 'description' => ['type' => 'TEXT'], + 'created_at' => ['type' => 'DATETIME', 'null' => true] + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('job', true); + + // Misc Table + $this->forge->addField([ + 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true ], + 'key' => ['type' => 'VARCHAR', 'constraint' => 40], + 'value' => ['type' => 'TEXT'], + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('misc', true); + + // Empty Table + $this->forge->addField([ + 'id' => ['type' => 'INTEGER', 'constraint' => 3, 'auto_increment' => true], + 'name' => ['type' => 'VARCHAR', 'constraint' => 40,], + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('empty', true); + } + + //-------------------------------------------------------------------- + + public function down() + { + $this->forge->dropTable('user'); + $this->forge->dropTable('job'); + $this->forge->dropTable('misc'); + $this->forge->dropTable('empty'); + } + + //-------------------------------------------------------------------- } diff --git a/tests/_support/Database/MockBuilder.php b/tests/_support/Database/MockBuilder.php index c24dcb1f6a78..f05c596e4ab2 100644 --- a/tests/_support/Database/MockBuilder.php +++ b/tests/_support/Database/MockBuilder.php @@ -2,12 +2,12 @@ class MockBuilder extends BaseBuilder { - public function __construct($tableName, ConnectionInterface &$db, array $options = null) - { - parent::__construct($tableName, $db, $options); - } + public function __construct($tableName, ConnectionInterface &$db, array $options = null) + { + parent::__construct($tableName, $db, $options); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/Database/MockConnection.php b/tests/_support/Database/MockConnection.php index 9df8d9ab36fd..13bdf2cde7bb 100644 --- a/tests/_support/Database/MockConnection.php +++ b/tests/_support/Database/MockConnection.php @@ -2,202 +2,202 @@ class MockConnection extends BaseConnection { - protected $returnValues = []; + protected $returnValues = []; - public $database; + public $database; public $lastQuery; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function shouldReturn(string $method, $return) - { - $this->returnValues[$method] = $return; + public function shouldReturn(string $method, $return) + { + $this->returnValues[$method] = $return; - return $this; - } + return $this; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function query(string $sql, $binds = null, $queryClass = 'CodeIgniter\\Database\\Query') - { - $queryClass = str_replace('Connection', 'Query', get_class($this)); + public function query(string $sql, $binds = null, $queryClass = 'CodeIgniter\\Database\\Query') + { + $queryClass = str_replace('Connection', 'Query', get_class($this)); - $query = new $queryClass($this); + $query = new $queryClass($this); - $query->setQuery($sql, $binds); + $query->setQuery($sql, $binds); - if (! empty($this->swapPre) && ! empty($this->DBPrefix)) - { - $query->swapPrefix($this->DBPrefix, $this->swapPre); - } + if (! empty($this->swapPre) && ! empty($this->DBPrefix)) + { + $query->swapPrefix($this->DBPrefix, $this->swapPre); + } - $startTime = microtime(true); + $startTime = microtime(true); $this->lastQuery = $query; - // Run the query - if (false === ($this->resultID = $this->simpleQuery($query->getQuery()))) - { - $query->setDuration($startTime, $startTime); - - // @todo deal with errors - - return false; - } - - $query->setDuration($startTime); - - $resultClass = str_replace('Connection', 'Result', get_class($this)); - - return new $resultClass($this->connID, $this->resultID); - } - - //-------------------------------------------------------------------- - - /** - * Connect to the database. - * - * @return mixed - */ - public function connect($persistent = false) - { - $return = $this->returnValues['connect'] ?? true; - - if (is_array($return)) - { - // By removing the top item here, we can - // get a different value for, say, testing failover connections. - $return = array_shift($this->returnValues['connect']); - } - - return $return; - } - - //-------------------------------------------------------------------- - - /** - * Keep or establish the connection if no queries have been sent for - * a length of time exceeding the server's idle timeout. - * - * @return mixed - */ - public function reconnect() - { - return true; - } - - //-------------------------------------------------------------------- - - /** - * Select a specific database table to use. - * - * @param string $databaseName - * - * @return mixed - */ - public function setDatabase(string $databaseName) - { - $this->database = $databaseName; - - return $this; - } - - //-------------------------------------------------------------------- - - /** - * Returns a string containing the version of the database being used. - * - * @return mixed - */ - public function getVersion() - { - return \CodeIgniter\CodeIgniter::CI_VERSION; - } - - //-------------------------------------------------------------------- - - /** - * Executes the query against the database. - * - * @param $sql - * - * @return mixed - */ - protected function execute($sql) - { - return $this->returnValues['execute']; - } - - //-------------------------------------------------------------------- - - /** - * Returns the total number of rows affected by this query. - * - * @return mixed - */ - public function affectedRows(): int - { - return 1; - } - - //-------------------------------------------------------------------- - - /** - * Returns the last error code and message. - * - * Must return an array with keys 'code' and 'message': - * - * return ['code' => null, 'message' => null); - * - * @return array - */ - public function error() - { - return ['code' => null, 'message' => null]; - } - - //-------------------------------------------------------------------- - - /** - * Insert ID - * - * @return int - */ - public function insertID() - { - return $this->connID->insert_id; - } - - //-------------------------------------------------------------------- - - /** - * Generates the SQL for listing tables in a platform-dependent manner. - * - * @param bool $constrainByPrefix - * - * @return string - */ - protected function _listTables($constrainByPrefix = false): string - { - return ''; - } - - //-------------------------------------------------------------------- - - /** - * Generates a platform-specific query string so that the column names can be fetched. - * - * @param string $table - * - * @return string - */ - protected function _listColumns(string $table = ''): string - { - return ''; - } - - //-------------------------------------------------------------------- + // Run the query + if (false === ($this->resultID = $this->simpleQuery($query->getQuery()))) + { + $query->setDuration($startTime, $startTime); + + // @todo deal with errors + + return false; + } + + $query->setDuration($startTime); + + $resultClass = str_replace('Connection', 'Result', get_class($this)); + + return new $resultClass($this->connID, $this->resultID); + } + + //-------------------------------------------------------------------- + + /** + * Connect to the database. + * + * @return mixed + */ + public function connect($persistent = false) + { + $return = $this->returnValues['connect'] ?? true; + + if (is_array($return)) + { + // By removing the top item here, we can + // get a different value for, say, testing failover connections. + $return = array_shift($this->returnValues['connect']); + } + + return $return; + } + + //-------------------------------------------------------------------- + + /** + * Keep or establish the connection if no queries have been sent for + * a length of time exceeding the server's idle timeout. + * + * @return mixed + */ + public function reconnect() + { + return true; + } + + //-------------------------------------------------------------------- + + /** + * Select a specific database table to use. + * + * @param string $databaseName + * + * @return mixed + */ + public function setDatabase(string $databaseName) + { + $this->database = $databaseName; + + return $this; + } + + //-------------------------------------------------------------------- + + /** + * Returns a string containing the version of the database being used. + * + * @return mixed + */ + public function getVersion() + { + return \CodeIgniter\CodeIgniter::CI_VERSION; + } + + //-------------------------------------------------------------------- + + /** + * Executes the query against the database. + * + * @param $sql + * + * @return mixed + */ + protected function execute($sql) + { + return $this->returnValues['execute']; + } + + //-------------------------------------------------------------------- + + /** + * Returns the total number of rows affected by this query. + * + * @return mixed + */ + public function affectedRows(): int + { + return 1; + } + + //-------------------------------------------------------------------- + + /** + * Returns the last error code and message. + * + * Must return an array with keys 'code' and 'message': + * + * return ['code' => null, 'message' => null); + * + * @return array + */ + public function error() + { + return ['code' => null, 'message' => null]; + } + + //-------------------------------------------------------------------- + + /** + * Insert ID + * + * @return int + */ + public function insertID() + { + return $this->connID->insert_id; + } + + //-------------------------------------------------------------------- + + /** + * Generates the SQL for listing tables in a platform-dependent manner. + * + * @param bool $constrainByPrefix + * + * @return string + */ + protected function _listTables($constrainByPrefix = false): string + { + return ''; + } + + //-------------------------------------------------------------------- + + /** + * Generates a platform-specific query string so that the column names can be fetched. + * + * @param string $table + * + * @return string + */ + protected function _listColumns(string $table = ''): string + { + return ''; + } + + //-------------------------------------------------------------------- /** * Close the connection. @@ -213,7 +213,7 @@ protected function _close() /** * Begin Transaction * - * @return bool + * @return bool */ protected function _transBegin(): bool { @@ -225,7 +225,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return bool */ protected function _transCommit(): bool { @@ -237,7 +237,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return bool */ protected function _transRollback(): bool { diff --git a/tests/_support/Database/MockQuery.php b/tests/_support/Database/MockQuery.php index 97658d1e9af3..53741edb02f2 100644 --- a/tests/_support/Database/MockQuery.php +++ b/tests/_support/Database/MockQuery.php @@ -2,5 +2,5 @@ class MockQuery extends Query { - + } diff --git a/tests/_support/Database/MockResult.php b/tests/_support/Database/MockResult.php index d8bdc0788d11..e5aa3da1a93b 100644 --- a/tests/_support/Database/MockResult.php +++ b/tests/_support/Database/MockResult.php @@ -2,97 +2,97 @@ class MockResult extends BaseResult { - /** - * Gets the number of fields in the result set. - * - * @return int - */ - public function getFieldCount(): int - { - - } - - //-------------------------------------------------------------------- - - /** - * Generates an array of column names in the result set. - * - * @return array - */ - public function getFieldNames(): array - { - - } - - //-------------------------------------------------------------------- - - /** - * Generates an array of objects representing field meta-data. - * - * @return array - */ - public function getFieldData(): array - { - - } - - //-------------------------------------------------------------------- - - /** - * Frees the current result. - * - * @return mixed - */ - public function freeResult() - { - - } - - //-------------------------------------------------------------------- - - /** - * 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 - */ - public function dataSeek($n = 0) - { - - } - - //-------------------------------------------------------------------- - - /** - * Returns the result set as an array. - * - * Overridden by driver classes. - * - * @return array - */ - protected function fetchAssoc(): array - { - - } - - //-------------------------------------------------------------------- - - /** - * Returns the result set as an object. - * - * Overridden by child classes. - * - * @param string $className - * - * @return object - */ - protected function fetchObject($className = 'stdClass') - { - - } - - //-------------------------------------------------------------------- + /** + * Gets the number of fields in the result set. + * + * @return int + */ + public function getFieldCount(): int + { + + } + + //-------------------------------------------------------------------- + + /** + * Generates an array of column names in the result set. + * + * @return array + */ + public function getFieldNames(): array + { + + } + + //-------------------------------------------------------------------- + + /** + * Generates an array of objects representing field meta-data. + * + * @return array + */ + public function getFieldData(): array + { + + } + + //-------------------------------------------------------------------- + + /** + * Frees the current result. + * + * @return mixed + */ + public function freeResult() + { + + } + + //-------------------------------------------------------------------- + + /** + * 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 + */ + public function dataSeek($n = 0) + { + + } + + //-------------------------------------------------------------------- + + /** + * Returns the result set as an array. + * + * Overridden by driver classes. + * + * @return array + */ + protected function fetchAssoc(): array + { + + } + + //-------------------------------------------------------------------- + + /** + * Returns the result set as an object. + * + * Overridden by child classes. + * + * @param string $className + * + * @return object + */ + protected function fetchObject($className = 'stdClass') + { + + } + + //-------------------------------------------------------------------- } diff --git a/tests/_support/HTTP/MockCURLRequest.php b/tests/_support/HTTP/MockCURLRequest.php index abd54cc1745d..06963f5e3171 100644 --- a/tests/_support/HTTP/MockCURLRequest.php +++ b/tests/_support/HTTP/MockCURLRequest.php @@ -9,29 +9,29 @@ */ class MockCURLRequest extends CURLRequest { - public $curl_options; + public $curl_options; - protected $output = ''; + protected $output = ''; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setOutput($output) - { - $this->output = $output; + public function setOutput($output) + { + $this->output = $output; - return $this; - } + return $this; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - protected function sendRequest(array $curl_options = []): string - { - // Save so we can access later. - $this->curl_options = $curl_options; + protected function sendRequest(array $curl_options = []): string + { + // Save so we can access later. + $this->curl_options = $curl_options; - return $this->output; - } + return $this->output; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/HTTP/MockResponse.php b/tests/_support/HTTP/MockResponse.php index 0cf70475e953..c8d60d4b370c 100755 --- a/tests/_support/HTTP/MockResponse.php +++ b/tests/_support/HTTP/MockResponse.php @@ -21,13 +21,13 @@ public function setCookie( foreach ( [ - 'value', - 'expire', - 'domain', - 'path', - 'prefix', - 'secure', - 'httponly', + 'value', + 'expire', + 'domain', + 'path', + 'prefix', + 'secure', + 'httponly', 'name' ] as $item ) @@ -43,16 +43,16 @@ public function setCookie( $_COOKIE[$prefix . $name] = $value; /* - TODO: Find a way to use setcookie() + TODO: Find a way to use setcookie() without it throwing header issues. setcookie ( - $prefix.$name, - $value, - $expire, - $path, - $domain, - $secure, + $prefix.$name, + $value, + $expire, + $path, + $domain, + $secure, $httponly ); */ @@ -69,15 +69,15 @@ public function hasCookie(string $name): bool public function deleteCookie ( - $name, - string $domain = '', - string $path = '/', + $name, + string $domain = '', + string $path = '/', string $prefix = '' ) { $COOKIE[$name] = null; unset($COOKIE[$name]); - + //set_cookie($name, '', '', $domain, $path, $prefix); } diff --git a/tests/_support/Helpers/ControllerResponse.php b/tests/_support/Helpers/ControllerResponse.php index 2ca95ba2c866..0cd8f4aa5808 100644 --- a/tests/_support/Helpers/ControllerResponse.php +++ b/tests/_support/Helpers/ControllerResponse.php @@ -7,151 +7,151 @@ class ControllerResponse { - /** - * @var \CodeIgniter\HTTP\IncomingRequest - */ - protected $request; - - /** - * @var \CodeIgniter\HTTP\Response - */ - protected $response; - - /** - * @var string - */ - protected $body; - - /** - * @var DOMParser - */ - protected $dom; - - public function __construct() - { - $this->dom = new DOMParser(); - } - - //-------------------------------------------------------------------- - // Getters / Setters - //-------------------------------------------------------------------- - - /** - * @param string $body - * - * @return $this - */ - public function setBody(string $body) - { - $this->body = $body; - - if (! empty($body)) - { - $this->dom = $this->dom->withString($body); - } - - return $this; - } - - /** - * @return string - */ - public function getBody() - { - return $this->body; - } - - - /** - * @param \CodeIgniter\HTTP\RequestInterface $request - * - * @return $this - */ - public function setRequest(RequestInterface $request) - { - $this->request = $request; - - return $this; - } - - /** - * @param \CodeIgniter\HTTP\ResponseInterface $response - * - * @return $this - */ - public function setResponse(ResponseInterface $response) - { - $this->response = $response; - - $this->setBody($response->getBody() ?? ''); - - return $this; - } - - /** - * @return \CodeIgniter\HTTP\IncomingRequest - */ - public function request() - { - return $this->request; - } - - /** - * @return \CodeIgniter\HTTP\Response - */ - public function response() - { - return $this->response; - } - - //-------------------------------------------------------------------- - // Simple Response Checks - //-------------------------------------------------------------------- - - /** - * Boils down the possible responses into a bolean valid/not-valid - * response type. - * - * @return bool - */ - public function isOK(): bool - { - // Only 200 and 300 range status codes - // are considered valid. - if ($this->response->getStatusCode() >= 400 || $this->response->getStatusCode() < 200) - { - return false; - } - - // Empty bodies are not considered valid. - if (empty($this->response->getBody())) - { - return false; - } - - return true; - } - - /** - * Returns whether or not the Response was a redirect response - * - * @return bool - */ - public function isRedirect(): bool - { - return $this->response instanceof RedirectResponse; - } - - //-------------------------------------------------------------------- - // Utility - //-------------------------------------------------------------------- - - public function __call($function, $params) - { - if (method_exists($this->dom, $function)) - { - return $this->dom->{$function}(...$params); - } - } + /** + * @var \CodeIgniter\HTTP\IncomingRequest + */ + protected $request; + + /** + * @var \CodeIgniter\HTTP\Response + */ + protected $response; + + /** + * @var string + */ + protected $body; + + /** + * @var DOMParser + */ + protected $dom; + + public function __construct() + { + $this->dom = new DOMParser(); + } + + //-------------------------------------------------------------------- + // Getters / Setters + //-------------------------------------------------------------------- + + /** + * @param string $body + * + * @return $this + */ + public function setBody(string $body) + { + $this->body = $body; + + if (! empty($body)) + { + $this->dom = $this->dom->withString($body); + } + + return $this; + } + + /** + * @return string + */ + public function getBody() + { + return $this->body; + } + + + /** + * @param \CodeIgniter\HTTP\RequestInterface $request + * + * @return $this + */ + public function setRequest(RequestInterface $request) + { + $this->request = $request; + + return $this; + } + + /** + * @param \CodeIgniter\HTTP\ResponseInterface $response + * + * @return $this + */ + public function setResponse(ResponseInterface $response) + { + $this->response = $response; + + $this->setBody($response->getBody() ?? ''); + + return $this; + } + + /** + * @return \CodeIgniter\HTTP\IncomingRequest + */ + public function request() + { + return $this->request; + } + + /** + * @return \CodeIgniter\HTTP\Response + */ + public function response() + { + return $this->response; + } + + //-------------------------------------------------------------------- + // Simple Response Checks + //-------------------------------------------------------------------- + + /** + * Boils down the possible responses into a bolean valid/not-valid + * response type. + * + * @return bool + */ + public function isOK(): bool + { + // Only 200 and 300 range status codes + // are considered valid. + if ($this->response->getStatusCode() >= 400 || $this->response->getStatusCode() < 200) + { + return false; + } + + // Empty bodies are not considered valid. + if (empty($this->response->getBody())) + { + return false; + } + + return true; + } + + /** + * Returns whether or not the Response was a redirect response + * + * @return bool + */ + public function isRedirect(): bool + { + return $this->response instanceof RedirectResponse; + } + + //-------------------------------------------------------------------- + // Utility + //-------------------------------------------------------------------- + + public function __call($function, $params) + { + if (method_exists($this->dom, $function)) + { + return $this->dom->{$function}(...$params); + } + } } diff --git a/tests/_support/Helpers/ControllerTester.php b/tests/_support/Helpers/ControllerTester.php index bf97190ac26e..eba6f9eec55e 100644 --- a/tests/_support/Helpers/ControllerTester.php +++ b/tests/_support/Helpers/ControllerTester.php @@ -21,169 +21,169 @@ */ trait ControllerTester { - protected $appConfig; - - protected $request; - - protected $response; - - protected $controller; - - protected $uri = 'http://example.com'; - - protected $body; - - /** - * Loads the specified controller, and generates any needed dependencies. - * - * @param string $name - * - * @return mixed - */ - public function controller(string $name) - { - if (! class_exists($name)) - { - throw new \InvalidArgumentException('Invalid Controller: '.$name); - } - - if (empty($this->appConfig)) - { - $this->appConfig = new App(); - } - - if (empty($this->request)) - { - $this->request = new IncomingRequest($this->appConfig, $this->uri, $this->body); - } - - if (empty($this->response)) - { - $this->response = new Response($this->appConfig); - } - - $this->controller = new $name($this->request, $this->response); - - return $this; - } - - /** - * Runs the specified method on the controller and returns the results. - * - * @param string $method - * @param array $params - * - * @return \Tests\Support\Helpers\ControllerResponse - */ - public function execute(string $method, ...$params) - { - if (! method_exists($this->controller, $method) || ! is_callable([$this->controller, $method])) - { - throw new \InvalidArgumentException('Method does not exist or is not callable in controller: '.$method); - } - - // The URL helper is always loaded by the system - // so ensure it's available. - helper('url'); - - $result = (new ControllerResponse()) - ->setRequest($this->request) - ->setResponse($this->response); - - try - { - ob_start(); - - $response = $this->controller->{$method}(...$params); - } - catch (\Throwable $e) - { - $result->response() - ->setStatusCode($e->getCode()); - } - finally - { - $output = ob_get_clean(); - - // If the controller returned a redirect response - // then we need to use that... - if (isset($response) && $response instanceof Response) - { - $result->setResponse($response); - } - - $result->response()->setBody($output); - $result->setBody($output); - } - - // If not response code has been sent, assume a success - if (empty($result->response()->getStatusCode())) - { - $result->response()->setStatusCode(200); - } - - return $result; - } - - /** - * @param mixed $appConfig - * - * @return mixed - */ - public function withConfig($appConfig) - { - $this->appConfig = $appConfig; - - return $this; - } - - /** - * @param mixed $request - * - * @return mixed - */ - public function withRequest($request) - { - $this->request = $request; - - return $this; - } - - /** - * @param mixed $response - * - * @return mixed - */ - public function withResponse($response) - { - $this->response = $response; - - return $this; - } - - /** - * @param string $uri - * - * @return mixed - */ - public function withUri(string $uri) - { - $this->uri = new URI($uri); - - return $this; - } - - /** - * @param mixed $body - * - * @return mixed - */ - public function withBody($body) - { - $this->body = $body; - - return $this; - } + protected $appConfig; + + protected $request; + + protected $response; + + protected $controller; + + protected $uri = 'http://example.com'; + + protected $body; + + /** + * Loads the specified controller, and generates any needed dependencies. + * + * @param string $name + * + * @return mixed + */ + public function controller(string $name) + { + if (! class_exists($name)) + { + throw new \InvalidArgumentException('Invalid Controller: '.$name); + } + + if (empty($this->appConfig)) + { + $this->appConfig = new App(); + } + + if (empty($this->request)) + { + $this->request = new IncomingRequest($this->appConfig, $this->uri, $this->body); + } + + if (empty($this->response)) + { + $this->response = new Response($this->appConfig); + } + + $this->controller = new $name($this->request, $this->response); + + return $this; + } + + /** + * Runs the specified method on the controller and returns the results. + * + * @param string $method + * @param array $params + * + * @return \Tests\Support\Helpers\ControllerResponse + */ + public function execute(string $method, ...$params) + { + if (! method_exists($this->controller, $method) || ! is_callable([$this->controller, $method])) + { + throw new \InvalidArgumentException('Method does not exist or is not callable in controller: '.$method); + } + + // The URL helper is always loaded by the system + // so ensure it's available. + helper('url'); + + $result = (new ControllerResponse()) + ->setRequest($this->request) + ->setResponse($this->response); + + try + { + ob_start(); + + $response = $this->controller->{$method}(...$params); + } + catch (\Throwable $e) + { + $result->response() + ->setStatusCode($e->getCode()); + } + finally + { + $output = ob_get_clean(); + + // If the controller returned a redirect response + // then we need to use that... + if (isset($response) && $response instanceof Response) + { + $result->setResponse($response); + } + + $result->response()->setBody($output); + $result->setBody($output); + } + + // If not response code has been sent, assume a success + if (empty($result->response()->getStatusCode())) + { + $result->response()->setStatusCode(200); + } + + return $result; + } + + /** + * @param mixed $appConfig + * + * @return mixed + */ + public function withConfig($appConfig) + { + $this->appConfig = $appConfig; + + return $this; + } + + /** + * @param mixed $request + * + * @return mixed + */ + public function withRequest($request) + { + $this->request = $request; + + return $this; + } + + /** + * @param mixed $response + * + * @return mixed + */ + public function withResponse($response) + { + $this->response = $response; + + return $this; + } + + /** + * @param string $uri + * + * @return mixed + */ + public function withUri(string $uri) + { + $this->uri = new URI($uri); + + return $this; + } + + /** + * @param mixed $body + * + * @return mixed + */ + public function withBody($body) + { + $this->body = $body; + + return $this; + } } diff --git a/tests/_support/Language/MockLanguage.php b/tests/_support/Language/MockLanguage.php index dae3c4ebd655..6c0edb704159 100644 --- a/tests/_support/Language/MockLanguage.php +++ b/tests/_support/Language/MockLanguage.php @@ -2,47 +2,47 @@ class MockLanguage extends Language { - /** - * Stores the data that should be - * returned by the 'requireFile()' method. - * - * @var mixed - */ - protected $data; - - //-------------------------------------------------------------------- - - /** - * Sets the data that should be returned by the - * 'requireFile()' method to allow easy overrides - * during testing. - * - * @param $data - * - * @return $this - */ - public function setData($data) - { - $this->data = $data; - - return $this; - } - - //-------------------------------------------------------------------- - - /** - * Provides an override that allows us to set custom - * data to be returned easily during testing. - * - * @param string $path - * - * @return array|mixed - */ - protected function requireFile(string $path): array - { - return $this->data ?? []; - } - - //-------------------------------------------------------------------- + /** + * Stores the data that should be + * returned by the 'requireFile()' method. + * + * @var mixed + */ + protected $data; + + //-------------------------------------------------------------------- + + /** + * Sets the data that should be returned by the + * 'requireFile()' method to allow easy overrides + * during testing. + * + * @param $data + * + * @return $this + */ + public function setData($data) + { + $this->data = $data; + + return $this; + } + + //-------------------------------------------------------------------- + + /** + * Provides an override that allows us to set custom + * data to be returned easily during testing. + * + * @param string $path + * + * @return array|mixed + */ + protected function requireFile(string $path): array + { + return $this->data ?? []; + } + + //-------------------------------------------------------------------- } diff --git a/tests/_support/Log/Handlers/TestHandler.php b/tests/_support/Log/Handlers/TestHandler.php index de34d92abdbf..5b467aac672a 100644 --- a/tests/_support/Log/Handlers/TestHandler.php +++ b/tests/_support/Log/Handlers/TestHandler.php @@ -8,92 +8,92 @@ */ class TestHandler implements HandlerInterface { - /** - * @var array - */ - protected $handles; - - /** - * @var string - */ - protected $dateFormat = 'Y-m-d H:i:s'; - - /** - * Local storage for logs. - * @var array - */ - protected static $logs = []; - - //-------------------------------------------------------------------- - - public function __construct(array $config) - { - $this->handles = $config['handles'] ?? []; - - self::$logs = []; - } - - //-------------------------------------------------------------------- - - /** - * Checks whether the Handler will handle logging items of this - * log Level. - * - * @param $level - * - * @return bool - */ - public function canHandle(string $level): bool - { - return in_array($level, $this->handles); - } - - //-------------------------------------------------------------------- - - /** - * Stores the date format to use while logging messages. - * - * @param string $format - * - * @return HandlerInterface - */ - public function setDateFormat(string $format) - { - $this->dateFormat = $format; - - return $this; - } - - //-------------------------------------------------------------------- - - /** - * Handles logging the message. - * If the handler returns false, then execution of handlers - * will stop. Any handlers that have not run, yet, will not - * be run. - * - * @param $level - * @param $message - * - * @return bool - */ - public function handle($level, $message): bool - { - $date = date($this->dateFormat); - - self::$logs[] = strtoupper($level).' - '.$date.' --> '.$message; - - return true; - } - - //-------------------------------------------------------------------- - - public static function getLogs() - { - return self::$logs; - } - - //-------------------------------------------------------------------- - - -} \ No newline at end of file + /** + * @var array + */ + protected $handles; + + /** + * @var string + */ + protected $dateFormat = 'Y-m-d H:i:s'; + + /** + * Local storage for logs. + * @var array + */ + protected static $logs = []; + + //-------------------------------------------------------------------- + + public function __construct(array $config) + { + $this->handles = $config['handles'] ?? []; + + self::$logs = []; + } + + //-------------------------------------------------------------------- + + /** + * Checks whether the Handler will handle logging items of this + * log Level. + * + * @param $level + * + * @return bool + */ + public function canHandle(string $level): bool + { + return in_array($level, $this->handles); + } + + //-------------------------------------------------------------------- + + /** + * Stores the date format to use while logging messages. + * + * @param string $format + * + * @return HandlerInterface + */ + public function setDateFormat(string $format) + { + $this->dateFormat = $format; + + return $this; + } + + //-------------------------------------------------------------------- + + /** + * Handles logging the message. + * If the handler returns false, then execution of handlers + * will stop. Any handlers that have not run, yet, will not + * be run. + * + * @param $level + * @param $message + * + * @return bool + */ + public function handle($level, $message): bool + { + $date = date($this->dateFormat); + + self::$logs[] = strtoupper($level).' - '.$date.' --> '.$message; + + return true; + } + + //-------------------------------------------------------------------- + + public static function getLogs() + { + return self::$logs; + } + + //-------------------------------------------------------------------- + + +} diff --git a/tests/_support/Log/TestLogger.php b/tests/_support/Log/TestLogger.php index 1012e6413452..97ae63db005c 100644 --- a/tests/_support/Log/TestLogger.php +++ b/tests/_support/Log/TestLogger.php @@ -3,74 +3,74 @@ class TestLogger extends Logger { - protected static $op_logs = []; + protected static $op_logs = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * The log method is overridden so that we can store log history during - * the tests to allow us to check ->assertLogged() methods. - * - * @param string $level - * @param string $message - * @param array $context - * - * @return bool - */ - public function log($level, $message, array $context = []): bool - { - // While this requires duplicate work, we want to ensure - // we have the final message to test against. - $log_message = $this->interpolate($message, $context); + /** + * The log method is overridden so that we can store log history during + * the tests to allow us to check ->assertLogged() methods. + * + * @param string $level + * @param string $message + * @param array $context + * + * @return bool + */ + public function log($level, $message, array $context = []): bool + { + // While this requires duplicate work, we want to ensure + // we have the final message to test against. + $log_message = $this->interpolate($message, $context); - // Determine the file and line by finding the first - // backtrace that is not part of our logging system. - $trace = debug_backtrace(); - $file = null; + // Determine the file and line by finding the first + // backtrace that is not part of our logging system. + $trace = debug_backtrace(); + $file = null; - foreach ($trace as $row) - { - if (! in_array($row['function'], ['log', 'log_message'])) - { - $file = basename($row['file'] ?? ''); - break; - } - } + foreach ($trace as $row) + { + if (! in_array($row['function'], ['log', 'log_message'])) + { + $file = basename($row['file'] ?? ''); + break; + } + } - self::$op_logs[] = [ - 'level' => $level, - 'message' => $log_message, - 'file' => $file, - ]; + self::$op_logs[] = [ + 'level' => $level, + 'message' => $log_message, + 'file' => $file, + ]; - // Let the parent do it's thing. - return parent::log($level, $message, $context); - } + // Let the parent do it's thing. + return parent::log($level, $message, $context); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Used by CIUnitTestCase class to provide ->assertLogged() methods. - * - * @param string $level - * @param string $message - * - * @return bool - */ - public static function didLog(string $level, $message) - { - foreach (self::$op_logs as $log) - { - if (strtolower($log['level']) == strtolower($level) - && $message == $log['message']) - { - return true; - } - } + /** + * Used by CIUnitTestCase class to provide ->assertLogged() methods. + * + * @param string $level + * @param string $message + * + * @return bool + */ + public static function didLog(string $level, $message) + { + foreach (self::$op_logs as $log) + { + if (strtolower($log['level']) == strtolower($level) + && $message == $log['message']) + { + return true; + } + } - return false; - } + return false; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/MockCommon.php b/tests/_support/MockCommon.php index b4cc0cd2823b..6db883a75027 100644 --- a/tests/_support/MockCommon.php +++ b/tests/_support/MockCommon.php @@ -11,27 +11,27 @@ if ( ! function_exists('is_cli')) { - /** - * Is CLI? - * - * Test to see if a request was made from the command line. - * You can set the return value for testing. - * - * @param bool $new_return return value to set - * @return bool - */ - function is_cli(bool $new_return = null): bool - { - // PHPUnit always runs via CLI. - static $return_value = TRUE; + /** + * Is CLI? + * + * Test to see if a request was made from the command line. + * You can set the return value for testing. + * + * @param bool $new_return return value to set + * @return bool + */ + function is_cli(bool $new_return = null): bool + { + // PHPUnit always runs via CLI. + static $return_value = TRUE; - if ($new_return !== null) - { - $return_value = $new_return; - } + if ($new_return !== null) + { + $return_value = $new_return; + } - return $return_value; - } + return $return_value; + } } //-------------------------------------------------------------------- diff --git a/tests/_support/Models/EntityModel.php b/tests/_support/Models/EntityModel.php index 2297b78c0dc2..da74ce81ba10 100644 --- a/tests/_support/Models/EntityModel.php +++ b/tests/_support/Models/EntityModel.php @@ -4,13 +4,13 @@ class EntityModel extends Model { - protected $table = 'job'; + protected $table = 'job'; - protected $returnType = '\Tests\Support\Models\SimpleEntity'; + protected $returnType = '\Tests\Support\Models\SimpleEntity'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = false; - protected $dateFormat = 'datetime'; + protected $dateFormat = 'datetime'; protected $allowedFields = [ 'name', 'description', 'created_at' diff --git a/tests/_support/Models/EventModel.php b/tests/_support/Models/EventModel.php index 79bc25d5bdd6..f125c0b3f706 100644 --- a/tests/_support/Models/EventModel.php +++ b/tests/_support/Models/EventModel.php @@ -4,13 +4,13 @@ class EventModel extends Model { - protected $table = 'user'; + protected $table = 'user'; - protected $returnType = 'array'; + protected $returnType = 'array'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = false; - protected $dateFormat = 'integer'; + protected $dateFormat = 'integer'; protected $allowedFields = [ 'name', 'email', 'country', 'deleted' @@ -26,51 +26,51 @@ class EventModel extends Model // Holds stuff for testing events protected $tokens = []; - protected function beforeInsertMethod(array $data) - { - $this->tokens[] = 'beforeInsert'; + protected function beforeInsertMethod(array $data) + { + $this->tokens[] = 'beforeInsert'; - return $data; + return $data; } - protected function afterInsertMethod(array $data) - { - $this->tokens[] = 'afterInsert'; + protected function afterInsertMethod(array $data) + { + $this->tokens[] = 'afterInsert'; - return $data; - } + return $data; + } - protected function beforeUpdateMethod(array $data) - { - $this->tokens[] = 'beforeUpdate'; + protected function beforeUpdateMethod(array $data) + { + $this->tokens[] = 'beforeUpdate'; - return $data; - } + return $data; + } - protected function afterUpdateMethod(array $data) - { - $this->tokens[] = 'afterUpdate'; + protected function afterUpdateMethod(array $data) + { + $this->tokens[] = 'afterUpdate'; - return $data; - } + return $data; + } - protected function afterFindMethod(array $data) - { - $this->tokens[] = 'afterFind'; + protected function afterFindMethod(array $data) + { + $this->tokens[] = 'afterFind'; - return $data; - } + return $data; + } - protected function afterDeleteMethod(array $data) - { - $this->tokens[] = 'afterDelete'; + protected function afterDeleteMethod(array $data) + { + $this->tokens[] = 'afterDelete'; - return $data; - } + return $data; + } - public function hasToken(string $token) - { - return in_array($token, $this->tokens); - } + public function hasToken(string $token) + { + return in_array($token, $this->tokens); + } } diff --git a/tests/_support/Models/JobModel.php b/tests/_support/Models/JobModel.php index c9b3fcb1f59b..cba62c4a680d 100644 --- a/tests/_support/Models/JobModel.php +++ b/tests/_support/Models/JobModel.php @@ -4,13 +4,13 @@ class JobModel extends Model { - protected $table = 'job'; + protected $table = 'job'; - protected $returnType = 'object'; + protected $returnType = 'object'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = false; - protected $dateFormat = 'integer'; + protected $dateFormat = 'integer'; - protected $allowedFields = ['name', 'description']; + protected $allowedFields = ['name', 'description']; } diff --git a/tests/_support/Models/UserModel.php b/tests/_support/Models/UserModel.php index 087aa97b0b3b..2e94de1c7c41 100644 --- a/tests/_support/Models/UserModel.php +++ b/tests/_support/Models/UserModel.php @@ -4,13 +4,13 @@ class UserModel extends Model { - protected $table = 'user'; + protected $table = 'user'; - protected $allowedFields = ['name', 'email', 'country', 'deleted']; + protected $allowedFields = ['name', 'email', 'country', 'deleted']; - protected $returnType = 'object'; + protected $returnType = 'object'; - protected $useSoftDeletes = true; + protected $useSoftDeletes = true; - protected $dateFormat = 'integer'; + protected $dateFormat = 'integer'; } diff --git a/tests/_support/Models/ValidModel.php b/tests/_support/Models/ValidModel.php index ce2310b5915a..d755354ec4a3 100644 --- a/tests/_support/Models/ValidModel.php +++ b/tests/_support/Models/ValidModel.php @@ -4,19 +4,19 @@ class ValidModel extends Model { - protected $table = 'job'; + protected $table = 'job'; - protected $returnType = 'object'; + protected $returnType = 'object'; - protected $useSoftDeletes = false; + protected $useSoftDeletes = false; - protected $dateFormat = 'integer'; + protected $dateFormat = 'integer'; protected $allowedFields = ['name', 'description']; protected $validationRules = [ 'name' => ['required', 'min_length[3]'], - 'token' => 'in_list[{id}]' + 'token' => 'in_list[{id}]' ]; protected $validationMessages = [ diff --git a/tests/_support/Security/MockSecurity.php b/tests/_support/Security/MockSecurity.php index 106cdc11b10f..ba64463e7fc7 100644 --- a/tests/_support/Security/MockSecurity.php +++ b/tests/_support/Security/MockSecurity.php @@ -4,13 +4,13 @@ class MockSecurity extends Security { - public function CSRFSetCookie(RequestInterface $request) - { - $_COOKIE['csrf_cookie_name'] = $this->CSRFHash; + public function CSRFSetCookie(RequestInterface $request) + { + $_COOKIE['csrf_cookie_name'] = $this->CSRFHash; - return $this; - } + return $this; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/Services.php b/tests/_support/Services.php index beb153eec17a..087bf838b292 100644 --- a/tests/_support/Services.php +++ b/tests/_support/Services.php @@ -8,63 +8,63 @@ */ class Services { - /** - * Mock objects for testing which are returned if exist. - * - * @var array - */ - static protected $mocks = []; + /** + * Mock objects for testing which are returned if exist. + * + * @var array + */ + static protected $mocks = []; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Reset shared instances and mocks for testing. - */ - public static function reset() - { - static::$mocks = []; + /** + * Reset shared instances and mocks for testing. + */ + public static function reset() + { + static::$mocks = []; - CIUnitTestCase::setPrivateProperty(ConfigServices::class, 'instances', []); - } + CIUnitTestCase::setPrivateProperty(ConfigServices::class, 'instances', []); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Inject mock object for testing. - * - * @param string $name - * @param $mock - */ - public static function injectMock(string $name, $mock) - { - $name = strtolower($name); - static::$mocks[$name] = $mock; - } + /** + * Inject mock object for testing. + * + * @param string $name + * @param $mock + */ + public static function injectMock(string $name, $mock) + { + $name = strtolower($name); + static::$mocks[$name] = $mock; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * Returns a service - * - * @param string $name - * @param array $arguments - */ - public static function __callStatic(string $name, array $arguments) - { - $name = strtolower($name); + /** + * Returns a service + * + * @param string $name + * @param array $arguments + */ + public static function __callStatic(string $name, array $arguments) + { + $name = strtolower($name); - // Returns mock if exists - if (isset(static::$mocks[$name])) - { - return static::$mocks[$name]; - } + // Returns mock if exists + if (isset(static::$mocks[$name])) + { + return static::$mocks[$name]; + } - if (method_exists(ConfigServices::class, $name)) - { - return ConfigServices::$name(...$arguments); - } - } + if (method_exists(ConfigServices::class, $name)) + { + return ConfigServices::$name(...$arguments); + } + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/_support/_bootstrap.php b/tests/_support/_bootstrap.php index 272ef3eb25e6..4e8dadf434b5 100644 --- a/tests/_support/_bootstrap.php +++ b/tests/_support/_bootstrap.php @@ -95,7 +95,7 @@ // Set environment values that would otherwise stop the framework from functioning during tests. if (! isset($_SERVER['app.baseURL'])) { - $_SERVER['app.baseURL'] = 'http://example.com'; + $_SERVER['app.baseURL'] = 'http://example.com'; } /* diff --git a/tests/bin/coveralls.phar b/tests/bin/coveralls.phar index 7697d400fdb7..1841b45245ba 100755 Binary files a/tests/bin/coveralls.phar and b/tests/bin/coveralls.phar differ diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index 793b98ae42e1..04a56e67ee1e 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -11,393 +11,393 @@ class ResponseTraitTest extends \CIUnitTestCase { - protected $request; - protected $response; - - /** - * @var Response formatter - */ - protected $formatter; - - public function setUp() - { - parent::setUp(); - - $this->formatter = new JSONFormatter(); - } - - protected function makeController(array $userConfig = [], string $uri = 'http://example.com', array $userHeaders = []) - { - $config = [ - 'baseURL' => 'http://example.com', - 'uriProtocol' => 'REQUEST_URI', - 'defaultLocale' => 'en', - 'negotiateLocale' => false, - 'supportedLocales' => ['en'], - 'CSPEnabled' => false, - 'cookiePrefix' => '', - 'cookieDomain' => '', - 'cookiePath' => '/', - 'cookieSecure' => false, - 'cookieHTTPOnly' => false, - 'proxyIPs' => [] - ]; - - $config = array_merge($config, $userConfig); - - $this->request = new MockIncomingRequest((object) $config, new URI($uri), null, new UserAgent()); - $this->response = new MockResponse((object) $config); - - // Insert headers into request. - $headers = [ - 'Accept' => 'text/html' - ]; - $headers = array_merge($headers, $userHeaders); - - foreach ($headers as $key => $value) - { - $this->request->setHeader($key, $value); - if (($key == 'Accept') && ! is_array($value)) - $this->response->setContentType($value); - } - - // Create the controller class finally. - $controller = new class($this->request, $this->response, $this->formatter) - { - - use ResponseTrait; - - protected $request; - protected $response; - protected $formatter; - - public function __construct(&$request, &$response, &$formatter) - { - $this->request = $request; - $this->response = $response; - $this->formatter = $formatter; - } - }; - - return $controller; - } - - //-------------------------------------------------------------------- - - public function testRespondSets404WithNoData() - { - $controller = $this->makeController(); - $controller->respond(null, null); - - $this->assertEquals(404, $this->response->getStatusCode()); - $this->assertNull($this->response->getBody()); - } - - //-------------------------------------------------------------------- - - public function testRespondSetsStatusWithEmptyData() - { - $controller = $this->makeController(); - $controller->respond(null, 201); - - $this->assertEquals(201, $this->response->getStatusCode()); - $this->assertNull($this->response->getBody()); - } - - //-------------------------------------------------------------------- - - public function testRespondSetsCorrectBodyAndStatus() - { - $controller = $this->makeController(); - $controller->respond('something', 201); - - $this->assertEquals(201, $this->response->getStatusCode()); - $this->assertEquals('something', $this->response->getBody()); - $this->assertStringStartsWith('text/html', $this->response->getHeaderLine('Content-Type')); - $this->assertEquals('Created', $this->response->getReason()); - } - - //-------------------------------------------------------------------- - - public function testRespondWithCustomReason() - { - $controller = $this->makeController(); - $controller->respond('something', 201, 'A Custom Reason'); - - $this->assertEquals(201, $this->response->getStatusCode()); - $this->assertEquals('A Custom Reason', $this->response->getReason()); - } - - public function testFailSingleMessage() - { - $controller = $this->makeController(); - - $controller->fail('Failure to Launch', 500, 'WHAT!', 'A Custom Reason'); - - // Will use the JSON formatter by default - $expected = [ - 'status' => 500, - 'error' => 'WHAT!', - 'messages' => [ - 'error' => 'Failure to Launch' - ] - ]; - - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - $this->assertEquals(500, $this->response->getStatusCode()); - $this->assertEquals('A Custom Reason', $this->response->getReason()); - } - - public function testCreated() - { - $controller = $this->makeController(); - $controller->respondCreated(['id' => 3], 'A Custom Reason'); - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(201, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format(['id' => 3]), $this->response->getBody()); - } - - public function testDeleted() - { - $controller = $this->makeController(); - $controller->respondDeleted(['id' => 3], 'A Custom Reason'); - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(200, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format(['id' => 3]), $this->response->getBody()); - } - - public function testUnauthorized() - { - $controller = $this->makeController(); - $controller->failUnauthorized('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 401, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(401, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testForbidden() - { - $controller = $this->makeController(); - $controller->failForbidden('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 403, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(403, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testNotFound() - { - $controller = $this->makeController(); - $controller->failNotFound('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 404, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(404, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testValidationError() - { - $controller = $this->makeController(); - $controller->failValidationError('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 400, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(400, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testResourceExists() - { - $controller = $this->makeController(); - $controller->failResourceExists('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 409, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(409, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testResourceGone() - { - $controller = $this->makeController(); - $controller->failResourceGone('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 410, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(410, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testTooManyRequests() - { - $controller = $this->makeController(); - $controller->failTooManyRequests('Nope', 'FAT CHANCE', 'A Custom Reason'); - - $expected = [ - 'status' => 429, - 'error' => 'FAT CHANCE', - 'messages' => [ - 'error' => 'Nope' - ] - ]; - - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(429, $this->response->getStatusCode()); - $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); - } - - public function testServerError() - { - $controller = $this->makeController(); - $controller->failServerError('Nope.', 'FAT-CHANCE', 'A custom reason.'); - - $this::assertEquals('A custom reason.', $this->response->getReason()); - $this::assertEquals(500, $this->response->getStatusCode()); - $this::assertEquals($this->formatter->format([ - 'status' => 500, - 'error' => 'FAT-CHANCE', - 'messages' => [ - 'error' => 'Nope.' - ] - ]), $this->response->getBody()); - } - - public function testValidContentTypes() - { - $chars = '; charset=UTF-8'; - $goodMimes = ['text/xml', 'text/html', 'application/json', 'application/xml']; - for ($i = 0; $i < count($goodMimes); $i ++ ) - $this->tryValidContentType($goodMimes[$i], $goodMimes[$i] . $chars); - } - - private function tryValidContentType($mimeType, $contentType) - { - $original = $_SERVER; - $_SERVER['CONTENT_TYPE'] = $mimeType; - - $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => $mimeType]); - $this->assertEquals($mimeType, $this->request->getHeaderLine('Accept'), 'Request header...'); - $this->response->setContentType($contentType); - $this->assertEquals($contentType, $this->response->getHeaderLine('Content-Type'), 'Response header pre-response...'); - - $_SERVER = $original; - } - - public function testValidResponses() - { - $chars = '; charset=UTF-8'; - $goodMimes = ['text/xml', 'text/html', 'application/json', 'application/xml']; - for ($i = 0; $i < count($goodMimes); $i ++ ) - $this->tryValidContentType($goodMimes[$i], $goodMimes[$i] . $chars); - } - - private function tryValidResponse($mimeType, $contentType) - { - $original = $_SERVER; - $_SERVER['CONTENT_TYPE'] = $mimeType; - - $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => $mimeType]); - $this->assertEquals($mimeType, $this->request->getHeaderLine('Accept'), 'Request header...'); - - $this->assertEquals($contentType, $this->response->getHeaderLine('Content-Type'), 'Response header pre-response...'); - $this->response->setContentType($contentType); - $controller->respond('HTML assumed'); - - $this->assertEquals(200, $this->response->getStatusCode()); - $expected = 'HTML assumed'; - $this->assertEquals($expected, $this->response->getBody()); - - $_SERVER = $original; - } - - public function testXMLFormatter() - { - $this->formatter = new XMLFormatter(); - $controller = $this->makeController(); - - $this->assertEquals('CodeIgniter\Format\XMLFormatter', get_class($this->formatter)); - - $controller->respondCreated(['id' => 3], 'A Custom Reason'); - $expected = <<formatter = new JSONFormatter(); + } + + protected function makeController(array $userConfig = [], string $uri = 'http://example.com', array $userHeaders = []) + { + $config = [ + 'baseURL' => 'http://example.com', + 'uriProtocol' => 'REQUEST_URI', + 'defaultLocale' => 'en', + 'negotiateLocale' => false, + 'supportedLocales' => ['en'], + 'CSPEnabled' => false, + 'cookiePrefix' => '', + 'cookieDomain' => '', + 'cookiePath' => '/', + 'cookieSecure' => false, + 'cookieHTTPOnly' => false, + 'proxyIPs' => [] + ]; + + $config = array_merge($config, $userConfig); + + $this->request = new MockIncomingRequest((object) $config, new URI($uri), null, new UserAgent()); + $this->response = new MockResponse((object) $config); + + // Insert headers into request. + $headers = [ + 'Accept' => 'text/html' + ]; + $headers = array_merge($headers, $userHeaders); + + foreach ($headers as $key => $value) + { + $this->request->setHeader($key, $value); + if (($key == 'Accept') && ! is_array($value)) + $this->response->setContentType($value); + } + + // Create the controller class finally. + $controller = new class($this->request, $this->response, $this->formatter) + { + + use ResponseTrait; + + protected $request; + protected $response; + protected $formatter; + + public function __construct(&$request, &$response, &$formatter) + { + $this->request = $request; + $this->response = $response; + $this->formatter = $formatter; + } + }; + + return $controller; + } + + //-------------------------------------------------------------------- + + public function testRespondSets404WithNoData() + { + $controller = $this->makeController(); + $controller->respond(null, null); + + $this->assertEquals(404, $this->response->getStatusCode()); + $this->assertNull($this->response->getBody()); + } + + //-------------------------------------------------------------------- + + public function testRespondSetsStatusWithEmptyData() + { + $controller = $this->makeController(); + $controller->respond(null, 201); + + $this->assertEquals(201, $this->response->getStatusCode()); + $this->assertNull($this->response->getBody()); + } + + //-------------------------------------------------------------------- + + public function testRespondSetsCorrectBodyAndStatus() + { + $controller = $this->makeController(); + $controller->respond('something', 201); + + $this->assertEquals(201, $this->response->getStatusCode()); + $this->assertEquals('something', $this->response->getBody()); + $this->assertStringStartsWith('text/html', $this->response->getHeaderLine('Content-Type')); + $this->assertEquals('Created', $this->response->getReason()); + } + + //-------------------------------------------------------------------- + + public function testRespondWithCustomReason() + { + $controller = $this->makeController(); + $controller->respond('something', 201, 'A Custom Reason'); + + $this->assertEquals(201, $this->response->getStatusCode()); + $this->assertEquals('A Custom Reason', $this->response->getReason()); + } + + public function testFailSingleMessage() + { + $controller = $this->makeController(); + + $controller->fail('Failure to Launch', 500, 'WHAT!', 'A Custom Reason'); + + // Will use the JSON formatter by default + $expected = [ + 'status' => 500, + 'error' => 'WHAT!', + 'messages' => [ + 'error' => 'Failure to Launch' + ] + ]; + + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + $this->assertEquals(500, $this->response->getStatusCode()); + $this->assertEquals('A Custom Reason', $this->response->getReason()); + } + + public function testCreated() + { + $controller = $this->makeController(); + $controller->respondCreated(['id' => 3], 'A Custom Reason'); + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(201, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format(['id' => 3]), $this->response->getBody()); + } + + public function testDeleted() + { + $controller = $this->makeController(); + $controller->respondDeleted(['id' => 3], 'A Custom Reason'); + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(200, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format(['id' => 3]), $this->response->getBody()); + } + + public function testUnauthorized() + { + $controller = $this->makeController(); + $controller->failUnauthorized('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 401, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(401, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testForbidden() + { + $controller = $this->makeController(); + $controller->failForbidden('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 403, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(403, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testNotFound() + { + $controller = $this->makeController(); + $controller->failNotFound('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 404, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(404, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testValidationError() + { + $controller = $this->makeController(); + $controller->failValidationError('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 400, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(400, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testResourceExists() + { + $controller = $this->makeController(); + $controller->failResourceExists('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 409, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(409, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testResourceGone() + { + $controller = $this->makeController(); + $controller->failResourceGone('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 410, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(410, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testTooManyRequests() + { + $controller = $this->makeController(); + $controller->failTooManyRequests('Nope', 'FAT CHANCE', 'A Custom Reason'); + + $expected = [ + 'status' => 429, + 'error' => 'FAT CHANCE', + 'messages' => [ + 'error' => 'Nope' + ] + ]; + + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(429, $this->response->getStatusCode()); + $this->assertEquals($this->formatter->format($expected), $this->response->getBody()); + } + + public function testServerError() + { + $controller = $this->makeController(); + $controller->failServerError('Nope.', 'FAT-CHANCE', 'A custom reason.'); + + $this::assertEquals('A custom reason.', $this->response->getReason()); + $this::assertEquals(500, $this->response->getStatusCode()); + $this::assertEquals($this->formatter->format([ + 'status' => 500, + 'error' => 'FAT-CHANCE', + 'messages' => [ + 'error' => 'Nope.' + ] + ]), $this->response->getBody()); + } + + public function testValidContentTypes() + { + $chars = '; charset=UTF-8'; + $goodMimes = ['text/xml', 'text/html', 'application/json', 'application/xml']; + for ($i = 0; $i < count($goodMimes); $i ++ ) + $this->tryValidContentType($goodMimes[$i], $goodMimes[$i] . $chars); + } + + private function tryValidContentType($mimeType, $contentType) + { + $original = $_SERVER; + $_SERVER['CONTENT_TYPE'] = $mimeType; + + $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => $mimeType]); + $this->assertEquals($mimeType, $this->request->getHeaderLine('Accept'), 'Request header...'); + $this->response->setContentType($contentType); + $this->assertEquals($contentType, $this->response->getHeaderLine('Content-Type'), 'Response header pre-response...'); + + $_SERVER = $original; + } + + public function testValidResponses() + { + $chars = '; charset=UTF-8'; + $goodMimes = ['text/xml', 'text/html', 'application/json', 'application/xml']; + for ($i = 0; $i < count($goodMimes); $i ++ ) + $this->tryValidContentType($goodMimes[$i], $goodMimes[$i] . $chars); + } + + private function tryValidResponse($mimeType, $contentType) + { + $original = $_SERVER; + $_SERVER['CONTENT_TYPE'] = $mimeType; + + $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => $mimeType]); + $this->assertEquals($mimeType, $this->request->getHeaderLine('Accept'), 'Request header...'); + + $this->assertEquals($contentType, $this->response->getHeaderLine('Content-Type'), 'Response header pre-response...'); + $this->response->setContentType($contentType); + $controller->respond('HTML assumed'); + + $this->assertEquals(200, $this->response->getStatusCode()); + $expected = 'HTML assumed'; + $this->assertEquals($expected, $this->response->getBody()); + + $_SERVER = $original; + } + + public function testXMLFormatter() + { + $this->formatter = new XMLFormatter(); + $controller = $this->makeController(); + + $this->assertEquals('CodeIgniter\Format\XMLFormatter', get_class($this->formatter)); + + $controller->respondCreated(['id' => 3], 'A Custom Reason'); + $expected = << 3 EOH; - $this->assertEquals($expected, $this->response->getBody()); - } + $this->assertEquals($expected, $this->response->getBody()); + } - public function testNoFormatterHTML() - { - $this->formatter = null; - $controller = $this->makeController(); - $controller->respondCreated('A Custom Reason'); + public function testNoFormatterHTML() + { + $this->formatter = null; + $controller = $this->makeController(); + $controller->respondCreated('A Custom Reason'); - $this->assertEquals('A Custom Reason', $this->response->getBody()); - } + $this->assertEquals('A Custom Reason', $this->response->getBody()); + } - public function testNoFormatterJSON() - { - $this->formatter = null; - $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => 'application/json']); - $controller->respondCreated(['id' => 3], 'A Custom Reason'); + public function testNoFormatterJSON() + { + $this->formatter = null; + $controller = $this->makeController([], 'http://codeigniter.com', ['Accept' => 'application/json']); + $controller->respondCreated(['id' => 3], 'A Custom Reason'); - $this->assertEquals('A Custom Reason', $this->response->getReason()); - $this->assertEquals(201, $this->response->getStatusCode()); + $this->assertEquals('A Custom Reason', $this->response->getReason()); + $this->assertEquals(201, $this->response->getStatusCode()); - $expected = <<assertEquals($expected, $this->response->getBody()); - } + $this->assertEquals($expected, $this->response->getBody()); + } } diff --git a/tests/system/Autoloader/AutoloaderTest.php b/tests/system/Autoloader/AutoloaderTest.php index 28586c89e010..d818f95a6540 100644 --- a/tests/system/Autoloader/AutoloaderTest.php +++ b/tests/system/Autoloader/AutoloaderTest.php @@ -7,207 +7,207 @@ class AutoloaderTest extends \CIUnitTestCase { - protected $loader; - - //-------------------------------------------------------------------- - - protected function setUp() - { - $config = new Autoload(); - - $config->classmap = [ - 'FirstClass' => '/app/dir/First.php', - 'Name\Spaced\Class' => '/app/namespace/Class.php', - ]; - $config->psr4 = [ - 'App\Controllers' => '/application/Controllers', - 'App\Libraries' => '/application/somewhere', - ]; - - $this->loader = new MockAutoloader(); - $this->loader->initialize($config); - - $this->loader->setFiles([ - '/application/Controllers/Classname.php', - '/application/somewhere/Classname.php', - '/app/dir/First.php', - '/app/namespace/Class.php', - '/my/app/Class.php', - APPPATH . 'Libraries/someLibrary.php', - APPPATH . 'Models/someModel.php', - APPPATH . 'Models/Some/CoolModel.php', - ]); - } - - //-------------------------------------------------------------------- - //-------------------------------------------------------------------- - // PSR4 Namespacing - //-------------------------------------------------------------------- - - public function testServiceAutoLoaderFromShareInstances() - { - - $auto_loader = \CodeIgniter\Config\Services::autoloader(); - // $auto_loader->register(); - // look for Home controller, as that should be in base repo - $actual = $auto_loader->loadClass('App\Controllers\Home'); - $expected = APPPATH . 'Controllers/Home.php'; - $this->assertSame($expected, $actual); - } - - //-------------------------------------------------------------------- - - public function testServiceAutoLoader() - { - - $getShared = false; - $auto_loader = \CodeIgniter\Config\Services::autoloader($getShared); - $auto_loader->initialize(new Autoload()); - $auto_loader->register(); - // look for Home controller, as that should be in base repo - $actual = $auto_loader->loadClass('App\Controllers\Home'); - $expected = APPPATH . 'Controllers/Home.php'; - $this->assertSame($expected, $actual); - } - - //-------------------------------------------------------------------- - - public function testExistingFile() - { - $actual = $this->loader->loadClass('App\Controllers\Classname'); - $expected = '/application/Controllers/Classname.php'; - $this->assertSame($expected, $actual); - - $actual = $this->loader->loadClass('App\Libraries\Classname'); - $expected = '/application/somewhere/Classname.php'; - $this->assertSame($expected, $actual); - } - - //-------------------------------------------------------------------- - - public function testMatchesWithPreceedingSlash() - { - $actual = $this->loader->loadClass('\App\Controllers\Classname'); - $expected = '/application/Controllers/Classname.php'; - $this->assertSame($expected, $actual); - } - - //-------------------------------------------------------------------- - - public function testMatchesWithFileExtension() - { - $actual = $this->loader->loadClass('\App\Controllers\Classname.php'); - $expected = '/application/Controllers/Classname.php'; - $this->assertSame($expected, $actual); - } - - //-------------------------------------------------------------------- - - public function testMissingFile() - { - $this->assertFalse($this->loader->loadClass('\App\Missing\Classname')); - } - - //-------------------------------------------------------------------- - //-------------------------------------------------------------------- - - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Config array must contain either the 'psr4' key or the 'classmap' key. - */ - public function testInitializeException() - { - $config = new Autoload(); - $config->classmap = []; - $config->psr4 = []; - - $this->loader = new MockAutoloader(); - $this->loader->initialize($config); - } - - public function testAddNamespaceWorks() - { - $this->assertFalse($this->loader->loadClass('My\App\Class')); - - $this->loader->addNamespace('My\App', '/my/app'); - - $actual = $this->loader->loadClass('My\App\Class'); - $expected = '/my/app/Class.php'; - - $this->assertSame($expected, $actual); - } - - public function testAddNamespaceMultiplePathsWorks() - { - $this->loader->addNamespace('My\App', '/my/app'); - $this->loader->addNamespace('My\App', '/test/app'); - $this->loader->setFiles([ - '/my/app/Class.php', - '/test/app/ClassTest.php', - ]); - - $actual = $this->loader->loadClass('My\App\ClassTest'); - $expected = '/test/app/ClassTest.php'; - $this->assertSame($expected, $actual); - - $actual = $this->loader->loadClass('My\App\Class'); - $expected = '/my/app/Class.php'; - $this->assertSame($expected, $actual); - } - - public function testAddNamespaceStingToArray() - { - $this->loader->addNamespace('App\Controllers', '/application/Controllers'); - - $this->assertSame('/application/Controllers/Classname.php', $this->loader->loadClass('App\Controllers\Classname')); - } - - //-------------------------------------------------------------------- - - public function testRemoveNamespace() - { - $this->loader->addNamespace('My\App', '/my/app'); - $this->assertSame('/my/app/Class.php', $this->loader->loadClass('My\App\Class')); - - $this->loader->removeNamespace('My\App'); - $this->assertFalse((bool) $this->loader->loadClass('My\App\Class')); - } - - //-------------------------------------------------------------------- - - public function testLoadLegacy() - { - // should not be able to find a folder - $this->assertFalse((bool) $this->loader->loadClass('someLibraries')); - // should be able to find these because we said so in the MockAutoloader - $this->assertTrue((bool) $this->loader->loadClass('someLibrary')); - $this->assertTrue((bool) $this->loader->loadClass('someModel')); - // should not be able to find these - don't exist - $this->assertFalse((bool) $this->loader->loadClass('anotherLibrary')); - $this->assertFalse((bool) $this->loader->loadClass('\nester\anotherLibrary')); - $this->assertFalse((bool) $this->loader->loadClass('\Shouldnt\Find\This')); - // should not be able to find these legacy classes - namespaced - $this->assertFalse($this->loader->loadClass('\Some\CoolModel')); - } - - //-------------------------------------------------------------------- - - public function testSanitizationSimply() - { - $test = '${../path}!#/to/some/file.php_'; - $expected = '/path/to/some/file.php'; - - $this->assertEquals($expected, $this->loader->sanitizeFilename($test)); - } - - //-------------------------------------------------------------------- - - public function testSanitizationAllowsWindowsFilepaths() - { - $test = 'C:\path\to\some/file.php'; - - $this->assertEquals($test, $this->loader->sanitizeFilename($test)); - } - - //-------------------------------------------------------------------- + protected $loader; + + //-------------------------------------------------------------------- + + protected function setUp() + { + $config = new Autoload(); + + $config->classmap = [ + 'FirstClass' => '/app/dir/First.php', + 'Name\Spaced\Class' => '/app/namespace/Class.php', + ]; + $config->psr4 = [ + 'App\Controllers' => '/application/Controllers', + 'App\Libraries' => '/application/somewhere', + ]; + + $this->loader = new MockAutoloader(); + $this->loader->initialize($config); + + $this->loader->setFiles([ + '/application/Controllers/Classname.php', + '/application/somewhere/Classname.php', + '/app/dir/First.php', + '/app/namespace/Class.php', + '/my/app/Class.php', + APPPATH . 'Libraries/someLibrary.php', + APPPATH . 'Models/someModel.php', + APPPATH . 'Models/Some/CoolModel.php', + ]); + } + + //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + // PSR4 Namespacing + //-------------------------------------------------------------------- + + public function testServiceAutoLoaderFromShareInstances() + { + + $auto_loader = \CodeIgniter\Config\Services::autoloader(); + // $auto_loader->register(); + // look for Home controller, as that should be in base repo + $actual = $auto_loader->loadClass('App\Controllers\Home'); + $expected = APPPATH . 'Controllers/Home.php'; + $this->assertSame($expected, $actual); + } + + //-------------------------------------------------------------------- + + public function testServiceAutoLoader() + { + + $getShared = false; + $auto_loader = \CodeIgniter\Config\Services::autoloader($getShared); + $auto_loader->initialize(new Autoload()); + $auto_loader->register(); + // look for Home controller, as that should be in base repo + $actual = $auto_loader->loadClass('App\Controllers\Home'); + $expected = APPPATH . 'Controllers/Home.php'; + $this->assertSame($expected, $actual); + } + + //-------------------------------------------------------------------- + + public function testExistingFile() + { + $actual = $this->loader->loadClass('App\Controllers\Classname'); + $expected = '/application/Controllers/Classname.php'; + $this->assertSame($expected, $actual); + + $actual = $this->loader->loadClass('App\Libraries\Classname'); + $expected = '/application/somewhere/Classname.php'; + $this->assertSame($expected, $actual); + } + + //-------------------------------------------------------------------- + + public function testMatchesWithPreceedingSlash() + { + $actual = $this->loader->loadClass('\App\Controllers\Classname'); + $expected = '/application/Controllers/Classname.php'; + $this->assertSame($expected, $actual); + } + + //-------------------------------------------------------------------- + + public function testMatchesWithFileExtension() + { + $actual = $this->loader->loadClass('\App\Controllers\Classname.php'); + $expected = '/application/Controllers/Classname.php'; + $this->assertSame($expected, $actual); + } + + //-------------------------------------------------------------------- + + public function testMissingFile() + { + $this->assertFalse($this->loader->loadClass('\App\Missing\Classname')); + } + + //-------------------------------------------------------------------- + //-------------------------------------------------------------------- + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Config array must contain either the 'psr4' key or the 'classmap' key. + */ + public function testInitializeException() + { + $config = new Autoload(); + $config->classmap = []; + $config->psr4 = []; + + $this->loader = new MockAutoloader(); + $this->loader->initialize($config); + } + + public function testAddNamespaceWorks() + { + $this->assertFalse($this->loader->loadClass('My\App\Class')); + + $this->loader->addNamespace('My\App', '/my/app'); + + $actual = $this->loader->loadClass('My\App\Class'); + $expected = '/my/app/Class.php'; + + $this->assertSame($expected, $actual); + } + + public function testAddNamespaceMultiplePathsWorks() + { + $this->loader->addNamespace('My\App', '/my/app'); + $this->loader->addNamespace('My\App', '/test/app'); + $this->loader->setFiles([ + '/my/app/Class.php', + '/test/app/ClassTest.php', + ]); + + $actual = $this->loader->loadClass('My\App\ClassTest'); + $expected = '/test/app/ClassTest.php'; + $this->assertSame($expected, $actual); + + $actual = $this->loader->loadClass('My\App\Class'); + $expected = '/my/app/Class.php'; + $this->assertSame($expected, $actual); + } + + public function testAddNamespaceStingToArray() + { + $this->loader->addNamespace('App\Controllers', '/application/Controllers'); + + $this->assertSame('/application/Controllers/Classname.php', $this->loader->loadClass('App\Controllers\Classname')); + } + + //-------------------------------------------------------------------- + + public function testRemoveNamespace() + { + $this->loader->addNamespace('My\App', '/my/app'); + $this->assertSame('/my/app/Class.php', $this->loader->loadClass('My\App\Class')); + + $this->loader->removeNamespace('My\App'); + $this->assertFalse((bool) $this->loader->loadClass('My\App\Class')); + } + + //-------------------------------------------------------------------- + + public function testLoadLegacy() + { + // should not be able to find a folder + $this->assertFalse((bool) $this->loader->loadClass('someLibraries')); + // should be able to find these because we said so in the MockAutoloader + $this->assertTrue((bool) $this->loader->loadClass('someLibrary')); + $this->assertTrue((bool) $this->loader->loadClass('someModel')); + // should not be able to find these - don't exist + $this->assertFalse((bool) $this->loader->loadClass('anotherLibrary')); + $this->assertFalse((bool) $this->loader->loadClass('\nester\anotherLibrary')); + $this->assertFalse((bool) $this->loader->loadClass('\Shouldnt\Find\This')); + // should not be able to find these legacy classes - namespaced + $this->assertFalse($this->loader->loadClass('\Some\CoolModel')); + } + + //-------------------------------------------------------------------- + + public function testSanitizationSimply() + { + $test = '${../path}!#/to/some/file.php_'; + $expected = '/path/to/some/file.php'; + + $this->assertEquals($expected, $this->loader->sanitizeFilename($test)); + } + + //-------------------------------------------------------------------- + + public function testSanitizationAllowsWindowsFilepaths() + { + $test = 'C:\path\to\some/file.php'; + + $this->assertEquals($test, $this->loader->sanitizeFilename($test)); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Autoloader/FileLocatorTest.php b/tests/system/Autoloader/FileLocatorTest.php index 131796ae8f05..eff9e99152fb 100644 --- a/tests/system/Autoloader/FileLocatorTest.php +++ b/tests/system/Autoloader/FileLocatorTest.php @@ -5,244 +5,244 @@ class FileLocatorTest extends \CIUnitTestCase { - /** - * @var MockFileLocator - */ - protected $loader; + /** + * @var MockFileLocator + */ + protected $loader; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setUp() - { - $config = new MockAutoload(); - $config->psr4 = [ - 'App\Libraries' => '/application/somewhere', - 'App' => '/application', - 'Sys' => BASEPATH, - 'Blog' => '/modules/blog' - ]; + public function setUp() + { + $config = new MockAutoload(); + $config->psr4 = [ + 'App\Libraries' => '/application/somewhere', + 'App' => '/application', + 'Sys' => BASEPATH, + 'Blog' => '/modules/blog' + ]; - $this->loader = new MockFileLocator($config); + $this->loader = new MockFileLocator($config); - $this->loader->setFiles([ - APPPATH . 'index.php', - APPPATH . 'Views/index.php', - APPPATH . 'Views/admin/users/create.php', - '/modules/blog/Views/index.php', - '/modules/blog/Views/admin/posts.php' - ]); - } + $this->loader->setFiles([ + APPPATH . 'index.php', + APPPATH . 'Views/index.php', + APPPATH . 'Views/admin/users/create.php', + '/modules/blog/Views/index.php', + '/modules/blog/Views/admin/posts.php' + ]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileWorksInApplicationDirectory() - { - $file = 'index'; + public function testLocateFileWorksInApplicationDirectory() + { + $file = 'index'; - $expected = APPPATH . 'Views/index.php'; + $expected = APPPATH . 'Views/index.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileWorksInApplicationDirectoryWithoutFolder() - { - $file = 'index'; + public function testLocateFileWorksInApplicationDirectoryWithoutFolder() + { + $file = 'index'; - $expected = APPPATH . 'index.php'; + $expected = APPPATH . 'index.php'; - $this->assertEquals($expected, $this->loader->locateFile($file)); - } + $this->assertEquals($expected, $this->loader->locateFile($file)); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileWorksInNestedApplicationDirectory() - { - $file = 'admin/users/create'; + public function testLocateFileWorksInNestedApplicationDirectory() + { + $file = 'admin/users/create'; - $expected = APPPATH . 'Views/admin/users/create.php'; + $expected = APPPATH . 'Views/admin/users/create.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileReplacesFolderName() - { - $file = '\Blog\Views/admin/posts.php'; + public function testLocateFileReplacesFolderName() + { + $file = '\Blog\Views/admin/posts.php'; - $expected = '/modules/blog/Views/admin/posts.php'; + $expected = '/modules/blog/Views/admin/posts.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileReplacesFolderNameLegacy() - { - $file = 'Views/index.php'; + public function testLocateFileReplacesFolderNameLegacy() + { + $file = 'Views/index.php'; - $expected = APPPATH . 'Views/index.php'; + $expected = APPPATH . 'Views/index.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileCanFindNamespacedView() - { - $file = '\Blog\index'; + public function testLocateFileCanFindNamespacedView() + { + $file = '\Blog\index'; - $expected = '/modules/blog/Views/index.php'; + $expected = '/modules/blog/Views/index.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileCanFindNestedNamespacedView() - { - $file = '\Blog\admin/posts.php'; + public function testLocateFileCanFindNestedNamespacedView() + { + $file = '\Blog\admin/posts.php'; - $expected = '/modules/blog/Views/admin/posts.php'; + $expected = '/modules/blog/Views/admin/posts.php'; - $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals($expected, $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLocateFileReturnsEmptyWithBadNamespace() - { - $file = '\Blogger\admin/posts.php'; + public function testLocateFileReturnsEmptyWithBadNamespace() + { + $file = '\Blogger\admin/posts.php'; - $this->assertEquals('', $this->loader->locateFile($file, 'Views')); - } + $this->assertEquals('', $this->loader->locateFile($file, 'Views')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSearchSimple() - { - $expected = rtrim(APPPATH, '/') . '/Config/App.php'; + public function testSearchSimple() + { + $expected = rtrim(APPPATH, '/') . '/Config/App.php'; - $foundFiles = $this->loader->search('Config/App.php'); + $foundFiles = $this->loader->search('Config/App.php'); - $this->assertEquals($expected, $foundFiles[0]); - } + $this->assertEquals($expected, $foundFiles[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSearchWithFileExtension() - { - $expected = rtrim(APPPATH, '/') . '/Config/App.php'; + public function testSearchWithFileExtension() + { + $expected = rtrim(APPPATH, '/') . '/Config/App.php'; - $foundFiles = $this->loader->search('Config/App', 'php'); + $foundFiles = $this->loader->search('Config/App', 'php'); - $this->assertEquals($expected, $foundFiles[0]); - } + $this->assertEquals($expected, $foundFiles[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSearchWithMultipleFilesFound() - { - $foundFiles = $this->loader->search('index', 'html'); + public function testSearchWithMultipleFilesFound() + { + $foundFiles = $this->loader->search('index', 'html'); - $expected = rtrim(APPPATH, '/') . '/index.html'; - $this->assertContains($expected, $foundFiles); + $expected = rtrim(APPPATH, '/') . '/index.html'; + $this->assertContains($expected, $foundFiles); - $expected = rtrim(BASEPATH, '/') . '/index.html'; - $this->assertContains($expected, $foundFiles); - } + $expected = rtrim(BASEPATH, '/') . '/index.html'; + $this->assertContains($expected, $foundFiles); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSearchForFileNotExist() - { - $foundFiles = $this->loader->search('Views/Fake.html'); + public function testSearchForFileNotExist() + { + $foundFiles = $this->loader->search('Views/Fake.html'); - $this->assertArrayNotHasKey(0, $foundFiles); - } + $this->assertArrayNotHasKey(0, $foundFiles); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListFilesSimple() - { - $files = $this->loader->listFiles('Config/'); + public function testListFilesSimple() + { + $files = $this->loader->listFiles('Config/'); - $expectedWin = APPPATH . 'Config\App.php'; - $expectedLin = APPPATH . 'Config/App.php'; - $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); - } + $expectedWin = APPPATH . 'Config\App.php'; + $expectedLin = APPPATH . 'Config/App.php'; + $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListFilesWithFileAsInput() - { - $files = $this->loader->listFiles('Config/App.php'); + public function testListFilesWithFileAsInput() + { + $files = $this->loader->listFiles('Config/App.php'); - $this->assertEmpty($files); - } + $this->assertEmpty($files); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListFilesFromMultipleDir() - { - $files = $this->loader->listFiles('Filters/'); + public function testListFilesFromMultipleDir() + { + $files = $this->loader->listFiles('Filters/'); - $expectedWin = APPPATH . 'Filters\DebugToolbar.php'; - $expectedLin = APPPATH . 'Filters/DebugToolbar.php'; - $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); + $expectedWin = APPPATH . 'Filters\DebugToolbar.php'; + $expectedLin = APPPATH . 'Filters/DebugToolbar.php'; + $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); - $expectedWin = BASEPATH . 'Filters\Filters.php'; - $expectedLin = BASEPATH . 'Filters/Filters.php'; - $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); - } + $expectedWin = BASEPATH . 'Filters\Filters.php'; + $expectedLin = BASEPATH . 'Filters/Filters.php'; + $this->assertTrue(in_array($expectedWin, $files) || in_array($expectedLin, $files)); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListFilesWithPathNotExist() - { - $files = $this->loader->listFiles('Fake/'); + public function testListFilesWithPathNotExist() + { + $files = $this->loader->listFiles('Fake/'); - $this->assertEmpty($files); - } + $this->assertEmpty($files); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListFilesWithoutPath() - { - $files = $this->loader->listFiles(''); + public function testListFilesWithoutPath() + { + $files = $this->loader->listFiles(''); - $this->assertEmpty($files); - } + $this->assertEmpty($files); + } - public function testFindQNameFromPathSimple() - { - $ClassName = $this->loader->findQualifiedNameFromPath('system/HTTP/Header.php'); - $expected = '\Sys\HTTP\Header'; + public function testFindQNameFromPathSimple() + { + $ClassName = $this->loader->findQualifiedNameFromPath('system/HTTP/Header.php'); + $expected = '\Sys\HTTP\Header'; - $this->assertEquals($expected, $ClassName); - } + $this->assertEquals($expected, $ClassName); + } - public function testFindQNameFromPathWithNumericNamespace() - { - $ClassName = $this->loader->findQualifiedNameFromPath('application/Config/App.php'); + public function testFindQNameFromPathWithNumericNamespace() + { + $ClassName = $this->loader->findQualifiedNameFromPath('application/Config/App.php'); - $this->assertNull($ClassName); - } + $this->assertNull($ClassName); + } - public function testFindQNameFromPathWithFileNotExist() - { - $ClassName = $this->loader->findQualifiedNameFromPath('modules/blog/Views/index.php'); + public function testFindQNameFromPathWithFileNotExist() + { + $ClassName = $this->loader->findQualifiedNameFromPath('modules/blog/Views/index.php'); - $this->assertNull($ClassName); - } + $this->assertNull($ClassName); + } - public function testFindQNameFromPathWithoutCorrespondingNamespace() - { - $ClassName = $this->loader->findQualifiedNameFromPath('tests/system/CodeIgniterTest.php'); + public function testFindQNameFromPathWithoutCorrespondingNamespace() + { + $ClassName = $this->loader->findQualifiedNameFromPath('tests/system/CodeIgniterTest.php'); - $this->assertNull($ClassName); - } + $this->assertNull($ClassName); + } } diff --git a/tests/system/CLI/CLITest.php b/tests/system/CLI/CLITest.php index df1d9746ecc4..9bed10319448 100644 --- a/tests/system/CLI/CLITest.php +++ b/tests/system/CLI/CLITest.php @@ -2,97 +2,97 @@ class CLITest extends \CIUnitTestCase { - private $stream_filter; - - public function setUp() - { - CLITestStreamFilter::$buffer = ''; - $this->stream_filter = stream_filter_append(STDOUT, 'CLITestStreamFilter'); - } - - public function tearDown() - { - stream_filter_remove($this->stream_filter); - } - - public function testNew() - { - $actual = new CLI(); - $this->assertInstanceOf(CLI::class, $actual); - } - - public function testBeep() - { - $this->expectOutputString("\x07"); - CLI::beep(); - } - - public function testBeep4() - { - $this->expectOutputString("\x07\x07\x07\x07"); - CLI::beep(4); - } - - public function testWait() - { - $time = time(); - CLI::wait(1, true); - $this->assertEquals(1, time() - $time); - - $time = time(); - CLI::wait(1); - $this->assertEquals(1, time() - $time); - } - - public function testIsWindows() - { - $this->assertEquals(('\\' === DIRECTORY_SEPARATOR), CLI::isWindows()); - $this->assertEquals(defined('PHP_WINDOWS_VERSION_MAJOR'), CLI::isWindows()); - } - - public function testNewLine() - { - $this->expectOutputString(''); - CLI::newLine(); - } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Invalid foreground color: Foreground - */ - public function testColorExceptionForeground() - { - CLI::color('test', 'Foreground'); - } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Invalid background color: Background - */ - public function testColorExceptionBackground() - { - CLI::color('test', 'white', 'Background'); - } - - public function testColor() - { - $this->assertEquals("\033[1;37m\033[42m\033[4mtest\033[0m", CLI::color('test', 'white', 'green', 'underline')); - } - - public function testShowProgress() - { - CLI::write('first.'); - CLI::showProgress(1, 20); - CLI::showProgress(10, 20); - CLI::showProgress(20, 20); - CLI::write('second.'); - CLI::showProgress(1, 20); - CLI::showProgress(10, 20); - CLI::showProgress(20, 20); - CLI::write('third.'); - CLI::showProgress(1, 20); - - $expected = <<stream_filter = stream_filter_append(STDOUT, 'CLITestStreamFilter'); + } + + public function tearDown() + { + stream_filter_remove($this->stream_filter); + } + + public function testNew() + { + $actual = new CLI(); + $this->assertInstanceOf(CLI::class, $actual); + } + + public function testBeep() + { + $this->expectOutputString("\x07"); + CLI::beep(); + } + + public function testBeep4() + { + $this->expectOutputString("\x07\x07\x07\x07"); + CLI::beep(4); + } + + public function testWait() + { + $time = time(); + CLI::wait(1, true); + $this->assertEquals(1, time() - $time); + + $time = time(); + CLI::wait(1); + $this->assertEquals(1, time() - $time); + } + + public function testIsWindows() + { + $this->assertEquals(('\\' === DIRECTORY_SEPARATOR), CLI::isWindows()); + $this->assertEquals(defined('PHP_WINDOWS_VERSION_MAJOR'), CLI::isWindows()); + } + + public function testNewLine() + { + $this->expectOutputString(''); + CLI::newLine(); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Invalid foreground color: Foreground + */ + public function testColorExceptionForeground() + { + CLI::color('test', 'Foreground'); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Invalid background color: Background + */ + public function testColorExceptionBackground() + { + CLI::color('test', 'white', 'Background'); + } + + public function testColor() + { + $this->assertEquals("\033[1;37m\033[42m\033[4mtest\033[0m", CLI::color('test', 'white', 'green', 'underline')); + } + + public function testShowProgress() + { + CLI::write('first.'); + CLI::showProgress(1, 20); + CLI::showProgress(10, 20); + CLI::showProgress(20, 20); + CLI::write('second.'); + CLI::showProgress(1, 20); + CLI::showProgress(10, 20); + CLI::showProgress(20, 20); + CLI::write('third.'); + CLI::showProgress(1, 20); + + $expected = <<assertEquals($expected, CLITestStreamFilter::$buffer); - } + $this->assertEquals($expected, CLITestStreamFilter::$buffer); + } - public function testShowProgressWithoutBar() - { - CLI::write('first.'); - CLI::showProgress(false, 20); - CLI::showProgress(false, 20); - CLI::showProgress(false, 20); + public function testShowProgressWithoutBar() + { + CLI::write('first.'); + CLI::showProgress(false, 20); + CLI::showProgress(false, 20); + CLI::showProgress(false, 20); - $expected = <<assertEquals($expected, CLITestStreamFilter::$buffer); - } - - public function testWrap() - { - $this->assertEquals('', CLI::wrap('')); - $this->assertEquals('1234'. PHP_EOL .' 5678'. PHP_EOL .' 90'. PHP_EOL .' abc'. PHP_EOL .' de'. PHP_EOL .' fghij'. PHP_EOL .' 0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', 5, 1)); - $this->assertEquals('1234 5678 90'. PHP_EOL .' abc de fghij'. PHP_EOL .' 0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', 999, 2)); - $this->assertEquals('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321')); - } - - /** - * @dataProvider tableProvider - * - * @param array $tbody - * @param array $thead - * @param array $expected - */ - public function testTable($tbody, $thead, $expected) - { - CLI::table($tbody, $thead); - $this->assertEquals(CLITestStreamFilter::$buffer, $expected); - } - - public function tableProvider() - { - $head = ['ID', 'Title']; - $one_row = [['id' => 1, 'foo' => 'bar']]; - $many_rows = [ - ['id' => 1, 'foo' => 'bar'], - ['id' => 2, 'foo' => 'bar * 2'], - ['id' => 3, 'foo' => 'bar + bar + bar'], - ]; - - return [ - [$one_row, [], "+---+-----+\n" . - "| 1 | bar |\n" . - "+---+-----+\n"], - [$one_row, $head, "+----+-------+\n" . - "| ID | Title |\n" . - "+----+-------+\n" . - "| 1 | bar |\n" . - "+----+-------+\n"], - [$many_rows, [], "+---+-----------------+\n" . - "| 1 | bar |\n" . - "| 2 | bar * 2 |\n" . - "| 3 | bar + bar + bar |\n" . - "+---+-----------------+\n"], - [$many_rows, $head, "+----+-----------------+\n" . - "| ID | Title |\n" . - "+----+-----------------+\n" . - "| 1 | bar |\n" . - "| 2 | bar * 2 |\n" . - "| 3 | bar + bar + bar |\n" . - "+----+-----------------+\n"], - ]; - } + $this->assertEquals($expected, CLITestStreamFilter::$buffer); + } + + public function testWrap() + { + $this->assertEquals('', CLI::wrap('')); + $this->assertEquals('1234'. PHP_EOL .' 5678'. PHP_EOL .' 90'. PHP_EOL .' abc'. PHP_EOL .' de'. PHP_EOL .' fghij'. PHP_EOL .' 0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', 5, 1)); + $this->assertEquals('1234 5678 90'. PHP_EOL .' abc de fghij'. PHP_EOL .' 0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', 999, 2)); + $this->assertEquals('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321', CLI::wrap('1234 5678 90'. PHP_EOL .'abc de fghij'. PHP_EOL .'0987654321')); + } + + /** + * @dataProvider tableProvider + * + * @param array $tbody + * @param array $thead + * @param array $expected + */ + public function testTable($tbody, $thead, $expected) + { + CLI::table($tbody, $thead); + $this->assertEquals(CLITestStreamFilter::$buffer, $expected); + } + + public function tableProvider() + { + $head = ['ID', 'Title']; + $one_row = [['id' => 1, 'foo' => 'bar']]; + $many_rows = [ + ['id' => 1, 'foo' => 'bar'], + ['id' => 2, 'foo' => 'bar * 2'], + ['id' => 3, 'foo' => 'bar + bar + bar'], + ]; + + return [ + [$one_row, [], "+---+-----+\n" . + "| 1 | bar |\n" . + "+---+-----+\n"], + [$one_row, $head, "+----+-------+\n" . + "| ID | Title |\n" . + "+----+-------+\n" . + "| 1 | bar |\n" . + "+----+-------+\n"], + [$many_rows, [], "+---+-----------------+\n" . + "| 1 | bar |\n" . + "| 2 | bar * 2 |\n" . + "| 3 | bar + bar + bar |\n" . + "+---+-----------------+\n"], + [$many_rows, $head, "+----+-----------------+\n" . + "| ID | Title |\n" . + "+----+-----------------+\n" . + "| 1 | bar |\n" . + "| 2 | bar * 2 |\n" . + "| 3 | bar + bar + bar |\n" . + "+----+-----------------+\n"], + ]; + } } class CLITestStreamFilter extends \php_user_filter { - public static $buffer = ''; - - public function filter($in, $out, &$consumed, $closing) - { - while ($bucket = stream_bucket_make_writeable($in)) { - self::$buffer .= $bucket->data; - $consumed += $bucket->datalen; - } - return PSFS_PASS_ON; - } + public static $buffer = ''; + + public function filter($in, $out, &$consumed, $closing) + { + while ($bucket = stream_bucket_make_writeable($in)) { + self::$buffer .= $bucket->data; + $consumed += $bucket->datalen; + } + return PSFS_PASS_ON; + } } stream_filter_register('CLITestStreamFilter', 'CodeIgniter\CLI\CLITestStreamFilter'); diff --git a/tests/system/Cache/CacheFactoryTest.php b/tests/system/Cache/CacheFactoryTest.php index 3eb9403ae3e9..4721e168670f 100644 --- a/tests/system/Cache/CacheFactoryTest.php +++ b/tests/system/Cache/CacheFactoryTest.php @@ -2,88 +2,88 @@ class CacheFactoryTest extends \CIUnitTestCase { - private static $directory = 'CacheFactory'; - private $cacheFactory; - private $config; - - public function setUp() - { - $this->cacheFactory = new CacheFactory(); - - //Initialize path - $this->config = new \Config\Cache(); - $this->config->storePath .= self::$directory; - } - - public function tearDown() - { - if (is_dir($this->config->storePath)) { - chmod($this->config->storePath, 0777); - rmdir($this->config->storePath); - } - } - - public function testNew() - { - $this->assertInstanceOf(CacheFactory::class, $this->cacheFactory); - } - - /** - * @expectedException \CodeIgniter\Cache\Exceptions\CacheException - * @expectedExceptionMessage Cache config must have an array of $validHandlers. - */ - public function testGetHandlerExceptionCacheInvalidHandlers() - { - $this->config->validHandlers = null; - - $this->cacheFactory->getHandler($this->config); - } - - /** - * @expectedException \CodeIgniter\Cache\Exceptions\CacheException - * @expectedExceptionMessage Cache config must have a handler and backupHandler set. - */ - public function testGetHandlerExceptionCacheNoBackup() - { - $this->config->backupHandler = null; - - $this->cacheFactory->getHandler($this->config); - } - - /** - * @expectedException \CodeIgniter\Cache\Exceptions\CacheException - * @expectedExceptionMessage Cache config must have a handler and backupHandler set. - */ - public function testGetHandlerExceptionCacheNoHandler() - { - $this->config->handler = null; - - $this->cacheFactory->getHandler($this->config); - } - - /** - * @expectedException \CodeIgniter\Cache\Exceptions\CacheException - * @expectedExceptionMessage Cache config has an invalid handler or backup handler specified. - */ - public function testGetHandlerExceptionCacheHandlerNotFound() - { - unset($this->config->validHandlers[$this->config->handler]); - - $this->cacheFactory->getHandler($this->config); - } - - public function testGetDummyHandler() - { - if (!is_dir($this->config->storePath)) { - mkdir($this->config->storePath, 0555, true); - } - - $this->config->handler = 'dummy'; - - $this->assertInstanceOf(\CodeIgniter\Cache\Handlers\DummyHandler::class, $this->cacheFactory->getHandler($this->config)); - - //Initialize path - $this->config = new \Config\Cache(); - $this->config->storePath .= self::$directory; - } + private static $directory = 'CacheFactory'; + private $cacheFactory; + private $config; + + public function setUp() + { + $this->cacheFactory = new CacheFactory(); + + //Initialize path + $this->config = new \Config\Cache(); + $this->config->storePath .= self::$directory; + } + + public function tearDown() + { + if (is_dir($this->config->storePath)) { + chmod($this->config->storePath, 0777); + rmdir($this->config->storePath); + } + } + + public function testNew() + { + $this->assertInstanceOf(CacheFactory::class, $this->cacheFactory); + } + + /** + * @expectedException \CodeIgniter\Cache\Exceptions\CacheException + * @expectedExceptionMessage Cache config must have an array of $validHandlers. + */ + public function testGetHandlerExceptionCacheInvalidHandlers() + { + $this->config->validHandlers = null; + + $this->cacheFactory->getHandler($this->config); + } + + /** + * @expectedException \CodeIgniter\Cache\Exceptions\CacheException + * @expectedExceptionMessage Cache config must have a handler and backupHandler set. + */ + public function testGetHandlerExceptionCacheNoBackup() + { + $this->config->backupHandler = null; + + $this->cacheFactory->getHandler($this->config); + } + + /** + * @expectedException \CodeIgniter\Cache\Exceptions\CacheException + * @expectedExceptionMessage Cache config must have a handler and backupHandler set. + */ + public function testGetHandlerExceptionCacheNoHandler() + { + $this->config->handler = null; + + $this->cacheFactory->getHandler($this->config); + } + + /** + * @expectedException \CodeIgniter\Cache\Exceptions\CacheException + * @expectedExceptionMessage Cache config has an invalid handler or backup handler specified. + */ + public function testGetHandlerExceptionCacheHandlerNotFound() + { + unset($this->config->validHandlers[$this->config->handler]); + + $this->cacheFactory->getHandler($this->config); + } + + public function testGetDummyHandler() + { + if (!is_dir($this->config->storePath)) { + mkdir($this->config->storePath, 0555, true); + } + + $this->config->handler = 'dummy'; + + $this->assertInstanceOf(\CodeIgniter\Cache\Handlers\DummyHandler::class, $this->cacheFactory->getHandler($this->config)); + + //Initialize path + $this->config = new \Config\Cache(); + $this->config->storePath .= self::$directory; + } } diff --git a/tests/system/Cache/Handlers/DummyHandlerTest.php b/tests/system/Cache/Handlers/DummyHandlerTest.php index 8c19a6ebc5f2..8526ccdc1692 100644 --- a/tests/system/Cache/Handlers/DummyHandlerTest.php +++ b/tests/system/Cache/Handlers/DummyHandlerTest.php @@ -2,61 +2,61 @@ class DummyHandlerTest extends \CIUnitTestCase { - private $dummyHandler; - - public function setUp() - { - $this->dummyHandler = new DummyHandler(); - $this->dummyHandler->initialize(); - } - - public function testNew() - { - $this->assertInstanceOf(DummyHandler::class, $this->dummyHandler); - } - - public function testGet() - { - $this->assertNull($this->dummyHandler->get('key')); - } - - public function testSave() - { - $this->assertTrue($this->dummyHandler->save('key', 'value')); - } - - public function testDelete() - { - $this->assertTrue($this->dummyHandler->delete('key')); - } - - public function testIncrement() - { - $this->assertTrue($this->dummyHandler->increment('key')); - } - - public function testDecrement() - { - $this->assertTrue($this->dummyHandler->decrement('key')); - } - - public function testClean() - { - $this->assertTrue($this->dummyHandler->clean()); - } - - public function testGetCacheInfo() - { - $this->assertNull($this->dummyHandler->getCacheInfo()); - } - - public function testGetMetaData() - { - $this->assertNull($this->dummyHandler->getMetaData('key')); - } - - public function testIsSupported() - { - $this->assertTrue($this->dummyHandler->isSupported()); - } + private $dummyHandler; + + public function setUp() + { + $this->dummyHandler = new DummyHandler(); + $this->dummyHandler->initialize(); + } + + public function testNew() + { + $this->assertInstanceOf(DummyHandler::class, $this->dummyHandler); + } + + public function testGet() + { + $this->assertNull($this->dummyHandler->get('key')); + } + + public function testSave() + { + $this->assertTrue($this->dummyHandler->save('key', 'value')); + } + + public function testDelete() + { + $this->assertTrue($this->dummyHandler->delete('key')); + } + + public function testIncrement() + { + $this->assertTrue($this->dummyHandler->increment('key')); + } + + public function testDecrement() + { + $this->assertTrue($this->dummyHandler->decrement('key')); + } + + public function testClean() + { + $this->assertTrue($this->dummyHandler->clean()); + } + + public function testGetCacheInfo() + { + $this->assertNull($this->dummyHandler->getCacheInfo()); + } + + public function testGetMetaData() + { + $this->assertNull($this->dummyHandler->getMetaData('key')); + } + + public function testIsSupported() + { + $this->assertTrue($this->dummyHandler->isSupported()); + } } diff --git a/tests/system/Cache/Handlers/FileHandlerTest.php b/tests/system/Cache/Handlers/FileHandlerTest.php index 592869eafebb..a8887cc072ec 100644 --- a/tests/system/Cache/Handlers/FileHandlerTest.php +++ b/tests/system/Cache/Handlers/FileHandlerTest.php @@ -1,200 +1,200 @@ config = new \Config\Cache(); - $this->config->storePath .= self::$directory; - - if (! is_dir($this->config->storePath)) - { - mkdir($this->config->storePath, 0777, true); - } - - $this->fileHandler = new FileHandler($this->config); - $this->fileHandler->initialize(); - } - - public function tearDown() - { - if (is_dir($this->config->storePath)) - { - chmod($this->config->storePath, 0777); - - foreach (self::getKeyArray() as $key) - { - if (is_file($this->config->storePath.DIRECTORY_SEPARATOR.$key)) - { - chmod($this->config->storePath.DIRECTORY_SEPARATOR.$key, 0777); - unlink($this->config->storePath.DIRECTORY_SEPARATOR.$key); - } - } - - rmdir($this->config->storePath); - } - } - - public function testNew() - { - $this->assertInstanceOf(FileHandler::class, $this->fileHandler); - } - - public function testSetDefaultPath() - { - //Initialize path - $config = new \Config\Cache(); - $config->storePath = null; - - $this->fileHandler = new FileHandler($config); - $this->fileHandler->initialize(); - - $this->assertInstanceOf(FileHandler::class, $this->fileHandler); - } - - public function testGet() - { - $this->fileHandler->save(self::$key1, 'value', 1); - - $this->assertSame('value', $this->fileHandler->get(self::$key1)); - $this->assertFalse($this->fileHandler->get(self::$dummy)); - - \CodeIgniter\CLI\CLI::wait(2); - $this->assertFalse($this->fileHandler->get(self::$key1)); - } - - public function testSave() - { - $this->assertTrue($this->fileHandler->save(self::$key1, 'value')); - - // The FileHandler always ensures the directory is writable... - chmod($this->config->storePath, 0444); - $this->assertTrue($this->fileHandler->save(self::$key2, 'value')); - } - - public function testDelete() - { - $this->fileHandler->save(self::$key1, 'value'); - - $this->assertTrue($this->fileHandler->delete(self::$key1)); - $this->assertFalse($this->fileHandler->delete(self::$dummy)); - } - - public function testIncrement() - { - $this->fileHandler->save(self::$key1, 1); - $this->fileHandler->save(self::$key2, 'value'); - - $this->assertSame(11, $this->fileHandler->increment(self::$key1, 10)); - $this->assertFalse($this->fileHandler->increment(self::$key2, 10)); - $this->assertSame(10, $this->fileHandler->increment(self::$key3, 10)); - } - - public function testDecrement() - { - $this->fileHandler->save(self::$key1, 10); - $this->fileHandler->save(self::$key2, 'value'); - $this->fileHandler->save(self::$key3, 0); - - $this->assertSame(9, $this->fileHandler->decrement(self::$key1, 1)); - $this->assertFalse($this->fileHandler->decrement(self::$key2, 1)); - $this->assertSame(-1, $this->fileHandler->decrement(self::$key3, 1)); - } - - public function testClean() - { - $this->fileHandler->save(self::$key1, 1); - $this->fileHandler->save(self::$key2, 'value'); - - $this->assertTrue($this->fileHandler->clean()); - - $this->fileHandler->save(self::$key1, 1); - $this->fileHandler->save(self::$key2, 'value'); - } - - public function testGetMetaData() - { - $time = time(); - $this->fileHandler->save(self::$key1, 'value'); - - $this->assertFalse($this->fileHandler->getMetaData(self::$dummy)); - - $actual = $this->fileHandler->getMetaData(self::$key1); - $this->assertLessThanOrEqual(60, $actual['expire']-$time); - $this->assertLessThanOrEqual(0, $actual['mtime']-$time); - $this->assertSame('value', $actual['data']); - } - - public function testIsSupported() - { - $this->assertTrue($this->fileHandler->isSupported()); - } - - //-------------------------------------------------------------------- - - public function testFileHandler() - { - $fileHandler = new BaseTestFileHandler(); - - $actual = $fileHandler->getFileInfoTest(); - - $this->assertArrayHasKey('server_path', $actual); - $this->assertArrayHasKey('size', $actual); - $this->assertArrayHasKey('date', $actual); - $this->assertArrayHasKey('readable', $actual); - $this->assertArrayHasKey('writable', $actual); - $this->assertArrayHasKey('executable', $actual); - $this->assertArrayHasKey('fileperms', $actual); - } + private static $directory = 'FileHandler'; + private static $key1 = 'key1'; + private static $key2 = 'key2'; + private static $key3 = 'key3'; + + private static function getKeyArray() + { + return [ + self::$key1, + self::$key2, + self::$key3, + ]; + } + + private static $dummy = 'dymmy'; + private $fileHandler; + private $config; + + public function setUp() + { + //Initialize path + $this->config = new \Config\Cache(); + $this->config->storePath .= self::$directory; + + if (! is_dir($this->config->storePath)) + { + mkdir($this->config->storePath, 0777, true); + } + + $this->fileHandler = new FileHandler($this->config); + $this->fileHandler->initialize(); + } + + public function tearDown() + { + if (is_dir($this->config->storePath)) + { + chmod($this->config->storePath, 0777); + + foreach (self::getKeyArray() as $key) + { + if (is_file($this->config->storePath.DIRECTORY_SEPARATOR.$key)) + { + chmod($this->config->storePath.DIRECTORY_SEPARATOR.$key, 0777); + unlink($this->config->storePath.DIRECTORY_SEPARATOR.$key); + } + } + + rmdir($this->config->storePath); + } + } + + public function testNew() + { + $this->assertInstanceOf(FileHandler::class, $this->fileHandler); + } + + public function testSetDefaultPath() + { + //Initialize path + $config = new \Config\Cache(); + $config->storePath = null; + + $this->fileHandler = new FileHandler($config); + $this->fileHandler->initialize(); + + $this->assertInstanceOf(FileHandler::class, $this->fileHandler); + } + + public function testGet() + { + $this->fileHandler->save(self::$key1, 'value', 1); + + $this->assertSame('value', $this->fileHandler->get(self::$key1)); + $this->assertFalse($this->fileHandler->get(self::$dummy)); + + \CodeIgniter\CLI\CLI::wait(2); + $this->assertFalse($this->fileHandler->get(self::$key1)); + } + + public function testSave() + { + $this->assertTrue($this->fileHandler->save(self::$key1, 'value')); + + // The FileHandler always ensures the directory is writable... + chmod($this->config->storePath, 0444); + $this->assertTrue($this->fileHandler->save(self::$key2, 'value')); + } + + public function testDelete() + { + $this->fileHandler->save(self::$key1, 'value'); + + $this->assertTrue($this->fileHandler->delete(self::$key1)); + $this->assertFalse($this->fileHandler->delete(self::$dummy)); + } + + public function testIncrement() + { + $this->fileHandler->save(self::$key1, 1); + $this->fileHandler->save(self::$key2, 'value'); + + $this->assertSame(11, $this->fileHandler->increment(self::$key1, 10)); + $this->assertFalse($this->fileHandler->increment(self::$key2, 10)); + $this->assertSame(10, $this->fileHandler->increment(self::$key3, 10)); + } + + public function testDecrement() + { + $this->fileHandler->save(self::$key1, 10); + $this->fileHandler->save(self::$key2, 'value'); + $this->fileHandler->save(self::$key3, 0); + + $this->assertSame(9, $this->fileHandler->decrement(self::$key1, 1)); + $this->assertFalse($this->fileHandler->decrement(self::$key2, 1)); + $this->assertSame(-1, $this->fileHandler->decrement(self::$key3, 1)); + } + + public function testClean() + { + $this->fileHandler->save(self::$key1, 1); + $this->fileHandler->save(self::$key2, 'value'); + + $this->assertTrue($this->fileHandler->clean()); + + $this->fileHandler->save(self::$key1, 1); + $this->fileHandler->save(self::$key2, 'value'); + } + + public function testGetMetaData() + { + $time = time(); + $this->fileHandler->save(self::$key1, 'value'); + + $this->assertFalse($this->fileHandler->getMetaData(self::$dummy)); + + $actual = $this->fileHandler->getMetaData(self::$key1); + $this->assertLessThanOrEqual(60, $actual['expire']-$time); + $this->assertLessThanOrEqual(0, $actual['mtime']-$time); + $this->assertSame('value', $actual['data']); + } + + public function testIsSupported() + { + $this->assertTrue($this->fileHandler->isSupported()); + } + + //-------------------------------------------------------------------- + + public function testFileHandler() + { + $fileHandler = new BaseTestFileHandler(); + + $actual = $fileHandler->getFileInfoTest(); + + $this->assertArrayHasKey('server_path', $actual); + $this->assertArrayHasKey('size', $actual); + $this->assertArrayHasKey('date', $actual); + $this->assertArrayHasKey('readable', $actual); + $this->assertArrayHasKey('writable', $actual); + $this->assertArrayHasKey('executable', $actual); + $this->assertArrayHasKey('fileperms', $actual); + } } final class BaseTestFileHandler extends FileHandler { - private static $directory = 'FileHandler'; - private $config; - - public function __construct() - { - $this->config = new \Config\Cache(); - $this->config->storePath .= self::$directory; - - parent::__construct($this->config); - } - - public function getFileInfoTest() - { - return $this->getFileInfo($this->config->storePath, [ - 'name', - 'server_path', - 'size', - 'date', - 'readable', - 'writable', - 'executable', - 'fileperms', - ]); - } + private static $directory = 'FileHandler'; + private $config; + + public function __construct() + { + $this->config = new \Config\Cache(); + $this->config->storePath .= self::$directory; + + parent::__construct($this->config); + } + + public function getFileInfoTest() + { + return $this->getFileInfo($this->config->storePath, [ + 'name', + 'server_path', + 'size', + 'date', + 'readable', + 'writable', + 'executable', + 'fileperms', + ]); + } } diff --git a/tests/system/Cache/Handlers/MemcachedHandlerTest.php b/tests/system/Cache/Handlers/MemcachedHandlerTest.php index f8ba8b1480c1..3beca82a25bb 100644 --- a/tests/system/Cache/Handlers/MemcachedHandlerTest.php +++ b/tests/system/Cache/Handlers/MemcachedHandlerTest.php @@ -2,136 +2,136 @@ class MemcachedHandlerTest extends \CIUnitTestCase { - private $memcachedHandler; - private static $key1 = 'key1'; - private static $key2 = 'key2'; - private static $key3 = 'key3'; - private static function getKeyArray() - { - return [ - self::$key1, self::$key2, self::$key3 - ]; - } - - private static $dummy = 'dymmy'; - private $config; - - public function setUp() - { - $this->config = new \Config\Cache(); - - $this->memcachedHandler = new MemcachedHandler($this->config->memcached); - if (!$this->memcachedHandler->isSupported()) { - $this->markTestSkipped('Not support memcached and memcache'); - } - - $this->memcachedHandler->initialize(); - } - - public function tearDown() - { - foreach (self::getKeyArray() as $key) { - $this->memcachedHandler->delete($key); - } - } - - public function testNew() - { - $this->assertInstanceOf(MemcachedHandler::class, $this->memcachedHandler); - } - - public function testGet() - { - $this->memcachedHandler->save(self::$key1, 'value', 1); - - $this->assertSame('value', $this->memcachedHandler->get(self::$key1)); - $this->assertFalse($this->memcachedHandler->get(self::$dummy)); - - \CodeIgniter\CLI\CLI::wait(2); - $this->assertFalse($this->memcachedHandler->get(self::$key1)); - } - - public function testSave() - { - $this->assertTrue($this->memcachedHandler->save(self::$key1, 'value')); - } - - public function testDelete() - { - $this->memcachedHandler->save(self::$key1, 'value'); - - $this->assertTrue($this->memcachedHandler->delete(self::$key1)); - $this->assertFalse($this->memcachedHandler->delete(self::$dummy)); - } - - public function testIncrement() - { - $this->memcachedHandler->save(self::$key1, 1); - - $this->assertFalse($this->memcachedHandler->increment(self::$key1, 10)); - - $config = new \Config\Cache(); - $config->memcached['raw'] = true; - $memcachedHandler = new MemcachedHandler($config->memcached); - $memcachedHandler->initialize(); - - $memcachedHandler->save(self::$key1, 1); - $memcachedHandler->save(self::$key2, 'value'); - - $this->assertSame(11, $memcachedHandler->increment(self::$key1, 10)); - $this->assertFalse($memcachedHandler->increment(self::$key2, 10)); - $this->assertSame(10, $memcachedHandler->increment(self::$key3, 10)); - } - - public function testDecrement() - { - $this->memcachedHandler->save(self::$key1, 10); - - $this->assertFalse($this->memcachedHandler->decrement(self::$key1, 1)); - - $config = new \Config\Cache(); - $config->memcached['raw'] = true; - $memcachedHandler = new MemcachedHandler($config->memcached); - $memcachedHandler->initialize(); - - $memcachedHandler->save(self::$key1, 10); - $memcachedHandler->save(self::$key2, 'value'); - - $this->assertSame(9, $memcachedHandler->decrement(self::$key1, 1)); - $this->assertFalse($memcachedHandler->decrement(self::$key2, 1)); - $this->assertSame(1, $memcachedHandler->decrement(self::$key3, 1)); - } - - public function testClean() - { - $this->memcachedHandler->save(self::$key1, 1); - $this->memcachedHandler->save(self::$key2, 'value'); - - $this->assertTrue($this->memcachedHandler->clean()); - } - - public function testGetCacheInfo() - { - $this->memcachedHandler->save(self::$key1, 'value'); - - $this->assertInternalType('array', $this->memcachedHandler->getCacheInfo()); - } - - public function testGetMetaData() - { - $time = time(); - $this->memcachedHandler->save(self::$key1, 'value'); - - $this->assertFalse($this->memcachedHandler->getMetaData(self::$dummy)); + private $memcachedHandler; + private static $key1 = 'key1'; + private static $key2 = 'key2'; + private static $key3 = 'key3'; + private static function getKeyArray() + { + return [ + self::$key1, self::$key2, self::$key3 + ]; + } + + private static $dummy = 'dymmy'; + private $config; + + public function setUp() + { + $this->config = new \Config\Cache(); + + $this->memcachedHandler = new MemcachedHandler($this->config->memcached); + if (!$this->memcachedHandler->isSupported()) { + $this->markTestSkipped('Not support memcached and memcache'); + } + + $this->memcachedHandler->initialize(); + } + + public function tearDown() + { + foreach (self::getKeyArray() as $key) { + $this->memcachedHandler->delete($key); + } + } + + public function testNew() + { + $this->assertInstanceOf(MemcachedHandler::class, $this->memcachedHandler); + } + + public function testGet() + { + $this->memcachedHandler->save(self::$key1, 'value', 1); + + $this->assertSame('value', $this->memcachedHandler->get(self::$key1)); + $this->assertFalse($this->memcachedHandler->get(self::$dummy)); + + \CodeIgniter\CLI\CLI::wait(2); + $this->assertFalse($this->memcachedHandler->get(self::$key1)); + } + + public function testSave() + { + $this->assertTrue($this->memcachedHandler->save(self::$key1, 'value')); + } + + public function testDelete() + { + $this->memcachedHandler->save(self::$key1, 'value'); + + $this->assertTrue($this->memcachedHandler->delete(self::$key1)); + $this->assertFalse($this->memcachedHandler->delete(self::$dummy)); + } + + public function testIncrement() + { + $this->memcachedHandler->save(self::$key1, 1); + + $this->assertFalse($this->memcachedHandler->increment(self::$key1, 10)); + + $config = new \Config\Cache(); + $config->memcached['raw'] = true; + $memcachedHandler = new MemcachedHandler($config->memcached); + $memcachedHandler->initialize(); + + $memcachedHandler->save(self::$key1, 1); + $memcachedHandler->save(self::$key2, 'value'); + + $this->assertSame(11, $memcachedHandler->increment(self::$key1, 10)); + $this->assertFalse($memcachedHandler->increment(self::$key2, 10)); + $this->assertSame(10, $memcachedHandler->increment(self::$key3, 10)); + } + + public function testDecrement() + { + $this->memcachedHandler->save(self::$key1, 10); + + $this->assertFalse($this->memcachedHandler->decrement(self::$key1, 1)); + + $config = new \Config\Cache(); + $config->memcached['raw'] = true; + $memcachedHandler = new MemcachedHandler($config->memcached); + $memcachedHandler->initialize(); + + $memcachedHandler->save(self::$key1, 10); + $memcachedHandler->save(self::$key2, 'value'); + + $this->assertSame(9, $memcachedHandler->decrement(self::$key1, 1)); + $this->assertFalse($memcachedHandler->decrement(self::$key2, 1)); + $this->assertSame(1, $memcachedHandler->decrement(self::$key3, 1)); + } + + public function testClean() + { + $this->memcachedHandler->save(self::$key1, 1); + $this->memcachedHandler->save(self::$key2, 'value'); + + $this->assertTrue($this->memcachedHandler->clean()); + } + + public function testGetCacheInfo() + { + $this->memcachedHandler->save(self::$key1, 'value'); + + $this->assertInternalType('array', $this->memcachedHandler->getCacheInfo()); + } + + public function testGetMetaData() + { + $time = time(); + $this->memcachedHandler->save(self::$key1, 'value'); + + $this->assertFalse($this->memcachedHandler->getMetaData(self::$dummy)); - $actual = $this->memcachedHandler->getMetaData(self::$key1); - $this->assertLessThanOrEqual(60, $actual['expire'] - $time); - $this->assertLessThanOrEqual(0, $actual['mtime'] - $time); - $this->assertSame('value', $actual['data']); - } - - public function testIsSupported() - { - $this->assertTrue($this->memcachedHandler->isSupported()); - } + $actual = $this->memcachedHandler->getMetaData(self::$key1); + $this->assertLessThanOrEqual(60, $actual['expire'] - $time); + $this->assertLessThanOrEqual(0, $actual['mtime'] - $time); + $this->assertSame('value', $actual['data']); + } + + public function testIsSupported() + { + $this->assertTrue($this->memcachedHandler->isSupported()); + } } diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index 91da1201322a..8ed19e5e208b 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -27,126 +27,126 @@ * 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 */ class RedisHandlerTest extends \CIUnitTestCase { - private $redisHandler; - private static $key1 = 'key1'; - private static $key2 = 'key2'; - private static $key3 = 'key3'; - private static function getKeyArray() - { - return [ - self::$key1, self::$key2, self::$key3 - ]; - } - - private static $dummy = 'dymmy'; - private $config; - - public function setUp() - { - $this->config = new \Config\Cache(); - - $this->redisHandler = new RedisHandler($this->config->redis); - if (!$this->redisHandler->isSupported()) { - $this->markTestSkipped('Not support redis'); - } - - $this->redisHandler->initialize(); - } - - public function tearDown() - { - foreach (self::getKeyArray() as $key) { - $this->redisHandler->delete($key); - } - } - - public function testNew() - { - $this->assertInstanceOf(RedisHandler::class, $this->redisHandler); - } - - public function testDestruct() - { - $this->redisHandler = new RedisHandler($this->config->redis); - $this->redisHandler->initialize(); - - $this->assertInstanceOf(RedisHandler::class, $this->redisHandler); - } - - - public function testGet() - { - $this->redisHandler->save(self::$key1, 'value', 1); - - $this->assertSame('value', $this->redisHandler->get(self::$key1)); - $this->assertFalse($this->redisHandler->get(self::$dummy)); - - \CodeIgniter\CLI\CLI::wait(2); - $this->assertFalse($this->redisHandler->get(self::$key1)); - } - - public function testSave() - { - $this->assertTrue($this->redisHandler->save(self::$key1, 'value')); - } - - public function testDelete() - { - $this->redisHandler->save(self::$key1, 'value'); - - $this->assertTrue($this->redisHandler->delete(self::$key1)); - $this->assertFalse($this->redisHandler->delete(self::$dummy)); - } - - //FIXME: I don't like all Hash logic very much. It's wasting memory. - //public function testIncrement() - //{ - //} - - //public function testDecrement() - //{ - //} - - public function testClean() - { - $this->redisHandler->save(self::$key1, 1); - $this->redisHandler->save(self::$key2, 'value'); - - $this->assertTrue($this->redisHandler->clean()); - } - - public function testGetCacheInfo() - { - $this->redisHandler->save(self::$key1, 'value'); - - $this->assertInternalType('array', $this->redisHandler->getCacheInfo()); - } - - public function testGetMetaData() - { - $time = time(); - $this->redisHandler->save(self::$key1, 'value'); - - $this->assertFalse($this->redisHandler->getMetaData(self::$dummy)); - - $actual = $this->redisHandler->getMetaData(self::$key1); - $this->assertLessThanOrEqual(60, $actual['expire'] - $time); - $this->assertLessThanOrEqual(0, $actual['mtime'] - $time); - $this->assertSame('value', $actual['data']); - } - - public function testIsSupported() - { - $this->assertTrue($this->redisHandler->isSupported()); - } + private $redisHandler; + private static $key1 = 'key1'; + private static $key2 = 'key2'; + private static $key3 = 'key3'; + private static function getKeyArray() + { + return [ + self::$key1, self::$key2, self::$key3 + ]; + } + + private static $dummy = 'dymmy'; + private $config; + + public function setUp() + { + $this->config = new \Config\Cache(); + + $this->redisHandler = new RedisHandler($this->config->redis); + if (!$this->redisHandler->isSupported()) { + $this->markTestSkipped('Not support redis'); + } + + $this->redisHandler->initialize(); + } + + public function tearDown() + { + foreach (self::getKeyArray() as $key) { + $this->redisHandler->delete($key); + } + } + + public function testNew() + { + $this->assertInstanceOf(RedisHandler::class, $this->redisHandler); + } + + public function testDestruct() + { + $this->redisHandler = new RedisHandler($this->config->redis); + $this->redisHandler->initialize(); + + $this->assertInstanceOf(RedisHandler::class, $this->redisHandler); + } + + + public function testGet() + { + $this->redisHandler->save(self::$key1, 'value', 1); + + $this->assertSame('value', $this->redisHandler->get(self::$key1)); + $this->assertFalse($this->redisHandler->get(self::$dummy)); + + \CodeIgniter\CLI\CLI::wait(2); + $this->assertFalse($this->redisHandler->get(self::$key1)); + } + + public function testSave() + { + $this->assertTrue($this->redisHandler->save(self::$key1, 'value')); + } + + public function testDelete() + { + $this->redisHandler->save(self::$key1, 'value'); + + $this->assertTrue($this->redisHandler->delete(self::$key1)); + $this->assertFalse($this->redisHandler->delete(self::$dummy)); + } + + //FIXME: I don't like all Hash logic very much. It's wasting memory. + //public function testIncrement() + //{ + //} + + //public function testDecrement() + //{ + //} + + public function testClean() + { + $this->redisHandler->save(self::$key1, 1); + $this->redisHandler->save(self::$key2, 'value'); + + $this->assertTrue($this->redisHandler->clean()); + } + + public function testGetCacheInfo() + { + $this->redisHandler->save(self::$key1, 'value'); + + $this->assertInternalType('array', $this->redisHandler->getCacheInfo()); + } + + public function testGetMetaData() + { + $time = time(); + $this->redisHandler->save(self::$key1, 'value'); + + $this->assertFalse($this->redisHandler->getMetaData(self::$dummy)); + + $actual = $this->redisHandler->getMetaData(self::$key1); + $this->assertLessThanOrEqual(60, $actual['expire'] - $time); + $this->assertLessThanOrEqual(0, $actual['mtime'] - $time); + $this->assertSame('value', $actual['data']); + } + + public function testIsSupported() + { + $this->assertTrue($this->redisHandler->isSupported()); + } } diff --git a/tests/system/Config/BaseConfigTest.php b/tests/system/Config/BaseConfigTest.php index 327d09dc01e3..e8f8273adb63 100644 --- a/tests/system/Config/BaseConfigTest.php +++ b/tests/system/Config/BaseConfigTest.php @@ -5,170 +5,170 @@ class BaseConfigTest extends CIUnitTestCase { - protected $fixturesFolder; - - //-------------------------------------------------------------------- - - public function setup() - { - $this->fixturesFolder = __DIR__ . '/fixtures'; - - if ( ! class_exists('SimpleConfig', false)) - { - require $this->fixturesFolder . '/SimpleConfig.php'; - } - if ( ! class_exists('RegistrarConfig', false)) - { - require $this->fixturesFolder . '/RegistrarConfig.php'; - } - if ( ! class_exists('RegistrarConfig2', false)) - { - require $this->fixturesFolder . '/RegistrarConfig2.php'; - } - if ( ! class_exists('RegistrarConfig3', false)) - { - require $this->fixturesFolder . '/RegistrarConfig3.php'; - } - } - - //-------------------------------------------------------------------- - - public function testBasicValues() - { - $dotenv = new DotEnv($this->fixturesFolder, '.env'); - $dotenv->load(); - $config = new \SimpleConfig(); - - $this->assertEquals('bar', $config->FOO); - // empty treated as boolean false - $this->assertEquals(false, $config->echo); - // 'true' should be treated as boolean true - $this->assertTrue($config->foxtrot); - // numbers should be treated properly - $this->assertEquals(18, $config->golf); - } - - //-------------------------------------------------------------------- - - public function testEnvironmentOverrides() - { - $dotenv = new DotEnv($this->fixturesFolder, '.env', 'z'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - // override config with ENV var - $this->assertEquals('pow', $config->alpha); - // config should not be over-written by wrongly named ENV var - $this->assertEquals('three', $config->charlie); - // override config with shortPrefix ENV var - $this->assertEquals('hubbahubba', $config->delta); - // incorrect env name should not inject property - $this->assertObjectNotHasAttribute('notthere', $config); - // same ENV var as property, but not namespaced, still over-rides - $this->assertEquals('kazaam', $config->bravo); - } - - //-------------------------------------------------------------------- - - public function testPrefixedValues() - { - $dotenv = new DotEnv($this->fixturesFolder, '.env'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - $this->assertEquals('baz', $config->onedeep); - } - - //-------------------------------------------------------------------- - - public function testPrefixedArrayValues() - { - $dotenv = new DotEnv($this->fixturesFolder, '.env'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - $this->assertEquals('ci4', $config->default['name']); - $this->assertEquals('Malcolm', $config->crew['captain']); - $this->assertEquals('Spock', $config->crew['science']); - $this->assertFalse(array_key_exists('pilot', $config->crew)); - $this->assertTrue($config->crew['comms']); - $this->assertFalse($config->crew['doctor']); - } - - //-------------------------------------------------------------------- - - public function testArrayValues() - { - $dotenv = new DotEnv($this->fixturesFolder, '.env'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - $this->assertEquals('complex', $config->simple['name']); - $this->assertEquals('foo', $config->first); - $this->assertEquals('bar', $config->second); - } - - //-------------------------------------------------------------------- - - public function testSetsDefaultValues() - { - $dotenv = new DotEnv($this->fixturesFolder, 'commented.env'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - $this->assertEquals('foo', $config->first); - $this->assertEquals('bar', $config->second); - } - - //-------------------------------------------------------------------- - - public function testRecognizesLooseValues() - { - $dotenv = new DotEnv($this->fixturesFolder, 'loose.env'); - $dotenv->load(); - - $config = new \SimpleConfig(); - - $this->assertEquals(0, $config->QZERO); - $this->assertSame("0", $config->QZEROSTR); - $this->assertEquals(" ", $config->QEMPTYSTR); - $this->assertFalse($config->QFALSE); - } - - //-------------------------------------------------------------------- - - public function testRegistrars() - { - $config = new \RegistrarConfig(); - - // no change to unmodified property - $this->assertEquals('bar', $config->foo); - // add to an existing array property - $this->assertEquals(['baz', 'first', 'second'], $config->bar); - // add a new property - $this->assertEquals('nice', $config->format); - // add a new array property - $this->assertEquals(['apple', 'banana'], $config->fruit); - } - - public function testBadRegistrar() - { - $this->expectException('RuntimeException'); - $config = new \RegistrarConfig2(); - $this->assertEquals('bar', $config->foo); - } - - // not very interesting, but useful for code coverage - public function testWorseRegistrar() - { - $config = new \RegistrarConfig3(); - // there should be no change - $this->assertEquals('bar', $config->foo); - } + protected $fixturesFolder; + + //-------------------------------------------------------------------- + + public function setup() + { + $this->fixturesFolder = __DIR__ . '/fixtures'; + + if ( ! class_exists('SimpleConfig', false)) + { + require $this->fixturesFolder . '/SimpleConfig.php'; + } + if ( ! class_exists('RegistrarConfig', false)) + { + require $this->fixturesFolder . '/RegistrarConfig.php'; + } + if ( ! class_exists('RegistrarConfig2', false)) + { + require $this->fixturesFolder . '/RegistrarConfig2.php'; + } + if ( ! class_exists('RegistrarConfig3', false)) + { + require $this->fixturesFolder . '/RegistrarConfig3.php'; + } + } + + //-------------------------------------------------------------------- + + public function testBasicValues() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env'); + $dotenv->load(); + $config = new \SimpleConfig(); + + $this->assertEquals('bar', $config->FOO); + // empty treated as boolean false + $this->assertEquals(false, $config->echo); + // 'true' should be treated as boolean true + $this->assertTrue($config->foxtrot); + // numbers should be treated properly + $this->assertEquals(18, $config->golf); + } + + //-------------------------------------------------------------------- + + public function testEnvironmentOverrides() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env', 'z'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + // override config with ENV var + $this->assertEquals('pow', $config->alpha); + // config should not be over-written by wrongly named ENV var + $this->assertEquals('three', $config->charlie); + // override config with shortPrefix ENV var + $this->assertEquals('hubbahubba', $config->delta); + // incorrect env name should not inject property + $this->assertObjectNotHasAttribute('notthere', $config); + // same ENV var as property, but not namespaced, still over-rides + $this->assertEquals('kazaam', $config->bravo); + } + + //-------------------------------------------------------------------- + + public function testPrefixedValues() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals('baz', $config->onedeep); + } + + //-------------------------------------------------------------------- + + public function testPrefixedArrayValues() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals('ci4', $config->default['name']); + $this->assertEquals('Malcolm', $config->crew['captain']); + $this->assertEquals('Spock', $config->crew['science']); + $this->assertFalse(array_key_exists('pilot', $config->crew)); + $this->assertTrue($config->crew['comms']); + $this->assertFalse($config->crew['doctor']); + } + + //-------------------------------------------------------------------- + + public function testArrayValues() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals('complex', $config->simple['name']); + $this->assertEquals('foo', $config->first); + $this->assertEquals('bar', $config->second); + } + + //-------------------------------------------------------------------- + + public function testSetsDefaultValues() + { + $dotenv = new DotEnv($this->fixturesFolder, 'commented.env'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals('foo', $config->first); + $this->assertEquals('bar', $config->second); + } + + //-------------------------------------------------------------------- + + public function testRecognizesLooseValues() + { + $dotenv = new DotEnv($this->fixturesFolder, 'loose.env'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals(0, $config->QZERO); + $this->assertSame("0", $config->QZEROSTR); + $this->assertEquals(" ", $config->QEMPTYSTR); + $this->assertFalse($config->QFALSE); + } + + //-------------------------------------------------------------------- + + public function testRegistrars() + { + $config = new \RegistrarConfig(); + + // no change to unmodified property + $this->assertEquals('bar', $config->foo); + // add to an existing array property + $this->assertEquals(['baz', 'first', 'second'], $config->bar); + // add a new property + $this->assertEquals('nice', $config->format); + // add a new array property + $this->assertEquals(['apple', 'banana'], $config->fruit); + } + + public function testBadRegistrar() + { + $this->expectException('RuntimeException'); + $config = new \RegistrarConfig2(); + $this->assertEquals('bar', $config->foo); + } + + // not very interesting, but useful for code coverage + public function testWorseRegistrar() + { + $config = new \RegistrarConfig3(); + // there should be no change + $this->assertEquals('bar', $config->foo); + } } diff --git a/tests/system/Config/DotEnvTest.php b/tests/system/Config/DotEnvTest.php index 67a744a1baa8..6a415ed03735 100644 --- a/tests/system/Config/DotEnvTest.php +++ b/tests/system/Config/DotEnvTest.php @@ -8,173 +8,173 @@ class DotEnvTest extends \CIUnitTestCase { - protected $fixturesFolder; + protected $fixturesFolder; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setup() - { - $this->fixturesFolder = __DIR__.'/fixtures'; + public function setup() + { + $this->fixturesFolder = __DIR__.'/fixtures'; $file = "unreadable.env"; - $path = rtrim($this->fixturesFolder, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file; + $path = rtrim($this->fixturesFolder, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file; chmod($path, 0644); - } - - //-------------------------------------------------------------------- - - public function testReturnsFalseIfCannotFindFile() - { - $dotenv = new DotEnv(__DIR__); - $this->assertFalse($dotenv->load()); - } - - //-------------------------------------------------------------------- - - public function testLoadsVars() - { - $dotenv = new DotEnv($this->fixturesFolder); - $dotenv->load(); - $this->assertEquals('bar', getenv('FOO')); - $this->assertEquals('baz', getenv('BAR')); - $this->assertEquals('with spaces', getenv('SPACED')); - $this->assertEquals('', getenv('NULL')); - } - - //-------------------------------------------------------------------- - - public function testLoadsNoneStringFiles() - { - $dotenv = new DotEnv($this->fixturesFolder, 2); - $dotenv->load(); - $this->assertEquals('bar', getenv('FOO')); - $this->assertEquals('baz', getenv('BAR')); - $this->assertEquals('with spaces', getenv('SPACED')); - $this->assertEquals('', getenv('NULL')); - } - - //-------------------------------------------------------------------- - - public function testCommentedLoadsVars() - { - $dotenv = new DotEnv($this->fixturesFolder, 'commented.env'); - $dotenv->load(); - $this->assertEquals('bar', getenv('CFOO')); - $this->assertFalse(getenv('CBAR')); - $this->assertFalse(getenv('CZOO')); - $this->assertEquals('with spaces', getenv('CSPACED')); - $this->assertEquals('a value with a # character', getenv('CQUOTES')); - $this->assertEquals('a value with a # character & a quote " character inside quotes', getenv('CQUOTESWITHQUOTE')); - $this->assertEquals('', getenv('CNULL')); - } - - //-------------------------------------------------------------------- - - public function testLoadsUnreadableFile() - { - $file = "unreadable.env"; - $path = rtrim($this->fixturesFolder, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file; + } + + //-------------------------------------------------------------------- + + public function testReturnsFalseIfCannotFindFile() + { + $dotenv = new DotEnv(__DIR__); + $this->assertFalse($dotenv->load()); + } + + //-------------------------------------------------------------------- + + public function testLoadsVars() + { + $dotenv = new DotEnv($this->fixturesFolder); + $dotenv->load(); + $this->assertEquals('bar', getenv('FOO')); + $this->assertEquals('baz', getenv('BAR')); + $this->assertEquals('with spaces', getenv('SPACED')); + $this->assertEquals('', getenv('NULL')); + } + + //-------------------------------------------------------------------- + + public function testLoadsNoneStringFiles() + { + $dotenv = new DotEnv($this->fixturesFolder, 2); + $dotenv->load(); + $this->assertEquals('bar', getenv('FOO')); + $this->assertEquals('baz', getenv('BAR')); + $this->assertEquals('with spaces', getenv('SPACED')); + $this->assertEquals('', getenv('NULL')); + } + + //-------------------------------------------------------------------- + + public function testCommentedLoadsVars() + { + $dotenv = new DotEnv($this->fixturesFolder, 'commented.env'); + $dotenv->load(); + $this->assertEquals('bar', getenv('CFOO')); + $this->assertFalse(getenv('CBAR')); + $this->assertFalse(getenv('CZOO')); + $this->assertEquals('with spaces', getenv('CSPACED')); + $this->assertEquals('a value with a # character', getenv('CQUOTES')); + $this->assertEquals('a value with a # character & a quote " character inside quotes', getenv('CQUOTESWITHQUOTE')); + $this->assertEquals('', getenv('CNULL')); + } + + //-------------------------------------------------------------------- + + public function testLoadsUnreadableFile() + { + $file = "unreadable.env"; + $path = rtrim($this->fixturesFolder, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file; chmod($path, 0000); - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage("The .env file is not readable: {$path}"); - $dotenv = new DotEnv($this->fixturesFolder, $file); - $dotenv->load(); - } - - //-------------------------------------------------------------------- - - public function testQuotedDotenvLoadsEnvironmentVars() - { - $dotenv = new Dotenv($this->fixturesFolder, 'quoted.env'); - $dotenv->load(); - $this->assertEquals('bar', getenv('QFOO')); - $this->assertEquals('baz', getenv('QBAR')); - $this->assertEquals('with spaces', getenv('QSPACED')); - $this->assertEquals('', getenv('QNULL')); - $this->assertEquals('pgsql:host=localhost;dbname=test', getenv('QEQUALS')); - $this->assertEquals('test some escaped characters like a quote (") or maybe a backslash (\\)', getenv('QESCAPED')); - } - - //-------------------------------------------------------------------- - - public function testSpacedValuesWithoutQuotesThrowsException() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('.env values containing spaces must be surrounded by quotes.'); - - $dotenv = new Dotenv($this->fixturesFolder, 'spaced-wrong.env'); - $dotenv->load(); - } - - //-------------------------------------------------------------------- - - public function testLoadsServerGlobals() - { - $dotenv = new Dotenv($this->fixturesFolder, '.env'); - $dotenv->load(); - - $this->assertEquals('bar', $_SERVER['FOO']); - $this->assertEquals('baz', $_SERVER['BAR']); - $this->assertEquals('with spaces', $_SERVER['SPACED']); - $this->assertEquals('', $_SERVER['NULL']); - } - - //-------------------------------------------------------------------- - - public function testNamespacedVariables() - { - $dotenv = new Dotenv($this->fixturesFolder, '.env'); - $dotenv->load(); - - $this->assertEquals('complex', $_SERVER['simple.name']); - } - - //-------------------------------------------------------------------- - - public function testLoadsGetServerVar() - { - $_SERVER['SER_VAR'] = 'TT'; - $dotenv = new Dotenv($this->fixturesFolder, 'nested.env'); - $dotenv->load(); - - $this->assertEquals('TT', $_ENV['NVAR7']); - } - - //-------------------------------------------------------------------- - - public function testLoadsEnvGlobals() - { - $dotenv = new Dotenv($this->fixturesFolder); - $dotenv->load(); - $this->assertEquals('bar', $_ENV['FOO']); - $this->assertEquals('baz', $_ENV['BAR']); - $this->assertEquals('with spaces', $_ENV['SPACED']); - $this->assertEquals('', $_ENV['NULL']); - } - - //-------------------------------------------------------------------- - - public function testNestedEnvironmentVars() - { - $dotenv = new Dotenv($this->fixturesFolder, 'nested.env'); - $dotenv->load(); - $this->assertEquals('{$NVAR1} {$NVAR2}', $_ENV['NVAR3']); // not resolved - $this->assertEquals('Hello World!', $_ENV['NVAR4']); - $this->assertEquals('$NVAR1 {NVAR2}', $_ENV['NVAR5']); // not resolved - } - - //-------------------------------------------------------------------- - - public function testDotenvAllowsSpecialCharacters() - { - $dotenv = new Dotenv($this->fixturesFolder, 'specialchars.env'); - $dotenv->load(); - $this->assertEquals('$a6^C7k%zs+e^.jvjXk', getenv('SPVAR1')); - $this->assertEquals('?BUty3koaV3%GA*hMAwH}B', getenv('SPVAR2')); - $this->assertEquals('jdgEB4{QgEC]HL))&GcXxokB+wqoN+j>xkV7K?m$r', getenv('SPVAR3')); - $this->assertEquals('22222:22#2^{', getenv('SPVAR4')); - $this->assertEquals('test some escaped characters like a quote " or maybe a backslash \\', getenv('SPVAR5')); - } - - //-------------------------------------------------------------------- + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage("The .env file is not readable: {$path}"); + $dotenv = new DotEnv($this->fixturesFolder, $file); + $dotenv->load(); + } + + //-------------------------------------------------------------------- + + public function testQuotedDotenvLoadsEnvironmentVars() + { + $dotenv = new Dotenv($this->fixturesFolder, 'quoted.env'); + $dotenv->load(); + $this->assertEquals('bar', getenv('QFOO')); + $this->assertEquals('baz', getenv('QBAR')); + $this->assertEquals('with spaces', getenv('QSPACED')); + $this->assertEquals('', getenv('QNULL')); + $this->assertEquals('pgsql:host=localhost;dbname=test', getenv('QEQUALS')); + $this->assertEquals('test some escaped characters like a quote (") or maybe a backslash (\\)', getenv('QESCAPED')); + } + + //-------------------------------------------------------------------- + + public function testSpacedValuesWithoutQuotesThrowsException() + { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('.env values containing spaces must be surrounded by quotes.'); + + $dotenv = new Dotenv($this->fixturesFolder, 'spaced-wrong.env'); + $dotenv->load(); + } + + //-------------------------------------------------------------------- + + public function testLoadsServerGlobals() + { + $dotenv = new Dotenv($this->fixturesFolder, '.env'); + $dotenv->load(); + + $this->assertEquals('bar', $_SERVER['FOO']); + $this->assertEquals('baz', $_SERVER['BAR']); + $this->assertEquals('with spaces', $_SERVER['SPACED']); + $this->assertEquals('', $_SERVER['NULL']); + } + + //-------------------------------------------------------------------- + + public function testNamespacedVariables() + { + $dotenv = new Dotenv($this->fixturesFolder, '.env'); + $dotenv->load(); + + $this->assertEquals('complex', $_SERVER['simple.name']); + } + + //-------------------------------------------------------------------- + + public function testLoadsGetServerVar() + { + $_SERVER['SER_VAR'] = 'TT'; + $dotenv = new Dotenv($this->fixturesFolder, 'nested.env'); + $dotenv->load(); + + $this->assertEquals('TT', $_ENV['NVAR7']); + } + + //-------------------------------------------------------------------- + + public function testLoadsEnvGlobals() + { + $dotenv = new Dotenv($this->fixturesFolder); + $dotenv->load(); + $this->assertEquals('bar', $_ENV['FOO']); + $this->assertEquals('baz', $_ENV['BAR']); + $this->assertEquals('with spaces', $_ENV['SPACED']); + $this->assertEquals('', $_ENV['NULL']); + } + + //-------------------------------------------------------------------- + + public function testNestedEnvironmentVars() + { + $dotenv = new Dotenv($this->fixturesFolder, 'nested.env'); + $dotenv->load(); + $this->assertEquals('{$NVAR1} {$NVAR2}', $_ENV['NVAR3']); // not resolved + $this->assertEquals('Hello World!', $_ENV['NVAR4']); + $this->assertEquals('$NVAR1 {NVAR2}', $_ENV['NVAR5']); // not resolved + } + + //-------------------------------------------------------------------- + + public function testDotenvAllowsSpecialCharacters() + { + $dotenv = new Dotenv($this->fixturesFolder, 'specialchars.env'); + $dotenv->load(); + $this->assertEquals('$a6^C7k%zs+e^.jvjXk', getenv('SPVAR1')); + $this->assertEquals('?BUty3koaV3%GA*hMAwH}B', getenv('SPVAR2')); + $this->assertEquals('jdgEB4{QgEC]HL))&GcXxokB+wqoN+j>xkV7K?m$r', getenv('SPVAR3')); + $this->assertEquals('22222:22#2^{', getenv('SPVAR4')); + $this->assertEquals('test some escaped characters like a quote " or maybe a backslash \\', getenv('SPVAR5')); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Config/MimesTest.php b/tests/system/Config/MimesTest.php index b4c5f6eabb4e..8e47695c1203 100644 --- a/tests/system/Config/MimesTest.php +++ b/tests/system/Config/MimesTest.php @@ -2,54 +2,54 @@ class MimesTest extends \CIUnitTestCase { - public function extensionsList() - { - return [ - 'null' => [null, 'xkadjflkjdsf'], - 'single' => ['cpt', 'application/mac-compactpro'], - 'trimmed' => ['cpt', ' application/mac-compactpro '], - 'manyMimes' => ['csv', 'text/csv'], - 'mixedCase' => ['csv', 'text/CSV'], - ]; - } - - //-------------------------------------------------------------------- - - /** - * @dataProvider extensionsList - * - * @param $expected - * @param $ext - */ - public function testGuessExtensionFromType($expected, $mime) - { - $this->assertEquals($expected, Mimes::guessExtensionFromType($mime)); - } - - //-------------------------------------------------------------------- - - public function mimesList() - { - return [ - 'null' => [null, 'xalkjdlfkj'], - 'single' => ['audio/midi', 'mid'], - 'many' => ['image/bmp', 'bmp'], - 'trimmed' => ['image/bmp', '.bmp'], - 'mixedCase' => ['image/bmp', 'BMP'], - ]; - } - - //-------------------------------------------------------------------- - - /** - * @dataProvider mimesList - */ - public function testGuessTypeFromExtension($expected, $ext) - { - $this->assertEquals($expected, Mimes::guessTypeFromExtension($ext)); - } - - //-------------------------------------------------------------------- + public function extensionsList() + { + return [ + 'null' => [null, 'xkadjflkjdsf'], + 'single' => ['cpt', 'application/mac-compactpro'], + 'trimmed' => ['cpt', ' application/mac-compactpro '], + 'manyMimes' => ['csv', 'text/csv'], + 'mixedCase' => ['csv', 'text/CSV'], + ]; + } + + //-------------------------------------------------------------------- + + /** + * @dataProvider extensionsList + * + * @param $expected + * @param $ext + */ + public function testGuessExtensionFromType($expected, $mime) + { + $this->assertEquals($expected, Mimes::guessExtensionFromType($mime)); + } + + //-------------------------------------------------------------------- + + public function mimesList() + { + return [ + 'null' => [null, 'xalkjdlfkj'], + 'single' => ['audio/midi', 'mid'], + 'many' => ['image/bmp', 'bmp'], + 'trimmed' => ['image/bmp', '.bmp'], + 'mixedCase' => ['image/bmp', 'BMP'], + ]; + } + + //-------------------------------------------------------------------- + + /** + * @dataProvider mimesList + */ + public function testGuessTypeFromExtension($expected, $ext) + { + $this->assertEquals($expected, Mimes::guessTypeFromExtension($ext)); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Config/ServicesTest.php b/tests/system/Config/ServicesTest.php index 071739011a1f..2fd40756a741 100644 --- a/tests/system/Config/ServicesTest.php +++ b/tests/system/Config/ServicesTest.php @@ -3,150 +3,150 @@ class ServicesTest extends \CIUnitTestCase { - protected $config; - protected $original; - - public function setUp() - { - $this->original = $_SERVER; -// $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es; q=1.0, en; q=0.5'; - $this->config = new App(); -// $this->config->negotiateLocale = true; -// $this->config->supportedLocales = ['en', 'es']; - } - - public function tearDown() - { - $_SERVER = $this->original; - } - - public function testNewCurlRequest() - { - $actual = Services::curlrequest(); - $this->assertInstanceOf(\CodeIgniter\HTTP\CURLRequest::class, $actual); - } - - public function testNewExceptions() - { - $actual = Services::exceptions(new Exceptions(), Services::request(), Services::response()); - $this->assertInstanceOf(\CodeIgniter\Debug\Exceptions::class, $actual); - } - - public function testNewExceptionsWithNullConfig() - { - $actual = Services::exceptions(null, null, null, false); - $this->assertInstanceOf(\CodeIgniter\Debug\Exceptions::class, $actual); - } - - public function testNewIterator() - { - $actual = Services::iterator(); - $this->assertInstanceOf(\CodeIgniter\Debug\Iterator::class, $actual); - } - - public function testNewImage() - { - $actual = Services::image(); - $this->assertInstanceOf(\CodeIgniter\Images\ImageHandlerInterface::class, $actual); - } - -// public function testNewMigrationRunner() -// { -// //FIXME - docs aren't clear about setting this up to just make sure that the service -// // returns a MigrationRunner -// $config = new \Config\Migrations(); -// $db = new \CodeIgniter\Database\MockConnection([]); -// $this->expectException('InvalidArgumentException'); -// $actual = Services::migrations($config, $db); -// $this->assertInstanceOf(\CodeIgniter\Database\MigrationRunner::class, $actual); -// } + protected $config; + protected $original; + + public function setUp() + { + $this->original = $_SERVER; +// $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es; q=1.0, en; q=0.5'; + $this->config = new App(); +// $this->config->negotiateLocale = true; +// $this->config->supportedLocales = ['en', 'es']; + } + + public function tearDown() + { + $_SERVER = $this->original; + } + + public function testNewCurlRequest() + { + $actual = Services::curlrequest(); + $this->assertInstanceOf(\CodeIgniter\HTTP\CURLRequest::class, $actual); + } + + public function testNewExceptions() + { + $actual = Services::exceptions(new Exceptions(), Services::request(), Services::response()); + $this->assertInstanceOf(\CodeIgniter\Debug\Exceptions::class, $actual); + } + + public function testNewExceptionsWithNullConfig() + { + $actual = Services::exceptions(null, null, null, false); + $this->assertInstanceOf(\CodeIgniter\Debug\Exceptions::class, $actual); + } + + public function testNewIterator() + { + $actual = Services::iterator(); + $this->assertInstanceOf(\CodeIgniter\Debug\Iterator::class, $actual); + } + + public function testNewImage() + { + $actual = Services::image(); + $this->assertInstanceOf(\CodeIgniter\Images\ImageHandlerInterface::class, $actual); + } + +// public function testNewMigrationRunner() +// { +// //FIXME - docs aren't clear about setting this up to just make sure that the service +// // returns a MigrationRunner +// $config = new \Config\Migrations(); +// $db = new \CodeIgniter\Database\MockConnection([]); +// $this->expectException('InvalidArgumentException'); +// $actual = Services::migrations($config, $db); +// $this->assertInstanceOf(\CodeIgniter\Database\MigrationRunner::class, $actual); +// } // - public function testNewNegotiatorWithNullConfig() - { - $actual = Services::negotiator(null); - $this->assertInstanceOf(\CodeIgniter\HTTP\Negotiate::class, $actual); - } - - public function testNewClirequest() - { - $actual = Services::clirequest(null); - $this->assertInstanceOf(\CodeIgniter\HTTP\CLIRequest::class, $actual); - } - - public function testNewUnsharedClirequest() - { - $actual = Services::clirequest(null, false); - $this->assertInstanceOf(\CodeIgniter\HTTP\CLIRequest::class, $actual); - } - - public function testNewPager() - { - $actual = Services::pager(null); - $this->assertInstanceOf(\CodeIgniter\Pager\Pager::class, $actual); - } - - public function testNewThrottlerFromShared() - { - $actual = Services::throttler(); - $this->assertInstanceOf(\CodeIgniter\Throttle\Throttler::class, $actual); - } - - public function testNewThrottler() - { - $actual = Services::throttler(false); - $this->assertInstanceOf(\CodeIgniter\Throttle\Throttler::class, $actual); - } - - public function testNewToolbar() - { - $actual = Services::toolbar(null); - $this->assertInstanceOf(\CodeIgniter\Debug\Toolbar::class, $actual); - } - - public function testNewUri() - { - $actual = Services::uri(null); - $this->assertInstanceOf(\CodeIgniter\HTTP\URI::class, $actual); - } - - public function testNewValidation() - { - $actual = Services::validation(null); - $this->assertInstanceOf(\CodeIgniter\Validation\Validation::class, $actual); - } - - public function testNewViewcellFromShared() - { - $actual = Services::viewcell(); - $this->assertInstanceOf(\CodeIgniter\View\Cell::class, $actual); - } - - public function testNewViewcell() - { - $actual = Services::viewcell(false); - $this->assertInstanceOf(\CodeIgniter\View\Cell::class, $actual); - } - - public function testNewSession() - { - $actual = Services::session($this->config); - $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); - } - - public function testNewSessionWithNullConfig() - { - $actual = Services::session(null, false); - $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); - } - - public function testCallStatic() - { - // __callStatic should kick in for this but fail - $actual = \CodeIgniter\Config\Services::SeSsIoNs(null, false); - $this->assertNull($actual); - // __callStatic should kick in for this - $actual = \CodeIgniter\Config\Services::SeSsIoN(null, false); - $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); - } + public function testNewNegotiatorWithNullConfig() + { + $actual = Services::negotiator(null); + $this->assertInstanceOf(\CodeIgniter\HTTP\Negotiate::class, $actual); + } + + public function testNewClirequest() + { + $actual = Services::clirequest(null); + $this->assertInstanceOf(\CodeIgniter\HTTP\CLIRequest::class, $actual); + } + + public function testNewUnsharedClirequest() + { + $actual = Services::clirequest(null, false); + $this->assertInstanceOf(\CodeIgniter\HTTP\CLIRequest::class, $actual); + } + + public function testNewPager() + { + $actual = Services::pager(null); + $this->assertInstanceOf(\CodeIgniter\Pager\Pager::class, $actual); + } + + public function testNewThrottlerFromShared() + { + $actual = Services::throttler(); + $this->assertInstanceOf(\CodeIgniter\Throttle\Throttler::class, $actual); + } + + public function testNewThrottler() + { + $actual = Services::throttler(false); + $this->assertInstanceOf(\CodeIgniter\Throttle\Throttler::class, $actual); + } + + public function testNewToolbar() + { + $actual = Services::toolbar(null); + $this->assertInstanceOf(\CodeIgniter\Debug\Toolbar::class, $actual); + } + + public function testNewUri() + { + $actual = Services::uri(null); + $this->assertInstanceOf(\CodeIgniter\HTTP\URI::class, $actual); + } + + public function testNewValidation() + { + $actual = Services::validation(null); + $this->assertInstanceOf(\CodeIgniter\Validation\Validation::class, $actual); + } + + public function testNewViewcellFromShared() + { + $actual = Services::viewcell(); + $this->assertInstanceOf(\CodeIgniter\View\Cell::class, $actual); + } + + public function testNewViewcell() + { + $actual = Services::viewcell(false); + $this->assertInstanceOf(\CodeIgniter\View\Cell::class, $actual); + } + + public function testNewSession() + { + $actual = Services::session($this->config); + $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); + } + + public function testNewSessionWithNullConfig() + { + $actual = Services::session(null, false); + $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); + } + + public function testCallStatic() + { + // __callStatic should kick in for this but fail + $actual = \CodeIgniter\Config\Services::SeSsIoNs(null, false); + $this->assertNull($actual); + // __callStatic should kick in for this + $actual = \CodeIgniter\Config\Services::SeSsIoN(null, false); + $this->assertInstanceOf(\CodeIgniter\Session\Session::class, $actual); + } } diff --git a/tests/system/Config/fixtures/RegistrarConfig.php b/tests/system/Config/fixtures/RegistrarConfig.php index aada7873acbe..758c5dc257bf 100644 --- a/tests/system/Config/fixtures/RegistrarConfig.php +++ b/tests/system/Config/fixtures/RegistrarConfig.php @@ -2,12 +2,12 @@ class RegistrarConfig extends \CodeIgniter\Config\BaseConfig { - public $foo = 'bar'; - public $bar = [ - 'baz' - ]; + public $foo = 'bar'; + public $bar = [ + 'baz' + ]; - protected $registrars = [ - \Tests\Support\Config\Registrar::class - ]; + protected $registrars = [ + \Tests\Support\Config\Registrar::class + ]; } diff --git a/tests/system/Config/fixtures/RegistrarConfig2.php b/tests/system/Config/fixtures/RegistrarConfig2.php index 8040e9496c0b..098a398bb91c 100644 --- a/tests/system/Config/fixtures/RegistrarConfig2.php +++ b/tests/system/Config/fixtures/RegistrarConfig2.php @@ -2,12 +2,12 @@ class RegistrarConfig2 extends \CodeIgniter\Config\BaseConfig { - public $foo = 'bar'; - public $bar = [ - 'baz' - ]; + public $foo = 'bar'; + public $bar = [ + 'baz' + ]; - protected $registrars = [ - \Tests\Support\Config\BadRegistrar::class - ]; + protected $registrars = [ + \Tests\Support\Config\BadRegistrar::class + ]; } diff --git a/tests/system/Config/fixtures/RegistrarConfig3.php b/tests/system/Config/fixtures/RegistrarConfig3.php index 3dfc9a133ab4..458a3d41491c 100644 --- a/tests/system/Config/fixtures/RegistrarConfig3.php +++ b/tests/system/Config/fixtures/RegistrarConfig3.php @@ -2,12 +2,12 @@ class RegistrarConfig3 extends \CodeIgniter\Config\BaseConfig { - public $foo = 'bar'; - public $bar = [ - 'baz' - ]; + public $foo = 'bar'; + public $bar = [ + 'baz' + ]; - protected $registrars = [ - \Tests\Support\Config\WorseRegistrar::class - ]; + protected $registrars = [ + \Tests\Support\Config\WorseRegistrar::class + ]; } diff --git a/tests/system/Config/fixtures/SimpleConfig.php b/tests/system/Config/fixtures/SimpleConfig.php index ed01b0f7c9c6..6d0564bb68f5 100644 --- a/tests/system/Config/fixtures/SimpleConfig.php +++ b/tests/system/Config/fixtures/SimpleConfig.php @@ -3,33 +3,33 @@ class SimpleConfig extends \CodeIgniter\Config\BaseConfig { - public $QZERO; - public $QZEROSTR; - public $QEMPTYSTR; - public $QFALSE; - public $first = 'foo'; - public $second = 'bar'; - public $FOO; - public $onedeep; - public $default = [ - 'name' => null - ]; - public $simple = [ - 'name' => null - ]; - // properties for environment over-ride testing - public $alpha = 'one'; - public $bravo = 'two'; - public $charlie = 'three'; - public $delta = 'four'; - public $echo = ''; - public $foxtrot = 'false'; - public $golf = 18; - public $crew = [ - 'captain' => 'Kirk', - 'science' => 'Spock', - 'doctor' => 'Bones', - 'comms' => 'Uhuru' - ]; + public $QZERO; + public $QZEROSTR; + public $QEMPTYSTR; + public $QFALSE; + public $first = 'foo'; + public $second = 'bar'; + public $FOO; + public $onedeep; + public $default = [ + 'name' => null + ]; + public $simple = [ + 'name' => null + ]; + // properties for environment over-ride testing + public $alpha = 'one'; + public $bravo = 'two'; + public $charlie = 'three'; + public $delta = 'four'; + public $echo = ''; + public $foxtrot = 'false'; + public $golf = 18; + public $crew = [ + 'captain' => 'Kirk', + 'science' => 'Spock', + 'doctor' => 'Bones', + 'comms' => 'Uhuru' + ]; } diff --git a/tests/system/Database/BaseConnectionTest.php b/tests/system/Database/BaseConnectionTest.php index 90057b97a333..a0f8c26664a9 100644 --- a/tests/system/Database/BaseConnectionTest.php +++ b/tests/system/Database/BaseConnectionTest.php @@ -3,146 +3,146 @@ class BaseConnectionTest extends \CIUnitTestCase { - protected $options = [ - 'DSN' => '', - 'hostname' => 'localhost', - 'username' => 'first', - 'password' => 'last', - 'database' => 'dbname', - 'DBDriver' => 'MockDriver', - 'DBPrefix' => 'test_', - 'pConnect' => true, - 'DBDebug' => (ENVIRONMENT !== 'production'), - 'cacheOn' => false, - 'cacheDir' => 'my/cacheDir', - 'charset' => 'utf8', - 'DBCollat' => 'utf8_general_ci', - 'swapPre' => '', - 'encrypt' => false, - 'compress' => false, - 'strictOn' => true, - 'failover' => [], - ]; - - protected $failoverOptions = [ - 'DSN' => '', - 'hostname' => 'localhost', - 'username' => 'failover', - 'password' => 'one', - 'database' => 'failover', - 'DBDriver' => 'MockDriver', - 'DBPrefix' => 'test_', - 'pConnect' => true, - 'DBDebug' => (ENVIRONMENT !== 'production'), - 'cacheOn' => false, - 'cacheDir' => 'my/cacheDir', - 'charset' => 'utf8', - 'DBCollat' => 'utf8_general_ci', - 'swapPre' => '', - 'encrypt' => false, - 'compress' => false, - 'strictOn' => true, - 'failover' => [], - ]; - - //-------------------------------------------------------------------- - - public function testSavesConfigOptions() - { - $db = new MockConnection($this->options); - - $this->assertSame('localhost', $db->hostname); - $this->assertSame('first', $db->username); - $this->assertSame('last', $db->password); - $this->assertSame('dbname', $db->database); - $this->assertSame('MockDriver', $db->DBDriver); - $this->assertTrue($db->pConnect); - $this->assertTrue($db->DBDebug); - $this->assertFalse($db->cacheOn); - $this->assertSame('my/cacheDir', $db->cacheDir); - $this->assertSame('utf8', $db->charset); - $this->assertSame('utf8_general_ci', $db->DBCollat); - $this->assertSame('', $db->swapPre); - $this->assertFalse($db->encrypt); - $this->assertFalse($db->compress); - $this->assertTrue($db->strictOn); - $this->assertSame([], $db->failover); - } - - //-------------------------------------------------------------------- - - public function testConnectionThrowExceptionWhenCannotConnect() - { - $db = new MockConnection($this->options); - - $this->expectException('\CodeIgniter\Database\Exceptions\DatabaseException'); - $this->expectExceptionMessage('Unable to connect to the database.'); - - $db->shouldReturn('connect', false) - ->initialize(); - } - - //-------------------------------------------------------------------- - - public function testCanConnectAndStoreConnection() - { - $db = new MockConnection($this->options); - - $db->shouldReturn('connect', 123) - ->initialize(); - - $this->assertSame(123, $db->getConnection()); - } - - //-------------------------------------------------------------------- - - /** - * @throws \CodeIgniter\Database\Exceptions\DatabaseException - * @group single - */ - public function testCanConnectToFailoverWhenNoConnectionAvailable() - { - $options = $this->options; - $options['failover'] = [$this->failoverOptions]; - - $db = new MockConnection($options); - - $db->shouldReturn('connect', [false, 345]) - ->initialize(); - - $this->assertSame(345, $db->getConnection()); - $this->assertSame('failover', $db->username); - } - - //-------------------------------------------------------------------- - - public function testStoresConnectionTimings() - { - $start = microtime(true); - - $db = new MockConnection($this->options); - - $db->initialize(); - - $this->assertGreaterThan($start, $db->getConnectStart()); - $this->assertGreaterThan(0.0, $db->getConnectDuration()); - } - - //-------------------------------------------------------------------- - - /** - * Ensures we don't have escaped - values... - * - * @see https://github.com/bcit-ci/CodeIgniter4/issues/606 - */ - public function testEscapeProtectsNegativeNumbers() - { - $db = new MockConnection($this->options); - - $db->initialize(); + protected $options = [ + 'DSN' => '', + 'hostname' => 'localhost', + 'username' => 'first', + 'password' => 'last', + 'database' => 'dbname', + 'DBDriver' => 'MockDriver', + 'DBPrefix' => 'test_', + 'pConnect' => true, + 'DBDebug' => (ENVIRONMENT !== 'production'), + 'cacheOn' => false, + 'cacheDir' => 'my/cacheDir', + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + 'swapPre' => '', + 'encrypt' => false, + 'compress' => false, + 'strictOn' => true, + 'failover' => [], + ]; + + protected $failoverOptions = [ + 'DSN' => '', + 'hostname' => 'localhost', + 'username' => 'failover', + 'password' => 'one', + 'database' => 'failover', + 'DBDriver' => 'MockDriver', + 'DBPrefix' => 'test_', + 'pConnect' => true, + 'DBDebug' => (ENVIRONMENT !== 'production'), + 'cacheOn' => false, + 'cacheDir' => 'my/cacheDir', + 'charset' => 'utf8', + 'DBCollat' => 'utf8_general_ci', + 'swapPre' => '', + 'encrypt' => false, + 'compress' => false, + 'strictOn' => true, + 'failover' => [], + ]; + + //-------------------------------------------------------------------- + + public function testSavesConfigOptions() + { + $db = new MockConnection($this->options); + + $this->assertSame('localhost', $db->hostname); + $this->assertSame('first', $db->username); + $this->assertSame('last', $db->password); + $this->assertSame('dbname', $db->database); + $this->assertSame('MockDriver', $db->DBDriver); + $this->assertTrue($db->pConnect); + $this->assertTrue($db->DBDebug); + $this->assertFalse($db->cacheOn); + $this->assertSame('my/cacheDir', $db->cacheDir); + $this->assertSame('utf8', $db->charset); + $this->assertSame('utf8_general_ci', $db->DBCollat); + $this->assertSame('', $db->swapPre); + $this->assertFalse($db->encrypt); + $this->assertFalse($db->compress); + $this->assertTrue($db->strictOn); + $this->assertSame([], $db->failover); + } + + //-------------------------------------------------------------------- + + public function testConnectionThrowExceptionWhenCannotConnect() + { + $db = new MockConnection($this->options); + + $this->expectException('\CodeIgniter\Database\Exceptions\DatabaseException'); + $this->expectExceptionMessage('Unable to connect to the database.'); + + $db->shouldReturn('connect', false) + ->initialize(); + } + + //-------------------------------------------------------------------- + + public function testCanConnectAndStoreConnection() + { + $db = new MockConnection($this->options); + + $db->shouldReturn('connect', 123) + ->initialize(); + + $this->assertSame(123, $db->getConnection()); + } + + //-------------------------------------------------------------------- + + /** + * @throws \CodeIgniter\Database\Exceptions\DatabaseException + * @group single + */ + public function testCanConnectToFailoverWhenNoConnectionAvailable() + { + $options = $this->options; + $options['failover'] = [$this->failoverOptions]; + + $db = new MockConnection($options); + + $db->shouldReturn('connect', [false, 345]) + ->initialize(); + + $this->assertSame(345, $db->getConnection()); + $this->assertSame('failover', $db->username); + } + + //-------------------------------------------------------------------- + + public function testStoresConnectionTimings() + { + $start = microtime(true); + + $db = new MockConnection($this->options); + + $db->initialize(); + + $this->assertGreaterThan($start, $db->getConnectStart()); + $this->assertGreaterThan(0.0, $db->getConnectDuration()); + } + + //-------------------------------------------------------------------- + + /** + * Ensures we don't have escaped - values... + * + * @see https://github.com/bcit-ci/CodeIgniter4/issues/606 + */ + public function testEscapeProtectsNegativeNumbers() + { + $db = new MockConnection($this->options); + + $db->initialize(); - $this->assertEquals("'-100'", $db->escape(-100)); - } + $this->assertEquals("'-100'", $db->escape(-100)); + } } diff --git a/tests/system/Database/BaseQueryTest.php b/tests/system/Database/BaseQueryTest.php index 800e07ddd305..9f4d9434221c 100644 --- a/tests/system/Database/BaseQueryTest.php +++ b/tests/system/Database/BaseQueryTest.php @@ -3,198 +3,198 @@ class QueryTest extends \CIUnitTestCase { - protected $db; + protected $db; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setUp() - { - $this->db = new MockConnection([]); - } + public function setUp() + { + $this->db = new MockConnection([]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testQueryStoresSQL() - { - $query = new Query($this->db); + public function testQueryStoresSQL() + { + $query = new Query($this->db); - $sql = "SELECT * FROM users"; + $sql = "SELECT * FROM users"; - $query->setQuery($sql); + $query->setQuery($sql); - $this->assertEquals($sql, $query->getQuery()); - } + $this->assertEquals($sql, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testStoresDuration() - { - $query = new Query($this->db); + public function testStoresDuration() + { + $query = new Query($this->db); - $start = microtime(true); + $start = microtime(true); - $query->setDuration($start, $start+5); + $query->setDuration($start, $start+5); - $this->assertEquals(5, $query->getDuration()); - } + $this->assertEquals(5, $query->getDuration()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testsStoresErrorInformation() - { - $query = new Query($this->db); + public function testsStoresErrorInformation() + { + $query = new Query($this->db); - $code = 13; - $msg = 'Oops, yo!'; + $code = 13; + $msg = 'Oops, yo!'; - $this->assertFalse($query->hasError()); + $this->assertFalse($query->hasError()); - $query->setError($code, $msg); - $this->assertTrue($query->hasError()); - $this->assertEquals($code, $query->getErrorCode()); - $this->assertEquals($msg, $query->getErrorMessage()); - } + $query->setError($code, $msg); + $this->assertTrue($query->hasError()); + $this->assertEquals($code, $query->getErrorCode()); + $this->assertEquals($msg, $query->getErrorMessage()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSwapPrefix() - { - $query = new Query($this->db); + public function testSwapPrefix() + { + $query = new Query($this->db); - $origPrefix = 'db_'; - $newPrefix = 'ci_'; + $origPrefix = 'db_'; + $newPrefix = 'ci_'; - $origSQL = 'SELECT * FROM db_users WHERE db_users.id = 1'; - $newSQL = 'SELECT * FROM ci_users WHERE ci_users.id = 1'; + $origSQL = 'SELECT * FROM db_users WHERE db_users.id = 1'; + $newSQL = 'SELECT * FROM ci_users WHERE ci_users.id = 1'; - $query->setQuery($origSQL); - $query->swapPrefix($origPrefix, $newPrefix); + $query->setQuery($origSQL); + $query->swapPrefix($origPrefix, $newPrefix); - $this->assertEquals($newSQL, $query->getQuery()); - } + $this->assertEquals($newSQL, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function queryTypes() - { - return [ - 'select' => [false, 'SELECT * FROM users'], - 'set' => [true, 'SET ...'], - 'insert' => [true, 'INSERT INTO ...'], - 'update' => [true, 'UPDATE ...'], - 'delete' => [true, 'DELETE ...'], - 'replace' => [true, 'REPLACE ...'], - 'create' => [true, 'CREATE ...'], - 'drop' => [true, 'DROP ...'], - 'truncate' => [true, 'TRUNCATE ...'], - 'load' => [true, 'LOAD ...'], - 'copy' => [true, 'COPY ...'], - 'alter' => [true, 'ALTER ...'], - 'rename' => [true, 'RENAME ...'], - 'grant' => [true, 'GRANT ...'], - 'revoke' => [true, 'REVOKE ...'], - 'lock' => [true, 'LOCK ...'], - 'unlock' => [true, 'UNLOCK ...'], - 'reindex' => [true, 'REINDEX ...'], - ]; - } + public function queryTypes() + { + return [ + 'select' => [false, 'SELECT * FROM users'], + 'set' => [true, 'SET ...'], + 'insert' => [true, 'INSERT INTO ...'], + 'update' => [true, 'UPDATE ...'], + 'delete' => [true, 'DELETE ...'], + 'replace' => [true, 'REPLACE ...'], + 'create' => [true, 'CREATE ...'], + 'drop' => [true, 'DROP ...'], + 'truncate' => [true, 'TRUNCATE ...'], + 'load' => [true, 'LOAD ...'], + 'copy' => [true, 'COPY ...'], + 'alter' => [true, 'ALTER ...'], + 'rename' => [true, 'RENAME ...'], + 'grant' => [true, 'GRANT ...'], + 'revoke' => [true, 'REVOKE ...'], + 'lock' => [true, 'LOCK ...'], + 'unlock' => [true, 'UNLOCK ...'], + 'reindex' => [true, 'REINDEX ...'], + ]; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * @dataProvider queryTypes - */ - public function testIsWriteType($expected, $sql) - { - $query = new Query($this->db); + /** + * @dataProvider queryTypes + */ + public function testIsWriteType($expected, $sql) + { + $query = new Query($this->db); - $query->setQuery($sql); - $this->assertSame($expected, $query->isWriteType()); - } + $query->setQuery($sql); + $this->assertSame($expected, $query->isWriteType()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSingleBindingOutsideOfArray() - { - $query = new Query($this->db); + public function testSingleBindingOutsideOfArray() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE id = ?', 13); + $query->setQuery('SELECT * FROM users WHERE id = ?', 13); - $expected = 'SELECT * FROM users WHERE id = 13'; + $expected = 'SELECT * FROM users WHERE id = 13'; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testBindingSingleElementInArray() - { - $query = new Query($this->db); + public function testBindingSingleElementInArray() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE id = ?', [13]); + $query->setQuery('SELECT * FROM users WHERE id = ?', [13]); - $expected = 'SELECT * FROM users WHERE id = 13'; + $expected = 'SELECT * FROM users WHERE id = 13'; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testBindingMultipleItems() - { - $query = new Query($this->db); + public function testBindingMultipleItems() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE id = ? OR name = ?', [13, 'Vader']); + $query->setQuery('SELECT * FROM users WHERE id = ? OR name = ?', [13, 'Vader']); - $expected = "SELECT * FROM users WHERE id = 13 OR name = 'Vader'"; + $expected = "SELECT * FROM users WHERE id = 13 OR name = 'Vader'"; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testBindingAutoEscapesParameters() - { - $query = new Query($this->db); + public function testBindingAutoEscapesParameters() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE name = ?', ["O'Reilly"]); + $query->setQuery('SELECT * FROM users WHERE name = ?', ["O'Reilly"]); - $expected = "SELECT * FROM users WHERE name = 'O''Reilly'"; + $expected = "SELECT * FROM users WHERE name = 'O''Reilly'"; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testNamedBinds() - { - $query = new Query($this->db); + public function testNamedBinds() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE id = :id: OR name = :name:', ['id' => 13, 'name' => 'Geoffrey']); + $query->setQuery('SELECT * FROM users WHERE id = :id: OR name = :name:', ['id' => 13, 'name' => 'Geoffrey']); - $expected = "SELECT * FROM users WHERE id = 13 OR name = 'Geoffrey'"; + $expected = "SELECT * FROM users WHERE id = 13 OR name = 'Geoffrey'"; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * @group single - * - * @see https://github.com/bcit-ci/CodeIgniter4/issues/201 - */ - public function testSimilarNamedBinds() - { - $query = new Query($this->db); + /** + * @group single + * + * @see https://github.com/bcit-ci/CodeIgniter4/issues/201 + */ + public function testSimilarNamedBinds() + { + $query = new Query($this->db); - $query->setQuery('SELECT * FROM users WHERE sitemap = :sitemap: OR site = :site:', ['sitemap' => 'sitemap', 'site' => 'site']); + $query->setQuery('SELECT * FROM users WHERE sitemap = :sitemap: OR site = :site:', ['sitemap' => 'sitemap', 'site' => 'site']); - $expected = "SELECT * FROM users WHERE sitemap = 'sitemap' OR site = 'site'"; + $expected = "SELECT * FROM users WHERE sitemap = 'sitemap' OR site = 'site'"; - $this->assertEquals($expected, $query->getQuery()); - } + $this->assertEquals($expected, $query->getQuery()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/AliasTest.php b/tests/system/Database/Live/AliasTest.php index 9697868089d7..6ceef24e7d2e 100644 --- a/tests/system/Database/Live/AliasTest.php +++ b/tests/system/Database/Live/AliasTest.php @@ -2,21 +2,21 @@ class AliasTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testAlias() - { - $builder = $this->db->table('job j'); + public function testAlias() + { + $builder = $this->db->table('job j'); - $jobs = $builder - ->where('j.name', 'Developer') - ->get(); + $jobs = $builder + ->where('j.name', 'Developer') + ->get(); - $this->assertEquals(1, count($jobs->getResult())); - } + $this->assertEquals(1, count($jobs->getResult())); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/CIDbTestCaseTest.php b/tests/system/Database/Live/CIDbTestCaseTest.php index 27da620ba3bf..401f60cf3605 100644 --- a/tests/system/Database/Live/CIDbTestCaseTest.php +++ b/tests/system/Database/Live/CIDbTestCaseTest.php @@ -5,43 +5,43 @@ */ class CIDbTestCaseTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testHasInDatabase() - { - $this->hasInDatabase('user', ['name' => 'Ricky', 'email' => 'sofine@example.com', 'country' => 'US']); + public function testHasInDatabase() + { + $this->hasInDatabase('user', ['name' => 'Ricky', 'email' => 'sofine@example.com', 'country' => 'US']); - $this->seeInDatabase('user', ['name' => 'Ricky', 'email' => 'sofine@example.com', 'country' => 'US']); - } - - //-------------------------------------------------------------------- + $this->seeInDatabase('user', ['name' => 'Ricky', 'email' => 'sofine@example.com', 'country' => 'US']); + } - public function testDontSeeInDatabase() - { - $this->dontSeeInDatabase('user', ['name' => 'Ricardo']); - } + //-------------------------------------------------------------------- - //-------------------------------------------------------------------- + public function testDontSeeInDatabase() + { + $this->dontSeeInDatabase('user', ['name' => 'Ricardo']); + } - public function testSeeNumRecords() - { - $this->seeNumRecords(2, 'user', ['country' => 'US']); - } + //-------------------------------------------------------------------- - //-------------------------------------------------------------------- + public function testSeeNumRecords() + { + $this->seeNumRecords(2, 'user', ['country' => 'US']); + } + //-------------------------------------------------------------------- - public function testGrabFromDatabase() - { - $email = $this->grabFromDatabase('user', 'email', ['name' => 'Derek Jones']); - $this->assertEquals('derek@world.com', $email); - } + public function testGrabFromDatabase() + { + $email = $this->grabFromDatabase('user', 'email', ['name' => 'Derek Jones']); - //-------------------------------------------------------------------- + $this->assertEquals('derek@world.com', $email); + } + //-------------------------------------------------------------------- - -} \ No newline at end of file + + +} diff --git a/tests/system/Database/Live/CountTest.php b/tests/system/Database/Live/CountTest.php index 6813d36c2ba4..05d734fb5a52 100644 --- a/tests/system/Database/Live/CountTest.php +++ b/tests/system/Database/Live/CountTest.php @@ -5,45 +5,45 @@ */ class CountTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testCountReturnsZeroWithNoResults() - { - $this->assertSame(0, $this->db->table('empty')->countAll()); - } + public function testCountReturnsZeroWithNoResults() + { + $this->assertSame(0, $this->db->table('empty')->countAll()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCountAllReturnsCorrectInteger() - { - $this->assertSame(4, $this->db->table('job')->countAll()); - } + public function testCountAllReturnsCorrectInteger() + { + $this->assertSame(4, $this->db->table('job')->countAll()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCountAllResultsReturnsZeroWithNoResults() - { - $this->assertSame(0, $this->db->table('job')->where('name', 'Superstar')->countAllResults()); - } + public function testCountAllResultsReturnsZeroWithNoResults() + { + $this->assertSame(0, $this->db->table('job')->where('name', 'Superstar')->countAllResults()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCountAllResultsReturnsCorrectValue() - { - $this->assertSame(1, $this->db->table('job')->where('name', 'Developer')->countAllResults()); - } + public function testCountAllResultsReturnsCorrectValue() + { + $this->assertSame(1, $this->db->table('job')->where('name', 'Developer')->countAllResults()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCountAllResultsHonorsReset() - { - $builder = $this->db->table('job'); + public function testCountAllResultsHonorsReset() + { + $builder = $this->db->table('job'); - $this->assertSame(1, $builder->where('name', 'Developer')->countAllResults(false)); - $this->assertSame(1, $builder->countAllResults()); - } + $this->assertSame(1, $builder->where('name', 'Developer')->countAllResults(false)); + $this->assertSame(1, $builder->countAllResults()); + } - //-------------------------------------------------------------------- -} \ No newline at end of file + //-------------------------------------------------------------------- +} diff --git a/tests/system/Database/Live/DeleteTest.php b/tests/system/Database/Live/DeleteTest.php index 2d6e50bc79ce..b88bfb0ae2bb 100644 --- a/tests/system/Database/Live/DeleteTest.php +++ b/tests/system/Database/Live/DeleteTest.php @@ -7,65 +7,65 @@ */ class DeleteTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testDeleteThrowExceptionWithNoCriteria() - { - $this->expectException('\CodeIgniter\Database\Exceptions\DatabaseException'); + public function testDeleteThrowExceptionWithNoCriteria() + { + $this->expectException('\CodeIgniter\Database\Exceptions\DatabaseException'); - $this->db->table('job')->delete(); - } + $this->db->table('job')->delete(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWithExternalWhere() - { - $this->seeInDatabase('job', ['name' => 'Developer']); + public function testDeleteWithExternalWhere() + { + $this->seeInDatabase('job', ['name' => 'Developer']); - $this->db->table('job')->where('name', 'Developer')->delete(); + $this->db->table('job')->where('name', 'Developer')->delete(); - $this->dontSeeInDatabase('job', ['name' => 'Developer']); - } + $this->dontSeeInDatabase('job', ['name' => 'Developer']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWithInternalWhere() - { - $this->seeInDatabase('job', ['name' => 'Developer']); + public function testDeleteWithInternalWhere() + { + $this->seeInDatabase('job', ['name' => 'Developer']); - $this->db->table('job')->delete(['name' => 'Developer']); + $this->db->table('job')->delete(['name' => 'Developer']); - $this->dontSeeInDatabase('job', ['name' => 'Developer']); - } + $this->dontSeeInDatabase('job', ['name' => 'Developer']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * @group single - * @throws \CodeIgniter\Database\Exceptions\DatabaseException - */ - public function testDeleteWithLimit() - { - $this->seeNumRecords(2, 'user', ['country' => 'US']); + /** + * @group single + * @throws \CodeIgniter\Database\Exceptions\DatabaseException + */ + public function testDeleteWithLimit() + { + $this->seeNumRecords(2, 'user', ['country' => 'US']); - try - { - $this->db->table('user') - ->delete(['country' => 'US'], 1); - } - catch (DatabaseException $e) - { - if (strpos($e->getMessage(), 'does not allow LIMITs on DELETE queries.') !== false) - { - return; - } - } + try + { + $this->db->table('user') + ->delete(['country' => 'US'], 1); + } + catch (DatabaseException $e) + { + if (strpos($e->getMessage(), 'does not allow LIMITs on DELETE queries.') !== false) + { + return; + } + } - $this->seeNumRecords(1, 'user', ['country' => 'US']); - } + $this->seeNumRecords(1, 'user', ['country' => 'US']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/EmptyTest.php b/tests/system/Database/Live/EmptyTest.php index 8f5520e94c08..0c5e3e6f1692 100644 --- a/tests/system/Database/Live/EmptyTest.php +++ b/tests/system/Database/Live/EmptyTest.php @@ -5,25 +5,25 @@ */ class EmptyTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testEmpty() - { - $this->db->table('misc')->emptyTable(); + public function testEmpty() + { + $this->db->table('misc')->emptyTable(); - $this->assertEquals(0, $this->db->table('misc')->countAll()); - } - - //-------------------------------------------------------------------- + $this->assertEquals(0, $this->db->table('misc')->countAll()); + } - public function testTruncate() - { - $this->db->table('misc')->truncate(); + //-------------------------------------------------------------------- - $this->assertEquals(0, $this->db->table('misc')->countAll()); - } + public function testTruncate() + { + $this->db->table('misc')->truncate(); - //-------------------------------------------------------------------- -} \ No newline at end of file + $this->assertEquals(0, $this->db->table('misc')->countAll()); + } + + //-------------------------------------------------------------------- +} diff --git a/tests/system/Database/Live/ForgeTest.php b/tests/system/Database/Live/ForgeTest.php index 35e8fef13439..1ccbac2066eb 100644 --- a/tests/system/Database/Live/ForgeTest.php +++ b/tests/system/Database/Live/ForgeTest.php @@ -5,279 +5,279 @@ */ class ForgeTest extends \CIDatabaseTestCase { - protected $refresh = true; - - protected $seed = 'CITestSeeder'; - - public function setUp() - { - parent::setUp(); - $this->forge = \Config\Database::forge($this->DBGroup); - } - - public function testCreateTable() - { - $this->forge->dropTable('forge_test_table', true); - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - 'unsigned' => false, - 'auto_increment' => true, - ], - ]); - - $this->forge->addKey('id', true); - $this->forge->createTable('forge_test_table'); - - $exist = $this->db->tableExists('forge_test_table'); - $this->forge->dropTable('forge_test_table', true); - - $this->assertTrue($exist); - } - - public function testAddFields() - { - - $this->forge->dropTable('forge_test_fields', true); - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - 'unsigned' => false, - 'auto_increment' => true, - ], - 'username' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - 'unique' => false, - ], - 'name' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - ], - 'active' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - 'default' => 0, - ], - ]); - - $this->forge->addKey('id', true); - $this->forge->addKey(['username', 'active'], false, true); - $create = $this->forge->createTable('forge_test_fields', true); - - //Check Field names - $fieldsNames = $this->db->getFieldNames('forge_test_fields'); - $this->assertContains('id', $fieldsNames); - $this->assertContains('username', $fieldsNames); - $this->assertContains('name', $fieldsNames); - $this->assertContains('active', $fieldsNames); - - - $fieldsData = $this->db->getFieldData('forge_test_fields'); - - $this->assertContains($fieldsData[0]->name, ['id', 'name', 'username', 'active']); - $this->assertContains($fieldsData[1]->name, ['id', 'name', 'username', 'active']); - - if ($this->db->DBDriver === 'MySQLi') - { - //Check types - $this->assertEquals($fieldsData[0]->type, 'int'); - $this->assertEquals($fieldsData[1]->type, 'varchar'); - - $this->assertEquals($fieldsData[0]->max_length, 11); - - $this->assertNull($fieldsData[0]->default); - $this->assertNull($fieldsData[1]->default); - - $this->assertEquals($fieldsData[0]->primary_key, 1); - - $this->assertEquals($fieldsData[1]->max_length, 255); - - } - elseif ($this->db->DBDriver === 'Postgre') - { - //Check types - $this->assertEquals($fieldsData[0]->type, 'integer'); - $this->assertEquals($fieldsData[1]->type, 'character varying'); - - $this->assertEquals($fieldsData[0]->max_length, 32); - $this->assertNull($fieldsData[1]->default); - - $this->assertEquals($fieldsData[1]->max_length, 255); - } - else - { - $this->assertTrue(false, "DB Driver not supported"); - } - - $this->forge->dropTable('forge_test_fields', true); - - } - - public function testCompositeKey() - { - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 3, - 'auto_increment' => true, - ], - 'code' => [ - 'type' => 'VARCHAR', - 'constraint' => 40, - ], - 'company' => [ - 'type' => 'VARCHAR', - 'constraint' => 40, - ], - 'active' => [ - 'type' => 'INTEGER', - 'constraint' => 1, - ], - ]); - $this->forge->addPrimaryKey('id'); - $this->forge->addKey(['code', 'company']); - $this->forge->addUniqueKey(['code', 'active']); - $this->forge->createTable('forge_test_1', true); - - $keys = $this->db->getIndexData('forge_test_1'); - - if ($this->db->DBDriver == 'MySQLi') - { - $this->assertEquals($keys[0]->name, 'PRIMARY KEY'); - $this->assertEquals($keys[0]->fields, ['id']); - $this->assertEquals($keys[0]->type, 'PRIMARY'); - $this->assertEquals($keys[2]->name, 'code_company'); - $this->assertEquals($keys[2]->fields, ['code', 'company']); - $this->assertEquals($keys[2]->type, 'INDEX'); - $this->assertEquals($keys[1]->name, 'code_active'); - $this->assertEquals($keys[1]->fields, ['code', 'active']); - $this->assertEquals($keys[1]->type, 'UNIQUE'); - } - elseif($this->db->DBDriver == 'Postgre') - { - $this->assertEquals($keys[0]->name, 'pk_db_forge_test_1'); - $this->assertEquals($keys[0]->fields, ['id']); - $this->assertEquals($keys[0]->type, 'PRIMARY'); - $this->assertEquals($keys[1]->name, 'db_forge_test_1_code_company'); - $this->assertEquals($keys[1]->fields, ['code', 'company']); - $this->assertEquals($keys[1]->type, 'INDEX'); - $this->assertEquals($keys[2]->name, 'db_forge_test_1_code_active'); - $this->assertEquals($keys[2]->fields, ['code', 'active']); - $this->assertEquals($keys[2]->type, 'UNIQUE'); - } - - $this->forge->dropTable('forge_test_1', true); - } - - public function testForeignKey() - { - - $attributes = []; - - if ($this->db->DBDriver == 'MySQLi') - { - $attributes = ['ENGINE' => 'InnoDB']; - } - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'name' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - ], - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('forge_test_users', true, $attributes); - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'users_id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'name' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - ], - ]); - $this->forge->addKey('id', true); - $this->forge->addForeignKey('users_id', 'forge_test_users', 'id', 'CASCADE', 'CASCADE'); - - $this->forge->createTable('forge_test_invoices', true, $attributes); - - $foreignKeyData = $this->db->getForeignKeyData('forge_test_invoices'); - - $this->assertEquals($foreignKeyData[0]->constraint_name, - $this->db->DBPrefix.'forge_test_invoices_users_id_foreign'); - $this->assertEquals($foreignKeyData[0]->table_name, $this->db->DBPrefix.'forge_test_invoices'); - $this->assertEquals($foreignKeyData[0]->foreign_table_name, $this->db->DBPrefix.'forge_test_users'); - - $this->forge->dropTable('forge_test_invoices', true); - $this->forge->dropTable('forge_test_users', true); - - } - - public function testDropForeignKey() - { - - $attributes = []; - - if ($this->db->DBDriver == 'MySQLi') - { - $attributes = ['ENGINE' => 'InnoDB']; - } - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'name' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - ], - ]); - $this->forge->addKey('id', true); - $this->forge->createTable('forge_test_users', true, $attributes); - - $this->forge->addField([ - 'id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'users_id' => [ - 'type' => 'INTEGER', - 'constraint' => 11, - ], - 'name' => [ - 'type' => 'VARCHAR', - 'constraint' => 255, - ], - ]); - $this->forge->addKey('id', true); - $this->forge->addForeignKey('users_id', 'forge_test_users', 'id', 'CASCADE', 'CASCADE'); - - $this->forge->createTable('forge_test_invoices', true, $attributes); - - $this->forge->dropForeignKey('forge_test_invoices', 'forge_test_invoices_users_id_foreign'); - - $foreignKeyData = $this->db->getForeignKeyData('forge_test_invoices'); - - $this->assertEmpty($foreignKeyData); - - $this->forge->dropTable('forge_test_invoices', true); - $this->forge->dropTable('forge_test_users', true); - - } + protected $refresh = true; + + protected $seed = 'CITestSeeder'; + + public function setUp() + { + parent::setUp(); + $this->forge = \Config\Database::forge($this->DBGroup); + } + + public function testCreateTable() + { + $this->forge->dropTable('forge_test_table', true); + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + 'unsigned' => false, + 'auto_increment' => true, + ], + ]); + + $this->forge->addKey('id', true); + $this->forge->createTable('forge_test_table'); + + $exist = $this->db->tableExists('forge_test_table'); + $this->forge->dropTable('forge_test_table', true); + + $this->assertTrue($exist); + } + + public function testAddFields() + { + + $this->forge->dropTable('forge_test_fields', true); + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + 'unsigned' => false, + 'auto_increment' => true, + ], + 'username' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + 'unique' => false, + ], + 'name' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + ], + 'active' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + 'default' => 0, + ], + ]); + + $this->forge->addKey('id', true); + $this->forge->addKey(['username', 'active'], false, true); + $create = $this->forge->createTable('forge_test_fields', true); + + //Check Field names + $fieldsNames = $this->db->getFieldNames('forge_test_fields'); + $this->assertContains('id', $fieldsNames); + $this->assertContains('username', $fieldsNames); + $this->assertContains('name', $fieldsNames); + $this->assertContains('active', $fieldsNames); + + + $fieldsData = $this->db->getFieldData('forge_test_fields'); + + $this->assertContains($fieldsData[0]->name, ['id', 'name', 'username', 'active']); + $this->assertContains($fieldsData[1]->name, ['id', 'name', 'username', 'active']); + + if ($this->db->DBDriver === 'MySQLi') + { + //Check types + $this->assertEquals($fieldsData[0]->type, 'int'); + $this->assertEquals($fieldsData[1]->type, 'varchar'); + + $this->assertEquals($fieldsData[0]->max_length, 11); + + $this->assertNull($fieldsData[0]->default); + $this->assertNull($fieldsData[1]->default); + + $this->assertEquals($fieldsData[0]->primary_key, 1); + + $this->assertEquals($fieldsData[1]->max_length, 255); + + } + elseif ($this->db->DBDriver === 'Postgre') + { + //Check types + $this->assertEquals($fieldsData[0]->type, 'integer'); + $this->assertEquals($fieldsData[1]->type, 'character varying'); + + $this->assertEquals($fieldsData[0]->max_length, 32); + $this->assertNull($fieldsData[1]->default); + + $this->assertEquals($fieldsData[1]->max_length, 255); + } + else + { + $this->assertTrue(false, "DB Driver not supported"); + } + + $this->forge->dropTable('forge_test_fields', true); + + } + + public function testCompositeKey() + { + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 3, + 'auto_increment' => true, + ], + 'code' => [ + 'type' => 'VARCHAR', + 'constraint' => 40, + ], + 'company' => [ + 'type' => 'VARCHAR', + 'constraint' => 40, + ], + 'active' => [ + 'type' => 'INTEGER', + 'constraint' => 1, + ], + ]); + $this->forge->addPrimaryKey('id'); + $this->forge->addKey(['code', 'company']); + $this->forge->addUniqueKey(['code', 'active']); + $this->forge->createTable('forge_test_1', true); + + $keys = $this->db->getIndexData('forge_test_1'); + + if ($this->db->DBDriver == 'MySQLi') + { + $this->assertEquals($keys[0]->name, 'PRIMARY KEY'); + $this->assertEquals($keys[0]->fields, ['id']); + $this->assertEquals($keys[0]->type, 'PRIMARY'); + $this->assertEquals($keys[2]->name, 'code_company'); + $this->assertEquals($keys[2]->fields, ['code', 'company']); + $this->assertEquals($keys[2]->type, 'INDEX'); + $this->assertEquals($keys[1]->name, 'code_active'); + $this->assertEquals($keys[1]->fields, ['code', 'active']); + $this->assertEquals($keys[1]->type, 'UNIQUE'); + } + elseif($this->db->DBDriver == 'Postgre') + { + $this->assertEquals($keys[0]->name, 'pk_db_forge_test_1'); + $this->assertEquals($keys[0]->fields, ['id']); + $this->assertEquals($keys[0]->type, 'PRIMARY'); + $this->assertEquals($keys[1]->name, 'db_forge_test_1_code_company'); + $this->assertEquals($keys[1]->fields, ['code', 'company']); + $this->assertEquals($keys[1]->type, 'INDEX'); + $this->assertEquals($keys[2]->name, 'db_forge_test_1_code_active'); + $this->assertEquals($keys[2]->fields, ['code', 'active']); + $this->assertEquals($keys[2]->type, 'UNIQUE'); + } + + $this->forge->dropTable('forge_test_1', true); + } + + public function testForeignKey() + { + + $attributes = []; + + if ($this->db->DBDriver == 'MySQLi') + { + $attributes = ['ENGINE' => 'InnoDB']; + } + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'name' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + ], + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('forge_test_users', true, $attributes); + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'users_id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'name' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + ], + ]); + $this->forge->addKey('id', true); + $this->forge->addForeignKey('users_id', 'forge_test_users', 'id', 'CASCADE', 'CASCADE'); + + $this->forge->createTable('forge_test_invoices', true, $attributes); + + $foreignKeyData = $this->db->getForeignKeyData('forge_test_invoices'); + + $this->assertEquals($foreignKeyData[0]->constraint_name, + $this->db->DBPrefix.'forge_test_invoices_users_id_foreign'); + $this->assertEquals($foreignKeyData[0]->table_name, $this->db->DBPrefix.'forge_test_invoices'); + $this->assertEquals($foreignKeyData[0]->foreign_table_name, $this->db->DBPrefix.'forge_test_users'); + + $this->forge->dropTable('forge_test_invoices', true); + $this->forge->dropTable('forge_test_users', true); + + } + + public function testDropForeignKey() + { + + $attributes = []; + + if ($this->db->DBDriver == 'MySQLi') + { + $attributes = ['ENGINE' => 'InnoDB']; + } + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'name' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + ], + ]); + $this->forge->addKey('id', true); + $this->forge->createTable('forge_test_users', true, $attributes); + + $this->forge->addField([ + 'id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'users_id' => [ + 'type' => 'INTEGER', + 'constraint' => 11, + ], + 'name' => [ + 'type' => 'VARCHAR', + 'constraint' => 255, + ], + ]); + $this->forge->addKey('id', true); + $this->forge->addForeignKey('users_id', 'forge_test_users', 'id', 'CASCADE', 'CASCADE'); + + $this->forge->createTable('forge_test_invoices', true, $attributes); + + $this->forge->dropForeignKey('forge_test_invoices', 'forge_test_invoices_users_id_foreign'); + + $foreignKeyData = $this->db->getForeignKeyData('forge_test_invoices'); + + $this->assertEmpty($foreignKeyData); + + $this->forge->dropTable('forge_test_invoices', true); + $this->forge->dropTable('forge_test_users', true); + + } } diff --git a/tests/system/Database/Live/FromTest.php b/tests/system/Database/Live/FromTest.php index 0f6de21426be..239f8d7179b2 100644 --- a/tests/system/Database/Live/FromTest.php +++ b/tests/system/Database/Live/FromTest.php @@ -5,37 +5,37 @@ */ class FromTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testFromCanAddTables() - { - $result = $this->db->table('job')->from('misc')->get()->getResult(); + public function testFromCanAddTables() + { + $result = $this->db->table('job')->from('misc')->get()->getResult(); - $this->assertCount(12, $result); - } + $this->assertCount(12, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFromCanOverride() - { - $result = $this->db->table('job')->from('misc', true)->get()->getResult(); + public function testFromCanOverride() + { + $result = $this->db->table('job')->from('misc', true)->get()->getResult(); - $this->assertCount(3, $result); - } + $this->assertCount(3, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFromWithWhere() - { - $result = $this->db->table('job')->from('user')->where('user.id', 1)->get()->getResult(); + public function testFromWithWhere() + { + $result = $this->db->table('job')->from('user')->where('user.id', 1)->get()->getResult(); - $this->assertCount(4, $result); - } + $this->assertCount(4, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/GetTest.php b/tests/system/Database/Live/GetTest.php index 286cc3a3d813..23b584a62ce8 100644 --- a/tests/system/Database/Live/GetTest.php +++ b/tests/system/Database/Live/GetTest.php @@ -5,60 +5,60 @@ */ class GetTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testGet() - { - $jobs = $this->db->table('job') - ->get() - ->getResult(); + public function testGet() + { + $jobs = $this->db->table('job') + ->get() + ->getResult(); - $this->assertCount(4, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Politician', $jobs[1]->name); - $this->assertEquals('Accountant', $jobs[2]->name); - $this->assertEquals('Musician', $jobs[3]->name); - } + $this->assertCount(4, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Politician', $jobs[1]->name); + $this->assertEquals('Accountant', $jobs[2]->name); + $this->assertEquals('Musician', $jobs[3]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetWitLimit() - { - $jobs = $this->db->table('job') - ->get(2, 2) - ->getResult(); + public function testGetWitLimit() + { + $jobs = $this->db->table('job') + ->get(2, 2) + ->getResult(); - $this->assertCount(2, $jobs); - $this->assertEquals('Accountant', $jobs[0]->name); - $this->assertEquals('Musician', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Accountant', $jobs[0]->name); + $this->assertEquals('Musician', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetWhereArray() - { - $jobs = $this->db->table('job') - ->getWhere(['id' => 1]) - ->getResult(); + public function testGetWhereArray() + { + $jobs = $this->db->table('job') + ->getWhere(['id' => 1]) + ->getResult(); - $this->assertCount(1, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - } + $this->assertCount(1, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetWhereWithLimits() - { - $jobs = $this->db->table('job') - ->getWhere('id > 1', 1, 1) - ->getResult(); + public function testGetWhereWithLimits() + { + $jobs = $this->db->table('job') + ->getWhere('id > 1', 1, 1) + ->getResult(); - $this->assertCount(1, $jobs); - $this->assertEquals('Accountant', $jobs[0]->name); - } + $this->assertCount(1, $jobs); + $this->assertEquals('Accountant', $jobs[0]->name); + } - //-------------------------------------------------------------------- -} \ No newline at end of file + //-------------------------------------------------------------------- +} diff --git a/tests/system/Database/Live/GroupTest.php b/tests/system/Database/Live/GroupTest.php index 7e457ef74faa..459445a0e30a 100644 --- a/tests/system/Database/Live/GroupTest.php +++ b/tests/system/Database/Live/GroupTest.php @@ -5,120 +5,120 @@ */ class GroupTest extends \CIDatabaseTestCase { - protected $refresh = true; - - protected $seed = 'CITestSeeder'; - - public function testGroupBy() - { - $result = $this->db->table('user') - ->select('name') - ->groupBy('name') - ->get() - ->getResult(); - - $this->assertCount(4, $result); - } - - //-------------------------------------------------------------------- - - public function testHavingBy() - { - $result = $this->db->table('job') - ->select('name') - ->groupBy('name') - ->having('SUM(id) > 2') - ->get() - ->getResultArray(); - - $this->assertCount(2, $result); - } - - //-------------------------------------------------------------------- - - public function testOrHavingBy() - { - $result = $this->db->table('user') - ->groupBy('id') - ->having('id >', 3) - ->orHaving('SUM(id) > 2') - ->get() - ->getResult(); - - $this->assertCount(2, $result); - } - - //-------------------------------------------------------------------- - - public function testAndGroups() - { - $result = $this->db->table('user') - ->groupStart() - ->where('id >=', 3) - ->where('name !=', 'Chris Martin') - ->groupEnd() - ->where('country', 'US') - ->get() - ->getResult(); - - $this->assertCount(1, $result); - $this->assertEquals('Richard A Causey', $result[0]->name); - } - - //-------------------------------------------------------------------- - - public function testOrGroups() - { - $result = $this->db->table('user') - ->where('country', 'Iran') - ->orGroupStart() - ->where('id >=', 3) - ->where('name !=', 'Richard A Causey') - ->groupEnd() - ->get() - ->getResult(); - - $this->assertCount(2, $result); - $this->assertEquals('Ahmadinejad', $result[0]->name); - $this->assertEquals('Chris Martin', $result[1]->name); - } - - //-------------------------------------------------------------------- - - public function testNotGroups() - { - $result = $this->db->table('user') - ->where('country', 'US') - ->notGroupStart() - ->where('id >=', 3) - ->where('name !=', 'Chris Martin') - ->groupEnd() - ->get() - ->getResult(); - - $this->assertCount(1, $result); - $this->assertEquals('Derek Jones', $result[0]->name); - } - - //-------------------------------------------------------------------- - - public function testOrNotGroups() - { - $result = $this->db->table('user') - ->where('country', 'US') - ->orNotGroupStart() - ->where('id >=', 2) - ->where('country', 'Iran') - ->groupEnd() - ->get() - ->getResult(); - - $this->assertCount(3, $result); - $this->assertEquals('Derek Jones', $result[0]->name); - $this->assertEquals('Richard A Causey', $result[1]->name); - $this->assertEquals('Chris Martin', $result[2]->name); - } - - //-------------------------------------------------------------------- + protected $refresh = true; + + protected $seed = 'CITestSeeder'; + + public function testGroupBy() + { + $result = $this->db->table('user') + ->select('name') + ->groupBy('name') + ->get() + ->getResult(); + + $this->assertCount(4, $result); + } + + //-------------------------------------------------------------------- + + public function testHavingBy() + { + $result = $this->db->table('job') + ->select('name') + ->groupBy('name') + ->having('SUM(id) > 2') + ->get() + ->getResultArray(); + + $this->assertCount(2, $result); + } + + //-------------------------------------------------------------------- + + public function testOrHavingBy() + { + $result = $this->db->table('user') + ->groupBy('id') + ->having('id >', 3) + ->orHaving('SUM(id) > 2') + ->get() + ->getResult(); + + $this->assertCount(2, $result); + } + + //-------------------------------------------------------------------- + + public function testAndGroups() + { + $result = $this->db->table('user') + ->groupStart() + ->where('id >=', 3) + ->where('name !=', 'Chris Martin') + ->groupEnd() + ->where('country', 'US') + ->get() + ->getResult(); + + $this->assertCount(1, $result); + $this->assertEquals('Richard A Causey', $result[0]->name); + } + + //-------------------------------------------------------------------- + + public function testOrGroups() + { + $result = $this->db->table('user') + ->where('country', 'Iran') + ->orGroupStart() + ->where('id >=', 3) + ->where('name !=', 'Richard A Causey') + ->groupEnd() + ->get() + ->getResult(); + + $this->assertCount(2, $result); + $this->assertEquals('Ahmadinejad', $result[0]->name); + $this->assertEquals('Chris Martin', $result[1]->name); + } + + //-------------------------------------------------------------------- + + public function testNotGroups() + { + $result = $this->db->table('user') + ->where('country', 'US') + ->notGroupStart() + ->where('id >=', 3) + ->where('name !=', 'Chris Martin') + ->groupEnd() + ->get() + ->getResult(); + + $this->assertCount(1, $result); + $this->assertEquals('Derek Jones', $result[0]->name); + } + + //-------------------------------------------------------------------- + + public function testOrNotGroups() + { + $result = $this->db->table('user') + ->where('country', 'US') + ->orNotGroupStart() + ->where('id >=', 2) + ->where('country', 'Iran') + ->groupEnd() + ->get() + ->getResult(); + + $this->assertCount(3, $result); + $this->assertEquals('Derek Jones', $result[0]->name); + $this->assertEquals('Richard A Causey', $result[1]->name); + $this->assertEquals('Chris Martin', $result[2]->name); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/IncrementTest.php b/tests/system/Database/Live/IncrementTest.php index f85495064820..67efad1bf1d1 100644 --- a/tests/system/Database/Live/IncrementTest.php +++ b/tests/system/Database/Live/IncrementTest.php @@ -5,59 +5,59 @@ */ class IncrementTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testIncrement() - { - $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); + public function testIncrement() + { + $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); - $this->db->table('job') - ->where('name', 'incremental') - ->increment('description'); + $this->db->table('job') + ->where('name', 'incremental') + ->increment('description'); - $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '7']); - } + $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '7']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testIncrementWithValue() - { - $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); + public function testIncrementWithValue() + { + $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); - $this->db->table('job') - ->where('name', 'incremental') - ->increment('description', 2); + $this->db->table('job') + ->where('name', 'incremental') + ->increment('description', 2); - $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '8']); - } + $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '8']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDecrement() - { - $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); + public function testDecrement() + { + $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); - $this->db->table('job') - ->where('name', 'incremental') - ->decrement('description'); + $this->db->table('job') + ->where('name', 'incremental') + ->decrement('description'); - $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '5']); - } + $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '5']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDecrementWithValue() - { - $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); + public function testDecrementWithValue() + { + $this->hasInDatabase('job', ['name' => 'incremental', 'description' => '6']); - $this->db->table('job') - ->where('name', 'incremental') - ->decrement('description', 2); + $this->db->table('job') + ->where('name', 'incremental') + ->decrement('description', 2); - $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '4']); - } + $this->seeInDatabase('job', ['name' => 'incremental', 'description' => '4']); + } - //-------------------------------------------------------------------- -} \ No newline at end of file + //-------------------------------------------------------------------- +} diff --git a/tests/system/Database/Live/InsertTest.php b/tests/system/Database/Live/InsertTest.php index a57d8967d372..8e2740e45964 100644 --- a/tests/system/Database/Live/InsertTest.php +++ b/tests/system/Database/Live/InsertTest.php @@ -5,65 +5,65 @@ */ class InsertTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testInsert() - { - $job_data = ['name' => 'Grocery Sales', 'description' => 'Discount!']; + public function testInsert() + { + $job_data = ['name' => 'Grocery Sales', 'description' => 'Discount!']; - $this->db->table('job')->insert($job_data); + $this->db->table('job')->insert($job_data); - $this->seeInDatabase('job', ['name' => 'Grocery Sales']); - } + $this->seeInDatabase('job', ['name' => 'Grocery Sales']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testInsertBatch() - { - $job_data = [ - ['name' => 'Comedian', 'description' => 'Theres something in your teeth'], - ['name' => 'Cab Driver', 'description' => 'Iam yellow'], - ]; + public function testInsertBatch() + { + $job_data = [ + ['name' => 'Comedian', 'description' => 'Theres something in your teeth'], + ['name' => 'Cab Driver', 'description' => 'Iam yellow'], + ]; - $this->db->table('job')->insertBatch($job_data); + $this->db->table('job')->insertBatch($job_data); - $this->seeInDatabase('job', ['name' => 'Comedian']); - $this->seeInDatabase('job', ['name' => 'Cab Driver']); - } + $this->seeInDatabase('job', ['name' => 'Comedian']); + $this->seeInDatabase('job', ['name' => 'Cab Driver']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testReplaceWithNoMatchingData() - { - $data = ['id' => 5, 'name' => 'Cab Driver', 'description' => 'Iam yellow']; + public function testReplaceWithNoMatchingData() + { + $data = ['id' => 5, 'name' => 'Cab Driver', 'description' => 'Iam yellow']; - $this->db->table('job')->replace($data); + $this->db->table('job')->replace($data); - $row = $this->db->table('job') - ->getwhere(['id' => 5]) - ->getRow(); + $row = $this->db->table('job') + ->getwhere(['id' => 5]) + ->getRow(); - $this->assertEquals('Cab Driver', $row->name); - } + $this->assertEquals('Cab Driver', $row->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testReplaceWithMatchingData() - { - $data = ['id' => 1, 'name' => 'Cab Driver', 'description' => 'Iam yellow']; + public function testReplaceWithMatchingData() + { + $data = ['id' => 1, 'name' => 'Cab Driver', 'description' => 'Iam yellow']; - $this->db->table('job')->replace($data); + $this->db->table('job')->replace($data); - $row = $this->db->table('job') - ->getwhere(['id' => 1]) - ->getRow(); + $row = $this->db->table('job') + ->getwhere(['id' => 1]) + ->getRow(); - $this->assertEquals('Cab Driver', $row->name); - } + $this->assertEquals('Cab Driver', $row->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testBug302() { diff --git a/tests/system/Database/Live/JoinTest.php b/tests/system/Database/Live/JoinTest.php index 003baa138376..ae24ec536687 100644 --- a/tests/system/Database/Live/JoinTest.php +++ b/tests/system/Database/Live/JoinTest.php @@ -5,25 +5,25 @@ */ class JoinTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testSimpleJoin() - { - $row = $this->db->table('job') - ->select('job.id as job_id, job.name as job_name, user.id as user_id, user.name as user_name') - ->join('user', 'user.id = job.id') - ->get() - ->getRow(); + public function testSimpleJoin() + { + $row = $this->db->table('job') + ->select('job.id as job_id, job.name as job_name, user.id as user_id, user.name as user_name') + ->join('user', 'user.id = job.id') + ->get() + ->getRow(); - $this->assertEquals(1, $row->job_id); - $this->assertEquals(1, $row->user_id); - $this->assertEquals('Derek Jones', $row->user_name); - $this->assertEquals('Developer', $row->job_name); - } + $this->assertEquals(1, $row->job_id); + $this->assertEquals(1, $row->user_id); + $this->assertEquals('Derek Jones', $row->user_name); + $this->assertEquals('Developer', $row->job_name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- -} \ No newline at end of file +} diff --git a/tests/system/Database/Live/LikeTest.php b/tests/system/Database/Live/LikeTest.php index 105aae33fbde..3b62f69d0104 100644 --- a/tests/system/Database/Live/LikeTest.php +++ b/tests/system/Database/Live/LikeTest.php @@ -5,122 +5,122 @@ */ class LikeTest extends \CIDatabaseTestCase { - protected $refresh = true; - - protected $seed = 'CITestSeeder'; - - public function testLikeDefault() - { - $job = $this->db->table('job')->like('name', 'veloper')->get(); - $job = $job->getRow(); - - $this->assertEquals(1, $job->id); - $this->assertEquals('Developer', $job->name); - } - - //-------------------------------------------------------------------- + protected $refresh = true; + + protected $seed = 'CITestSeeder'; + + public function testLikeDefault() + { + $job = $this->db->table('job')->like('name', 'veloper')->get(); + $job = $job->getRow(); + + $this->assertEquals(1, $job->id); + $this->assertEquals('Developer', $job->name); + } + + //-------------------------------------------------------------------- - public function testLikeBefore() - { - $job = $this->db->table('job')->like('name', 'veloper', 'before')->get(); - $job = $job->getRow(); - - $this->assertEquals(1, $job->id); - $this->assertEquals('Developer', $job->name); - } - - //-------------------------------------------------------------------- - - public function testLikeAfter() - { - $job = $this->db->table('job')->like('name', 'Develop')->get(); - $job = $job->getRow(); - - $this->assertEquals(1, $job->id); - $this->assertEquals('Developer', $job->name); - } - - //-------------------------------------------------------------------- - - public function testLikeBoth() - { - $job = $this->db->table('job')->like('name', 'veloper', 'both')->get(); - $job = $job->getRow(); - - $this->assertEquals(1, $job->id); - $this->assertEquals('Developer', $job->name); - } - - //-------------------------------------------------------------------- - - public function testLikeCaseInsensitive() - { - $job = $this->db->table('job')->like('name', 'VELOPER', 'both', null, true)->get(); - $job = $job->getRow(); - - $this->assertEquals(1, $job->id); - $this->assertEquals('Developer', $job->name); - } - - //-------------------------------------------------------------------- - - public function testOrLike() - { - $jobs = $this->db->table('job')->like('name', 'ian') - ->orLike('name', 'veloper') - ->get() - ->getResult(); - - $this->assertCount(3, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Politician', $jobs[1]->name); - $this->assertEquals('Musician', $jobs[2]->name); - } - - //-------------------------------------------------------------------- - - public function testNotLike() - { - $jobs = $this->db->table('job') - ->notLike('name', 'veloper') - ->get() - ->getResult(); - - $this->assertCount(3, $jobs); - $this->assertEquals('Politician', $jobs[0]->name); - $this->assertEquals('Accountant', $jobs[1]->name); - $this->assertEquals('Musician', $jobs[2]->name); - } - - //-------------------------------------------------------------------- - - public function testOrNotLike() - { - $jobs = $this->db->table('job') - ->like('name', 'ian') - ->orNotLike('name', 'veloper') - ->get() - ->getResult(); - - $this->assertCount(3, $jobs); - $this->assertEquals('Politician', $jobs[0]->name); - $this->assertEquals('Accountant', $jobs[1]->name); - $this->assertEquals('Musician', $jobs[2]->name); - } - - //-------------------------------------------------------------------- - - public function testLikeSpacesOrTabs() - { - $builder = $this->db->table('misc'); - $spaces = $builder->like('value', ' ')->get()->getResult(); - $tabs = $builder->like('value', "\t")->get()->getResult(); - - $this->assertCount(1, $spaces); - $this->assertCount(1, $tabs); - } - - //-------------------------------------------------------------------- + public function testLikeBefore() + { + $job = $this->db->table('job')->like('name', 'veloper', 'before')->get(); + $job = $job->getRow(); + + $this->assertEquals(1, $job->id); + $this->assertEquals('Developer', $job->name); + } + + //-------------------------------------------------------------------- + + public function testLikeAfter() + { + $job = $this->db->table('job')->like('name', 'Develop')->get(); + $job = $job->getRow(); + + $this->assertEquals(1, $job->id); + $this->assertEquals('Developer', $job->name); + } + + //-------------------------------------------------------------------- + + public function testLikeBoth() + { + $job = $this->db->table('job')->like('name', 'veloper', 'both')->get(); + $job = $job->getRow(); + + $this->assertEquals(1, $job->id); + $this->assertEquals('Developer', $job->name); + } + + //-------------------------------------------------------------------- + + public function testLikeCaseInsensitive() + { + $job = $this->db->table('job')->like('name', 'VELOPER', 'both', null, true)->get(); + $job = $job->getRow(); + + $this->assertEquals(1, $job->id); + $this->assertEquals('Developer', $job->name); + } + + //-------------------------------------------------------------------- + + public function testOrLike() + { + $jobs = $this->db->table('job')->like('name', 'ian') + ->orLike('name', 'veloper') + ->get() + ->getResult(); + + $this->assertCount(3, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Politician', $jobs[1]->name); + $this->assertEquals('Musician', $jobs[2]->name); + } + + //-------------------------------------------------------------------- + + public function testNotLike() + { + $jobs = $this->db->table('job') + ->notLike('name', 'veloper') + ->get() + ->getResult(); + + $this->assertCount(3, $jobs); + $this->assertEquals('Politician', $jobs[0]->name); + $this->assertEquals('Accountant', $jobs[1]->name); + $this->assertEquals('Musician', $jobs[2]->name); + } + + //-------------------------------------------------------------------- + + public function testOrNotLike() + { + $jobs = $this->db->table('job') + ->like('name', 'ian') + ->orNotLike('name', 'veloper') + ->get() + ->getResult(); + + $this->assertCount(3, $jobs); + $this->assertEquals('Politician', $jobs[0]->name); + $this->assertEquals('Accountant', $jobs[1]->name); + $this->assertEquals('Musician', $jobs[2]->name); + } + + //-------------------------------------------------------------------- + + public function testLikeSpacesOrTabs() + { + $builder = $this->db->table('misc'); + $spaces = $builder->like('value', ' ')->get()->getResult(); + $tabs = $builder->like('value', "\t")->get()->getResult(); + + $this->assertCount(1, $spaces); + $this->assertCount(1, $tabs); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/LimitTest.php b/tests/system/Database/Live/LimitTest.php index 69db06406def..5ccb169da535 100644 --- a/tests/system/Database/Live/LimitTest.php +++ b/tests/system/Database/Live/LimitTest.php @@ -5,36 +5,36 @@ */ class LimitTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testLimit() - { - $jobs = $this->db->table('job') - ->limit(2) - ->get() - ->getResult(); + public function testLimit() + { + $jobs = $this->db->table('job') + ->limit(2) + ->get() + ->getResult(); - $this->assertCount(2, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Politician', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Politician', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLimitAndOffset() - { - $jobs = $this->db->table('job') - ->limit(2, 2) - ->get() - ->getResult(); + public function testLimitAndOffset() + { + $jobs = $this->db->table('job') + ->limit(2, 2) + ->get() + ->getResult(); - $this->assertCount(2, $jobs); - $this->assertEquals('Accountant', $jobs[0]->name); - $this->assertEquals('Musician', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Accountant', $jobs[0]->name); + $this->assertEquals('Musician', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/ModelTest.php b/tests/system/Database/Live/ModelTest.php index 60ccbf8014ab..20eabd6f350c 100644 --- a/tests/system/Database/Live/ModelTest.php +++ b/tests/system/Database/Live/ModelTest.php @@ -15,397 +15,397 @@ */ class ModelTest extends \CIDatabaseTestCase { - use ReflectionHelper; + use ReflectionHelper; - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function setUp() - { - parent::setUp(); + public function setUp() + { + parent::setUp(); - $this->model = new Model($this->db); - } + $this->model = new Model($this->db); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindReturnsRow() - { - $model = new JobModel($this->db); + public function testFindReturnsRow() + { + $model = new JobModel($this->db); - $job = $model->find(4); + $job = $model->find(4); - $this->assertEquals('Musician', $job->name); - } + $this->assertEquals('Musician', $job->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindReturnsMultipleRows() - { - $model = new JobModel($this->db); + public function testFindReturnsMultipleRows() + { + $model = new JobModel($this->db); - $job = $model->find([1,4]); + $job = $model->find([1,4]); - $this->assertEquals('Developer', $job[0]->name); - $this->assertEquals('Musician', $job[1]->name); - } + $this->assertEquals('Developer', $job[0]->name); + $this->assertEquals('Musician', $job[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindRespectsReturnArray() - { - $model = new JobModel($this->db); + public function testFindRespectsReturnArray() + { + $model = new JobModel($this->db); - $job = $model->asArray()->find(4); + $job = $model->asArray()->find(4); - $this->assertInternalType('array', $job); - } + $this->assertInternalType('array', $job); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindRespectsReturnObject() - { - $model = new JobModel($this->db); + public function testFindRespectsReturnObject() + { + $model = new JobModel($this->db); - $job = $model->asObject()->find(4); + $job = $model->asObject()->find(4); - $this->assertInternalType('object', $job); - } + $this->assertInternalType('object', $job); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindRespectsSoftDeletes() - { - $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); + public function testFindRespectsSoftDeletes() + { + $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); - $model = new UserModel($this->db); + $model = new UserModel($this->db); - $user = $model->asObject()->find(4); + $user = $model->asObject()->find(4); - $this->assertEmpty($user); + $this->assertEmpty($user); - $user = $model->withDeleted()->find(4); + $user = $model->withDeleted()->find(4); - $this->assertEquals(1, count($user)); - } + $this->assertEquals(1, count($user)); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindWhereSimple() - { - $model = new JobModel($this->db); + public function testFindWhereSimple() + { + $model = new JobModel($this->db); - $jobs = $model->asObject()->findWhere('id >', 2); + $jobs = $model->asObject()->findWhere('id >', 2); - $this->assertCount(2, $jobs); - $this->assertEquals('Accountant', $jobs[0]->name); - $this->assertEquals('Musician', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Accountant', $jobs[0]->name); + $this->assertEquals('Musician', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindWhereWithArrayWhere() - { - $model = new JobModel($this->db); + public function testFindWhereWithArrayWhere() + { + $model = new JobModel($this->db); - $jobs = $model->asArray()->findWhere(['id' => 1]); + $jobs = $model->asArray()->findWhere(['id' => 1]); - $this->assertCount(1, $jobs); - $this->assertEquals('Developer', $jobs[0]['name']); - } + $this->assertCount(1, $jobs); + $this->assertEquals('Developer', $jobs[0]['name']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindWhereRespectsSoftDeletes() - { - $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); + public function testFindWhereRespectsSoftDeletes() + { + $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); - $model = new UserModel($this->db); + $model = new UserModel($this->db); - $user = $model->findWhere('id >', '2'); + $user = $model->findWhere('id >', '2'); - $this->assertCount(1, $user); + $this->assertCount(1, $user); - $user = $model->withDeleted()->findWhere('id >', 2); + $user = $model->withDeleted()->findWhere('id >', 2); - $this->assertCount(2, $user); - } + $this->assertCount(2, $user); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindAllReturnsAllRecords() - { - $model = new UserModel($this->db); + public function testFindAllReturnsAllRecords() + { + $model = new UserModel($this->db); - $users = $model->findAll(); + $users = $model->findAll(); - $this->assertCount(4, $users); - } + $this->assertCount(4, $users); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindAllRespectsLimits() - { - $model = new UserModel($this->db); + public function testFindAllRespectsLimits() + { + $model = new UserModel($this->db); - $users = $model->findAll(2); + $users = $model->findAll(2); - $this->assertCount(2, $users); - $this->assertEquals('Derek Jones', $users[0]->name); - } + $this->assertCount(2, $users); + $this->assertEquals('Derek Jones', $users[0]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindAllRespectsLimitsAndOffset() - { - $model = new UserModel($this->db); + public function testFindAllRespectsLimitsAndOffset() + { + $model = new UserModel($this->db); - $users = $model->findAll(2, 2); + $users = $model->findAll(2, 2); - $this->assertCount(2, $users); - $this->assertEquals('Richard A Causey', $users[0]->name); - } + $this->assertCount(2, $users); + $this->assertEquals('Richard A Causey', $users[0]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFindAllRespectsSoftDeletes() - { - $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); + public function testFindAllRespectsSoftDeletes() + { + $this->db->table('user')->where('id', 4)->update(['deleted' => 1]); - $model = new UserModel($this->db); + $model = new UserModel($this->db); - $user = $model->findAll(); + $user = $model->findAll(); - $this->assertCount(3, $user); + $this->assertCount(3, $user); - $user = $model->withDeleted()->findAll(); + $user = $model->withDeleted()->findAll(); - $this->assertCount(4, $user); - } + $this->assertCount(4, $user); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFirst() - { - $model = new UserModel(); + public function testFirst() + { + $model = new UserModel(); - $user = $model->where('id >', 2)->first(); + $user = $model->where('id >', 2)->first(); - $this->assertEquals(1, count($user)); - $this->assertEquals(3, $user->id); - } + $this->assertEquals(1, count($user)); + $this->assertEquals(3, $user->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testFirstRespectsSoftDeletes() - { - $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); + public function testFirstRespectsSoftDeletes() + { + $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); - $model = new UserModel(); + $model = new UserModel(); - $user = $model->first(); + $user = $model->first(); - $this->assertEquals(1, count($user)); - $this->assertEquals(2, $user->id); + $this->assertEquals(1, count($user)); + $this->assertEquals(2, $user->id); - $user = $model->withDeleted()->first(); + $user = $model->withDeleted()->first(); - $this->assertEquals(1, $user->id); - } + $this->assertEquals(1, $user->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSaveNewRecordObject() - { - $model = new JobModel(); + public function testSaveNewRecordObject() + { + $model = new JobModel(); - $data = new \stdClass(); - $data->name = 'Magician'; - $data->description = 'Makes peoples things dissappear.'; + $data = new \stdClass(); + $data->name = 'Magician'; + $data->description = 'Makes peoples things dissappear.'; - $model->protect(false)->save($data); + $model->protect(false)->save($data); - $this->seeInDatabase('job', ['name' => 'Magician']); - } + $this->seeInDatabase('job', ['name' => 'Magician']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSaveNewRecordArray() - { - $model = new JobModel(); + public function testSaveNewRecordArray() + { + $model = new JobModel(); - $data = [ - 'name' => 'Apprentice', - 'description' => 'That thing you do.' - ]; + $data = [ + 'name' => 'Apprentice', + 'description' => 'That thing you do.' + ]; - $result = $model->protect(false)->save($data); + $result = $model->protect(false)->save($data); - $this->seeInDatabase('job', ['name' => 'Apprentice']); - } + $this->seeInDatabase('job', ['name' => 'Apprentice']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSaveUpdateRecordObject() - { - $model = new JobModel(); + public function testSaveUpdateRecordObject() + { + $model = new JobModel(); - $data = [ - 'id' => 1, - 'name' => 'Apprentice', - 'description' => 'That thing you do.' - ]; + $data = [ + 'id' => 1, + 'name' => 'Apprentice', + 'description' => 'That thing you do.' + ]; - $result = $model->protect(false)->save($data); + $result = $model->protect(false)->save($data); - $this->seeInDatabase('job', ['name' => 'Apprentice']); - $this->assertTrue($result); - } + $this->seeInDatabase('job', ['name' => 'Apprentice']); + $this->assertTrue($result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSaveUpdateRecordArray() - { - $model = new JobModel(); + public function testSaveUpdateRecordArray() + { + $model = new JobModel(); - $data = new \stdClass(); - $data->id = 1; - $data->name = 'Engineer'; - $data->description = 'A fancier term for Developer.'; + $data = new \stdClass(); + $data->id = 1; + $data->name = 'Engineer'; + $data->description = 'A fancier term for Developer.'; - $result = $model->protect(false)->save($data); + $result = $model->protect(false)->save($data); - $this->seeInDatabase('job', ['name' => 'Engineer']); - $this->assertTrue($result); - } + $this->seeInDatabase('job', ['name' => 'Engineer']); + $this->assertTrue($result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSaveProtected() - { - $model = new JobModel(); + public function testSaveProtected() + { + $model = new JobModel(); - $data = new \stdClass(); - $data->id = 1; - $data->name = 'Engineer'; - $data->description = 'A fancier term for Developer.'; - $data->random_thing = 'Something wicked'; // If not protected, this would kill the script. + $data = new \stdClass(); + $data->id = 1; + $data->name = 'Engineer'; + $data->description = 'A fancier term for Developer.'; + $data->random_thing = 'Something wicked'; // If not protected, this would kill the script. - $result = $model->protect(true)->save($data); + $result = $model->protect(true)->save($data); $this->assertTrue($result); - } + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteBasics() - { - $model = new JobModel(); + public function testDeleteBasics() + { + $model = new JobModel(); - $this->seeInDatabase('job', ['name' =>'Developer']); + $this->seeInDatabase('job', ['name' =>'Developer']); - $model->delete(1); + $model->delete(1); - $this->dontSeeInDatabase('job', ['name' => 'Developer']); - } + $this->dontSeeInDatabase('job', ['name' => 'Developer']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWithSoftDeletes() - { - $model = new UserModel(); + public function testDeleteWithSoftDeletes() + { + $model = new UserModel(); - $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); + $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); - $model->delete(1); + $model->delete(1); - $this->seeInDatabase('user', ['name' => 'Derek Jones', 'deleted' => 1]); - } + $this->seeInDatabase('user', ['name' => 'Derek Jones', 'deleted' => 1]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWithSoftDeletesPurge() - { - $model = new UserModel(); + public function testDeleteWithSoftDeletesPurge() + { + $model = new UserModel(); - $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); + $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); - $model->delete(1, true); + $model->delete(1, true); - $this->dontSeeInDatabase('user', ['name' => 'Derek Jones']); - } + $this->dontSeeInDatabase('user', ['name' => 'Derek Jones']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWhereWithSoftDeletes() - { - $model = new UserModel(); + public function testDeleteWhereWithSoftDeletes() + { + $model = new UserModel(); - $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); + $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); - $model->deleteWhere('name', 'Derek Jones'); + $model->deleteWhere('name', 'Derek Jones'); - $this->seeInDatabase('user', ['name' => 'Derek Jones', 'deleted' => 1]); - } + $this->seeInDatabase('user', ['name' => 'Derek Jones', 'deleted' => 1]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteWhereWithSoftDeletesPurge() - { - $model = new UserModel(); + public function testDeleteWhereWithSoftDeletesPurge() + { + $model = new UserModel(); - $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); + $this->seeInDatabase('user', ['name' =>'Derek Jones', 'deleted' => 0]); - $model->deleteWhere('name', 'Derek Jones', true); + $model->deleteWhere('name', 'Derek Jones', true); - $this->dontSeeInDatabase('user', ['name' => 'Derek Jones']); - } + $this->dontSeeInDatabase('user', ['name' => 'Derek Jones']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPurgeDeleted() - { - $model = new UserModel(); + public function testPurgeDeleted() + { + $model = new UserModel(); - $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); + $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); - $model->purgeDeleted(); + $model->purgeDeleted(); - $users = $model->withDeleted()->findAll(); + $users = $model->withDeleted()->findAll(); - $this->assertCount(3, $users); - } + $this->assertCount(3, $users); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testOnlyDeleted() - { - $model = new UserModel($this->db); + public function testOnlyDeleted() + { + $model = new UserModel($this->db); - $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); + $this->db->table('user')->where('id', 1)->update(['deleted' => 1]); - $users = $model->onlyDeleted()->findAll(); + $users = $model->onlyDeleted()->findAll(); - $this->assertCount(1, $users); - } + $this->assertCount(1, $users); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testChunk() - { - $model = new UserModel(); + public function testChunk() + { + $model = new UserModel(); - $rowCount = 0; + $rowCount = 0; - $model->chunk(2, function($row) use (&$rowCount) { - $rowCount++; - }); + $model->chunk(2, function($row) use (&$rowCount) { + $rowCount++; + }); - $this->assertEquals(4, $rowCount); - } + $this->assertEquals(4, $rowCount); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testValidationBasics() { @@ -424,33 +424,33 @@ public function testValidationBasics() //-------------------------------------------------------------------- - public function testValidationPlaceholdersSuccess() - { - $model = new ValidModel($this->db); + public function testValidationPlaceholdersSuccess() + { + $model = new ValidModel($this->db); - $data = [ - 'name' => 'abc', - 'id' => 13, - 'token' => 13 - ]; + $data = [ + 'name' => 'abc', + 'id' => 13, + 'token' => 13 + ]; - $this->assertTrue($model->validate($data)); - } + $this->assertTrue($model->validate($data)); + } - public function testValidationPlaceholdersFail() - { - $model = new ValidModel($this->db); + public function testValidationPlaceholdersFail() + { + $model = new ValidModel($this->db); - $data = [ - 'name' => 'abc', - 'id' => 13, - 'token' => 12 - ]; + $data = [ + 'name' => 'abc', + 'id' => 13, + 'token' => 12 + ]; - $this->assertFalse($model->validate($data)); - } + $this->assertFalse($model->validate($data)); + } - public function testSkipValidation() + public function testSkipValidation() { $model = new ValidModel($this->db); @@ -485,77 +485,77 @@ public function testCanCreateAndSaveEntityClasses() $this->seeInDatabase('job', ['name' => 'Senior Developer', 'created_at' => '2017-07-15 00:00:00']); } - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/580 - */ - public function testPasswordsStoreCorrectly() + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/580 + */ + public function testPasswordsStoreCorrectly() { - $model = new UserModel(); + $model = new UserModel(); - $pass = password_hash('secret123', PASSWORD_BCRYPT); + $pass = password_hash('secret123', PASSWORD_BCRYPT); - $data = [ - 'name' => $pass, - 'email' => 'foo@example.com', - 'country' => 'US', - 'deleted' => 0 - ]; + $data = [ + 'name' => $pass, + 'email' => 'foo@example.com', + 'country' => 'US', + 'deleted' => 0 + ]; - $model->insert($data); + $model->insert($data); - $this->seeInDatabase('user', $data); + $this->seeInDatabase('user', $data); } - public function testInsertEvent() - { - $model = new EventModel(); + public function testInsertEvent() + { + $model = new EventModel(); - $data = [ - 'name' => 'Foo', - 'email' => 'foo@example.com', - 'country' => 'US', - 'deleted' => 0 - ]; + $data = [ + 'name' => 'Foo', + 'email' => 'foo@example.com', + 'country' => 'US', + 'deleted' => 0 + ]; - $model->insert($data); + $model->insert($data); - $this->assertTrue($model->hasToken('beforeInsert')); - $this->assertTrue($model->hasToken('afterInsert')); + $this->assertTrue($model->hasToken('beforeInsert')); + $this->assertTrue($model->hasToken('afterInsert')); } - public function testUpdateEvent() - { - $model = new EventModel(); + public function testUpdateEvent() + { + $model = new EventModel(); - $data = [ - 'name' => 'Foo', - 'email' => 'foo@example.com', - 'country' => 'US', - 'deleted' => 0 - ]; + $data = [ + 'name' => 'Foo', + 'email' => 'foo@example.com', + 'country' => 'US', + 'deleted' => 0 + ]; - $id = $model->insert($data); - $model->update($id, $data); + $id = $model->insert($data); + $model->update($id, $data); - $this->assertTrue($model->hasToken('beforeUpdate')); - $this->assertTrue($model->hasToken('afterUpdate')); - } + $this->assertTrue($model->hasToken('beforeUpdate')); + $this->assertTrue($model->hasToken('afterUpdate')); + } - public function testFindEvent() - { - $model = new EventModel(); + public function testFindEvent() + { + $model = new EventModel(); - $model->find(1); + $model->find(1); - $this->assertTrue($model->hasToken('afterFind')); - } + $this->assertTrue($model->hasToken('afterFind')); + } - public function testDeleteEvent() - { - $model = new EventModel(); + public function testDeleteEvent() + { + $model = new EventModel(); - $model->delete(1); + $model->delete(1); - $this->assertTrue($model->hasToken('afterDelete')); - } + $this->assertTrue($model->hasToken('afterDelete')); + } } diff --git a/tests/system/Database/Live/OrderTest.php b/tests/system/Database/Live/OrderTest.php index c1e36e768c24..ec1af650863f 100644 --- a/tests/system/Database/Live/OrderTest.php +++ b/tests/system/Database/Live/OrderTest.php @@ -5,58 +5,58 @@ */ class OrderTest extends \CIDatabaseTestCase { - protected $refresh = true; - - protected $seed = 'CITestSeeder'; - - public function testOrderAscending() - { - $jobs = $this->db->table('job') - ->orderBy('name', 'asc') - ->get() - ->getResult(); - - $this->assertCount(4, $jobs); - $this->assertEquals('Accountant', $jobs[0]->name); - $this->assertEquals('Developer', $jobs[1]->name); - $this->assertEquals('Musician', $jobs[2]->name); - $this->assertEquals('Politician', $jobs[3]->name); - } - - //-------------------------------------------------------------------- - - public function testOrderDescending() - { - $jobs = $this->db->table('job') - ->orderBy('name', 'desc') - ->get() - ->getResult(); - - $this->assertCount(4, $jobs); - $this->assertEquals('Accountant', $jobs[3]->name); - $this->assertEquals('Developer', $jobs[2]->name); - $this->assertEquals('Musician', $jobs[1]->name); - $this->assertEquals('Politician', $jobs[0]->name); - } - - //-------------------------------------------------------------------- - - public function testMultipleOrderValues() - { - $users = $this->db->table('user') - ->orderBy('country', 'asc') - ->orderBy('name', 'desc') - ->get() - ->getResult(); - - $this->assertCount(4, $users); - $this->assertEquals('Ahmadinejad', $users[0]->name); - $this->assertEquals('Chris Martin', $users[1]->name); - $this->assertEquals('Richard A Causey', $users[2]->name); - $this->assertEquals('Derek Jones', $users[3]->name); - } - - //-------------------------------------------------------------------- + protected $refresh = true; + + protected $seed = 'CITestSeeder'; + + public function testOrderAscending() + { + $jobs = $this->db->table('job') + ->orderBy('name', 'asc') + ->get() + ->getResult(); + + $this->assertCount(4, $jobs); + $this->assertEquals('Accountant', $jobs[0]->name); + $this->assertEquals('Developer', $jobs[1]->name); + $this->assertEquals('Musician', $jobs[2]->name); + $this->assertEquals('Politician', $jobs[3]->name); + } + + //-------------------------------------------------------------------- + + public function testOrderDescending() + { + $jobs = $this->db->table('job') + ->orderBy('name', 'desc') + ->get() + ->getResult(); + + $this->assertCount(4, $jobs); + $this->assertEquals('Accountant', $jobs[3]->name); + $this->assertEquals('Developer', $jobs[2]->name); + $this->assertEquals('Musician', $jobs[1]->name); + $this->assertEquals('Politician', $jobs[0]->name); + } + + //-------------------------------------------------------------------- + + public function testMultipleOrderValues() + { + $users = $this->db->table('user') + ->orderBy('country', 'asc') + ->orderBy('name', 'desc') + ->get() + ->getResult(); + + $this->assertCount(4, $users); + $this->assertEquals('Ahmadinejad', $users[0]->name); + $this->assertEquals('Chris Martin', $users[1]->name); + $this->assertEquals('Richard A Causey', $users[2]->name); + $this->assertEquals('Derek Jones', $users[3]->name); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/PreparedQueryTest.php b/tests/system/Database/Live/PreparedQueryTest.php index e92ffd5c883b..2e43ce537db1 100644 --- a/tests/system/Database/Live/PreparedQueryTest.php +++ b/tests/system/Database/Live/PreparedQueryTest.php @@ -7,60 +7,60 @@ */ class PreparedQueryTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPrepareReturnsPreparedQuery() - { - $query = $this->db->prepare(function($db){ - return $db->table('user')->insert([ - 'name' => 'a', - 'email' => 'b@example.com' - ]); - }); + public function testPrepareReturnsPreparedQuery() + { + $query = $this->db->prepare(function($db){ + return $db->table('user')->insert([ + 'name' => 'a', + 'email' => 'b@example.com' + ]); + }); - $this->assertInstanceOf(BasePreparedQuery::class, $query); + $this->assertInstanceOf(BasePreparedQuery::class, $query); - $ec = $this->db->escapeChar; - $pre = $this->db->DBPrefix; + $ec = $this->db->escapeChar; + $pre = $this->db->DBPrefix; - $placeholders = '?, ?'; + $placeholders = '?, ?'; - if ($this->db->DBDriver == 'Postgre') - { - $placeholders = '$1, $2'; - } + if ($this->db->DBDriver == 'Postgre') + { + $placeholders = '$1, $2'; + } - $expected = "INSERT INTO {$ec}{$pre}user{$ec} ({$ec}name{$ec}, {$ec}email{$ec}) VALUES ({$placeholders})"; - $this->assertEquals($expected, $query->getQueryString()); + $expected = "INSERT INTO {$ec}{$pre}user{$ec} ({$ec}name{$ec}, {$ec}email{$ec}) VALUES ({$placeholders})"; + $this->assertEquals($expected, $query->getQueryString()); - $query->close(); - } + $query->close(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testExecuteRunsQueryAndReturnsResultObject() - { - $query = $this->db->prepare(function($db){ - return $db->table('user')->insert([ - 'name' => 'a', - 'email' => 'b@example.com', - 'country' => 'x' - ]); - }); + public function testExecuteRunsQueryAndReturnsResultObject() + { + $query = $this->db->prepare(function($db){ + return $db->table('user')->insert([ + 'name' => 'a', + 'email' => 'b@example.com', + 'country' => 'x' + ]); + }); - $query->execute('foo', 'foo@example.com', 'US'); - $query->execute('bar', 'bar@example.com', 'GB'); + $query->execute('foo', 'foo@example.com', 'US'); + $query->execute('bar', 'bar@example.com', 'GB'); - $this->seeInDatabase($this->db->DBPrefix.'user', ['name' => 'foo', 'email' => 'foo@example.com']); - $this->seeInDatabase($this->db->DBPrefix.'user', ['name' => 'bar', 'email' => 'bar@example.com']); + $this->seeInDatabase($this->db->DBPrefix.'user', ['name' => 'foo', 'email' => 'foo@example.com']); + $this->seeInDatabase($this->db->DBPrefix.'user', ['name' => 'bar', 'email' => 'bar@example.com']); - $query->close(); - } + $query->close(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/PretendTest.php b/tests/system/Database/Live/PretendTest.php index cc59bec12d55..deb2ff1b5447 100644 --- a/tests/system/Database/Live/PretendTest.php +++ b/tests/system/Database/Live/PretendTest.php @@ -7,27 +7,27 @@ */ class PretendTest extends \CIDatabaseTestCase { - public function tearDown() - { - // We share `$this->db` in testing, so we need to restore the state. - $this->db->pretend(false); - } + public function tearDown() + { + // We share `$this->db` in testing, so we need to restore the state. + $this->db->pretend(false); + } - public function testPretendReturnsQueryObject() - { - $result = $this->db->pretend(false) - ->table('user') - ->get(); + public function testPretendReturnsQueryObject() + { + $result = $this->db->pretend(false) + ->table('user') + ->get(); - $this->assertFalse($result instanceof Query); + $this->assertFalse($result instanceof Query); - $result = $this->db->pretend(true) - ->table('user') - ->get(); + $result = $this->db->pretend(true) + ->table('user') + ->get(); - $this->assertInstanceOf(Query::class, $result); - } + $this->assertInstanceOf(Query::class, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/SelectTest.php b/tests/system/Database/Live/SelectTest.php index e4d2b1c3cebf..ac3cd728b29b 100644 --- a/tests/system/Database/Live/SelectTest.php +++ b/tests/system/Database/Live/SelectTest.php @@ -6,132 +6,132 @@ */ class SelectTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectAllByDefault() - { - $row = $this->db->table('job')->get()->getRowArray(); + public function testSelectAllByDefault() + { + $row = $this->db->table('job')->get()->getRowArray(); - $this->assertArrayHasKey('id', $row); - $this->assertArrayHasKey('name', $row); - $this->assertArrayHasKey('description', $row); - } + $this->assertArrayHasKey('id', $row); + $this->assertArrayHasKey('name', $row); + $this->assertArrayHasKey('description', $row); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectSingleColumn() - { - $row = $this->db->table('job')->select('name')->get()->getRowArray(); + public function testSelectSingleColumn() + { + $row = $this->db->table('job')->select('name')->get()->getRowArray(); - $this->assertArrayNotHasKey('id', $row); - $this->assertArrayHasKey('name', $row); - $this->assertArrayNotHasKey('description', $row); - } + $this->assertArrayNotHasKey('id', $row); + $this->assertArrayHasKey('name', $row); + $this->assertArrayNotHasKey('description', $row); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectMultipleColumns() - { - $row = $this->db->table('job')->select('name, description')->get()->getRowArray(); + public function testSelectMultipleColumns() + { + $row = $this->db->table('job')->select('name, description')->get()->getRowArray(); - $this->assertArrayNotHasKey('id', $row); - $this->assertArrayHasKey('name', $row); - $this->assertArrayHasKey('description', $row); - } + $this->assertArrayNotHasKey('id', $row); + $this->assertArrayHasKey('name', $row); + $this->assertArrayHasKey('description', $row); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectMax() - { - $result = $this->db->table('job')->selectMax('id')->get()->getRow(); + public function testSelectMax() + { + $result = $this->db->table('job')->selectMax('id')->get()->getRow(); - $this->assertEquals(4, $result->id); - } + $this->assertEquals(4, $result->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectMaxWithAlias() - { - $result = $this->db->table('job')->selectMax('id', 'xam')->get()->getRow(); + public function testSelectMaxWithAlias() + { + $result = $this->db->table('job')->selectMax('id', 'xam')->get()->getRow(); - $this->assertEquals(4, $result->xam); - } + $this->assertEquals(4, $result->xam); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectMin() - { - $result = $this->db->table('job')->selectMin('id')->get()->getRow(); + public function testSelectMin() + { + $result = $this->db->table('job')->selectMin('id')->get()->getRow(); - $this->assertEquals(1, $result->id); - } + $this->assertEquals(1, $result->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectMinWithAlias() - { - $result = $this->db->table('job')->selectMin('id', 'xam')->get()->getRow(); + public function testSelectMinWithAlias() + { + $result = $this->db->table('job')->selectMin('id', 'xam')->get()->getRow(); - $this->assertEquals(1, $result->xam); - } + $this->assertEquals(1, $result->xam); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectAvg() - { - $result = $this->db->table('job')->selectAvg('id')->get()->getRow(); + public function testSelectAvg() + { + $result = $this->db->table('job')->selectAvg('id')->get()->getRow(); - $this->assertEquals(2.5, $result->id); - } + $this->assertEquals(2.5, $result->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectAvgWitAlias() - { - $result = $this->db->table('job')->selectAvg('id', 'xam')->get()->getRow(); + public function testSelectAvgWitAlias() + { + $result = $this->db->table('job')->selectAvg('id', 'xam')->get()->getRow(); - $this->assertEquals(2.5, $result->xam); - } + $this->assertEquals(2.5, $result->xam); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectSum() - { - $result = $this->db->table('job')->selectSum('id')->get()->getRow(); + public function testSelectSum() + { + $result = $this->db->table('job')->selectSum('id')->get()->getRow(); - $this->assertEquals(10, $result->id); - } + $this->assertEquals(10, $result->id); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectSumWitAlias() - { - $result = $this->db->table('job')->selectSum('id', 'xam')->get()->getRow(); + public function testSelectSumWitAlias() + { + $result = $this->db->table('job')->selectSum('id', 'xam')->get()->getRow(); - $this->assertEquals(10, $result->xam); - } + $this->assertEquals(10, $result->xam); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectDistinctWorkTogether() - { - $users = $this->db->table('user')->select('country')->distinct()->get()->getResult(); + public function testSelectDistinctWorkTogether() + { + $users = $this->db->table('user')->select('country')->distinct()->get()->getResult(); - $this->assertCount(3, $users); - } + $this->assertCount(3, $users); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSelectDistinctCanBeTurnedOff() - { - $users = $this->db->table('user')->select('country')->distinct(false)->get()->getResult(); + public function testSelectDistinctCanBeTurnedOff() + { + $users = $this->db->table('user')->select('country')->distinct(false)->get()->getResult(); - $this->assertCount(4, $users); - } + $this->assertCount(4, $users); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Database/Live/UpdateTest.php b/tests/system/Database/Live/UpdateTest.php index 8971b28eef77..25b366c3b6c6 100644 --- a/tests/system/Database/Live/UpdateTest.php +++ b/tests/system/Database/Live/UpdateTest.php @@ -7,200 +7,200 @@ */ class UpdateTest extends \CIDatabaseTestCase { - protected $refresh = true; - - protected $seed = 'CITestSeeder'; - - public function testUpdateSetsAllWithoutWhere() - { - $this->db->table('user') - ->update(['name' => 'Bobby']); - - $result = $this->db->table('user')->get()->getResult(); - - $this->assertEquals('Bobby', $result[0]->name); - $this->assertEquals('Bobby', $result[1]->name); - $this->assertEquals('Bobby', $result[2]->name); - $this->assertEquals('Bobby', $result[3]->name); - } - - //-------------------------------------------------------------------- - - public function testUpdateSetsAllWithoutWhereAndLimit() - { - try - { - $this->db->table('user') - ->update(['name' => 'Bobby'], null, 1); - - $result = $this->db->table('user') - ->orderBy('id', 'asc') - ->get() - ->getResult(); - - $this->assertEquals('Bobby', $result[0]->name); - $this->assertEquals('Ahmadinejad', $result[1]->name); - $this->assertEquals('Richard A Causey', $result[2]->name); - $this->assertEquals('Chris Martin', $result[3]->name); - } - catch (DatabaseException $e) - { - // This DB doesn't support Where and Limit together - // but we don't want it called a "Risky" test. - $this->assertTrue(true); - return; - } - } - - //-------------------------------------------------------------------- - - public function testUpdateWithWhere() - { - $this->db->table('user') - ->update(['name' => 'Bobby'], ['country' => 'US']); - - $result = $this->db->table('user')->get()->getResultArray(); - - $rows = []; - - foreach ($result as $row) - { - if ($row['name'] == 'Bobby') - { - $rows[] = $row; - } - } - - $this->assertCount(2, $rows); - } - - //-------------------------------------------------------------------- - - public function testUpdateWithWhereAndLimit() - { - try - { - $this->db->table('user') - ->update(['name' => 'Bobby'], ['country' => 'US'], 1); - - $result = $this->db->table('user') - ->get() - ->getResult(); - - $this->assertEquals('Bobby', $result[0]->name); - $this->assertEquals('Ahmadinejad', $result[1]->name); - $this->assertEquals('Richard A Causey', $result[2]->name); - $this->assertEquals('Chris Martin', $result[3]->name); - } - catch (DatabaseException $e) - { - // This DB doesn't support Where and Limit together - // but we don't want it called a "Risky" test. - $this->assertTrue(true); - return; - } - } - - //-------------------------------------------------------------------- - - public function testUpdateBatch() - { - $data = [ - [ - 'name' => 'Derek Jones', - 'country' => 'Greece' - ], - [ - 'name' => 'Ahmadinejad', - 'country' => 'Greece' - ], - ]; - - $this->db->table('user') - ->updateBatch($data, 'name'); - - $this->seeInDatabase('user', [ - 'name' => 'Derek Jones', - 'country' => 'Greece' - ]); - $this->seeInDatabase('user', [ - 'name' => 'Ahmadinejad', - 'country' => 'Greece' - ]); - } - - //-------------------------------------------------------------------- - - public function testUpdateWithWhereSameColumn() - { - $this->db->table('user') - ->update(['country' => 'CA'], ['country' => 'US']); - - $result = $this->db->table('user')->get()->getResultArray(); - - $rows = []; - - foreach ($result as $row) - { - if ($row['country'] == 'CA') - { - $rows[] = $row; - } - } - - $this->assertCount(2, $rows); - } - - //-------------------------------------------------------------------- - - public function testUpdateWithWhereSameColumn2() - { - // calling order: set() -> where() - $this->db->table('user') - ->set('country', 'CA') - ->where('country', 'US') - ->update(); - - $result = $this->db->table('user')->get()->getResultArray(); - - $rows = []; - - foreach ($result as $row) - { - if ($row['country'] == 'CA') - { - $rows[] = $row; - } - } - - $this->assertCount(2, $rows); - } - - //-------------------------------------------------------------------- - - public function testUpdateWithWhereSameColumn3() - { - // calling order: where() -> set() in update() - $this->db->table('user') - ->where('country', 'US') - ->update(['country' => 'CA']); - - $result = $this->db->table('user')->get()->getResultArray(); - - $rows = []; - - foreach ($result as $row) - { - if ($row['country'] == 'CA') - { - $rows[] = $row; - } - } - - $this->assertCount(2, $rows); - } - - //-------------------------------------------------------------------- + protected $refresh = true; + + protected $seed = 'CITestSeeder'; + + public function testUpdateSetsAllWithoutWhere() + { + $this->db->table('user') + ->update(['name' => 'Bobby']); + + $result = $this->db->table('user')->get()->getResult(); + + $this->assertEquals('Bobby', $result[0]->name); + $this->assertEquals('Bobby', $result[1]->name); + $this->assertEquals('Bobby', $result[2]->name); + $this->assertEquals('Bobby', $result[3]->name); + } + + //-------------------------------------------------------------------- + + public function testUpdateSetsAllWithoutWhereAndLimit() + { + try + { + $this->db->table('user') + ->update(['name' => 'Bobby'], null, 1); + + $result = $this->db->table('user') + ->orderBy('id', 'asc') + ->get() + ->getResult(); + + $this->assertEquals('Bobby', $result[0]->name); + $this->assertEquals('Ahmadinejad', $result[1]->name); + $this->assertEquals('Richard A Causey', $result[2]->name); + $this->assertEquals('Chris Martin', $result[3]->name); + } + catch (DatabaseException $e) + { + // This DB doesn't support Where and Limit together + // but we don't want it called a "Risky" test. + $this->assertTrue(true); + return; + } + } + + //-------------------------------------------------------------------- + + public function testUpdateWithWhere() + { + $this->db->table('user') + ->update(['name' => 'Bobby'], ['country' => 'US']); + + $result = $this->db->table('user')->get()->getResultArray(); + + $rows = []; + + foreach ($result as $row) + { + if ($row['name'] == 'Bobby') + { + $rows[] = $row; + } + } + + $this->assertCount(2, $rows); + } + + //-------------------------------------------------------------------- + + public function testUpdateWithWhereAndLimit() + { + try + { + $this->db->table('user') + ->update(['name' => 'Bobby'], ['country' => 'US'], 1); + + $result = $this->db->table('user') + ->get() + ->getResult(); + + $this->assertEquals('Bobby', $result[0]->name); + $this->assertEquals('Ahmadinejad', $result[1]->name); + $this->assertEquals('Richard A Causey', $result[2]->name); + $this->assertEquals('Chris Martin', $result[3]->name); + } + catch (DatabaseException $e) + { + // This DB doesn't support Where and Limit together + // but we don't want it called a "Risky" test. + $this->assertTrue(true); + return; + } + } + + //-------------------------------------------------------------------- + + public function testUpdateBatch() + { + $data = [ + [ + 'name' => 'Derek Jones', + 'country' => 'Greece' + ], + [ + 'name' => 'Ahmadinejad', + 'country' => 'Greece' + ], + ]; + + $this->db->table('user') + ->updateBatch($data, 'name'); + + $this->seeInDatabase('user', [ + 'name' => 'Derek Jones', + 'country' => 'Greece' + ]); + $this->seeInDatabase('user', [ + 'name' => 'Ahmadinejad', + 'country' => 'Greece' + ]); + } + + //-------------------------------------------------------------------- + + public function testUpdateWithWhereSameColumn() + { + $this->db->table('user') + ->update(['country' => 'CA'], ['country' => 'US']); + + $result = $this->db->table('user')->get()->getResultArray(); + + $rows = []; + + foreach ($result as $row) + { + if ($row['country'] == 'CA') + { + $rows[] = $row; + } + } + + $this->assertCount(2, $rows); + } + + //-------------------------------------------------------------------- + + public function testUpdateWithWhereSameColumn2() + { + // calling order: set() -> where() + $this->db->table('user') + ->set('country', 'CA') + ->where('country', 'US') + ->update(); + + $result = $this->db->table('user')->get()->getResultArray(); + + $rows = []; + + foreach ($result as $row) + { + if ($row['country'] == 'CA') + { + $rows[] = $row; + } + } + + $this->assertCount(2, $rows); + } + + //-------------------------------------------------------------------- + + public function testUpdateWithWhereSameColumn3() + { + // calling order: where() -> set() in update() + $this->db->table('user') + ->where('country', 'US') + ->update(['country' => 'CA']); + + $result = $this->db->table('user')->get()->getResultArray(); + + $rows = []; + + foreach ($result as $row) + { + if ($row['country'] == 'CA') + { + $rows[] = $row; + } + } + + $this->assertCount(2, $rows); + } + + //-------------------------------------------------------------------- /** * @group single @@ -219,21 +219,21 @@ public function testUpdatePeriods() ]); } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - // @see https://bcit-ci.github.io/CodeIgniter4/database/query_builder.html#updating-data - public function testSetWithoutEscape() - { - $this->db->table('job') - ->set('description', 'name', false) - ->update(); + // @see https://bcit-ci.github.io/CodeIgniter4/database/query_builder.html#updating-data + public function testSetWithoutEscape() + { + $this->db->table('job') + ->set('description', 'name', false) + ->update(); - $result = $this->db->table('user')->get()->getResultArray(); + $result = $this->db->table('user')->get()->getResultArray(); - $this->seeInDatabase('job', [ - 'name' => 'Developer', - 'description' => 'Developer', - ]); - } + $this->seeInDatabase('job', [ + 'name' => 'Developer', + 'description' => 'Developer', + ]); + } } diff --git a/tests/system/Database/Live/WhereTest.php b/tests/system/Database/Live/WhereTest.php index eb241ad026fa..102df7cb66bb 100644 --- a/tests/system/Database/Live/WhereTest.php +++ b/tests/system/Database/Live/WhereTest.php @@ -5,118 +5,118 @@ */ class WhereTest extends \CIDatabaseTestCase { - protected $refresh = true; + protected $refresh = true; - protected $seed = 'CITestSeeder'; + protected $seed = 'CITestSeeder'; - public function testWhereSimpleKeyValue() - { - $row = $this->db->table('job')->where('id', 1)->get()->getRow(); + public function testWhereSimpleKeyValue() + { + $row = $this->db->table('job')->where('id', 1)->get()->getRow(); - $this->assertEquals(1, $row->id); - $this->assertEquals('Developer', $row->name); - } + $this->assertEquals(1, $row->id); + $this->assertEquals('Developer', $row->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testWhereCustomKeyValue() - { - $jobs = $this->db->table('job')->where('id !=', 1)->get()->getResult(); + public function testWhereCustomKeyValue() + { + $jobs = $this->db->table('job')->where('id !=', 1)->get()->getResult(); - $this->assertCount(3, $jobs); - } + $this->assertCount(3, $jobs); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testWhereArray() - { - $jobs = $this->db->table('job')->where([ - 'id >' => 2, - 'name !=' => 'Accountant' - ])->get()->getResult(); + public function testWhereArray() + { + $jobs = $this->db->table('job')->where([ + 'id >' => 2, + 'name !=' => 'Accountant' + ])->get()->getResult(); - $this->assertCount(1, $jobs); + $this->assertCount(1, $jobs); - $job = current($jobs); - $this->assertEquals('Musician', $job->name); - } + $job = current($jobs); + $this->assertEquals('Musician', $job->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testWhereCustomString() - { - $jobs = $this->db->table('job')->where("id > 2 AND name != 'Accountant'") - ->get() - ->getResult(); + public function testWhereCustomString() + { + $jobs = $this->db->table('job')->where("id > 2 AND name != 'Accountant'") + ->get() + ->getResult(); - $this->assertCount(1, $jobs); + $this->assertCount(1, $jobs); - $job = current($jobs); - $this->assertEquals('Musician', $job->name); - } + $job = current($jobs); + $this->assertEquals('Musician', $job->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testOrWhere() - { - $jobs = $this->db->table('job') - ->where('name !=', 'Accountant') - ->orWhere('id >', 3) - ->get() - ->getResult(); + public function testOrWhere() + { + $jobs = $this->db->table('job') + ->where('name !=', 'Accountant') + ->orWhere('id >', 3) + ->get() + ->getResult(); - $this->assertCount(3, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Politician', $jobs[1]->name); - $this->assertEquals('Musician', $jobs[2]->name); - } + $this->assertCount(3, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Politician', $jobs[1]->name); + $this->assertEquals('Musician', $jobs[2]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testOrWhereSameColumn() - { - $jobs = $this->db->table('job') - ->where('name', 'Developer') - ->orWhere('name', 'Politician') - ->get() - ->getResult(); + public function testOrWhereSameColumn() + { + $jobs = $this->db->table('job') + ->where('name', 'Developer') + ->orWhere('name', 'Politician') + ->get() + ->getResult(); - $this->assertCount(2, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Politician', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Politician', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testWhereIn() - { - $jobs = $this->db->table('job') - ->whereIn('name', ['Politician', 'Accountant']) - ->get() - ->getResult(); + public function testWhereIn() + { + $jobs = $this->db->table('job') + ->whereIn('name', ['Politician', 'Accountant']) + ->get() + ->getResult(); - $this->assertCount(2, $jobs); - $this->assertEquals('Politician', $jobs[0]->name); - $this->assertEquals('Accountant', $jobs[1]->name); - } + $this->assertCount(2, $jobs); + $this->assertEquals('Politician', $jobs[0]->name); + $this->assertEquals('Accountant', $jobs[1]->name); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * @group single */ - public function testWhereNotIn() - { - $jobs = $this->db->table('job') - ->whereNotIn('name', ['Politician', 'Accountant']) - ->get() - ->getResult(); - - $this->assertCount(2, $jobs); - $this->assertEquals('Developer', $jobs[0]->name); - $this->assertEquals('Musician', $jobs[1]->name); - } - - //-------------------------------------------------------------------- + public function testWhereNotIn() + { + $jobs = $this->db->table('job') + ->whereNotIn('name', ['Politician', 'Accountant']) + ->get() + ->getResult(); + + $this->assertCount(2, $jobs); + $this->assertEquals('Developer', $jobs[0]->name); + $this->assertEquals('Musician', $jobs[1]->name); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Debug/ExceptionsTest.php b/tests/system/Debug/ExceptionsTest.php index 7a354872c5c4..b49237462928 100644 --- a/tests/system/Debug/ExceptionsTest.php +++ b/tests/system/Debug/ExceptionsTest.php @@ -2,9 +2,9 @@ class ExceptionsTest extends \CIUnitTestCase { - public function testNew() - { - $actual = new Exceptions(new \Config\Exceptions(), \Config\Services::request(), \Config\Services::response()); - $this->assertInstanceOf(Exceptions::class, $actual); - } + public function testNew() + { + $actual = new Exceptions(new \Config\Exceptions(), \Config\Services::request(), \Config\Services::response()); + $this->assertInstanceOf(Exceptions::class, $actual); + } } diff --git a/tests/system/Debug/TimerTest.php b/tests/system/Debug/TimerTest.php index 961d7999bcbe..6c1d25e64536 100644 --- a/tests/system/Debug/TimerTest.php +++ b/tests/system/Debug/TimerTest.php @@ -3,85 +3,85 @@ class TimerTest extends \CIUnitTestCase { - public function setUp() { } + public function setUp() { } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function tearDown() { } + public function tearDown() { } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * We do most of our tests in this one method. While I usually frown - * on this, it's handy here so that we don't stall the tests any - * longer then needed. - */ - public function testStoresTimers() - { - $timer = new Timer(); + /** + * We do most of our tests in this one method. While I usually frown + * on this, it's handy here so that we don't stall the tests any + * longer then needed. + */ + public function testStoresTimers() + { + $timer = new Timer(); - $timer->start('test1'); - sleep(1); - $timer->stop('test1'); + $timer->start('test1'); + sleep(1); + $timer->stop('test1'); - $timers = $timer->getTimers(); + $timers = $timer->getTimers(); - $this->assertCount(1, $timers, "No timers were stored."); - $this->assertArrayHasKey('test1', $timers, 'No "test1" array found.'); - $this->assertArrayHasKey('start', $timers['test1'], 'No "start" value found.'); - $this->assertArrayHasKey('end', $timers['test1'], 'No "end" value found.'); + $this->assertCount(1, $timers, "No timers were stored."); + $this->assertArrayHasKey('test1', $timers, 'No "test1" array found.'); + $this->assertArrayHasKey('start', $timers['test1'], 'No "start" value found.'); + $this->assertArrayHasKey('end', $timers['test1'], 'No "end" value found.'); - // Since the timer has been stopped - it will have a value. In this - // case it should be over 1 second. - $this->assertArrayHasKey('duration', $timers['test1'], "No duration was calculated."); - $this->assertGreaterThanOrEqual(1.0, $timers['test1']['duration']); - } + // Since the timer has been stopped - it will have a value. In this + // case it should be over 1 second. + $this->assertArrayHasKey('duration', $timers['test1'], "No duration was calculated."); + $this->assertGreaterThanOrEqual(1.0, $timers['test1']['duration']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAutoCalcsTimerEnd() - { - $timer = new Timer(); + public function testAutoCalcsTimerEnd() + { + $timer = new Timer(); - $timer->start('test1'); - sleep(1); + $timer->start('test1'); + sleep(1); - $timers = $timer->getTimers(); + $timers = $timer->getTimers(); - $this->assertArrayHasKey('duration', $timers['test1'], "No duration was calculated."); - $this->assertGreaterThanOrEqual(1.0, $timers['test1']['duration']); - } + $this->assertArrayHasKey('duration', $timers['test1'], "No duration was calculated."); + $this->assertGreaterThanOrEqual(1.0, $timers['test1']['duration']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testElapsedTimeGivesSameResultAsTimersArray() - { - $timer = new Timer(); + public function testElapsedTimeGivesSameResultAsTimersArray() + { + $timer = new Timer(); - $timer->start('test1'); - sleep(1); - $timer->stop('test1'); + $timer->start('test1'); + sleep(1); + $timer->stop('test1'); - $timers = $timer->getTimers(); + $timers = $timer->getTimers(); - $expected = $timers['test1']['duration']; + $expected = $timers['test1']['duration']; - $this->assertEquals($expected, $timer->getElapsedTime('test1')); - } + $this->assertEquals($expected, $timer->getElapsedTime('test1')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * @expectedException RunTimeException - */ - public function testThrowsExceptionStoppingNonTimer() - { - $timer = new Timer(); + /** + * @expectedException RunTimeException + */ + public function testThrowsExceptionStoppingNonTimer() + { + $timer = new Timer(); - $timer->stop('test1'); - } + $timer->stop('test1'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testLongExecutionTime() { @@ -116,12 +116,12 @@ public function testCommonStartStop() //-------------------------------------------------------------------- - public function testReturnsNullGettingElapsedTimeOfNonTimer() - { - $timer = new Timer(); + public function testReturnsNullGettingElapsedTimeOfNonTimer() + { + $timer = new Timer(); - $this->assertNull($timer->getElapsedTime('test1')); - } + $this->assertNull($timer->getElapsedTime('test1')); + } //-------------------------------------------------------------------- } diff --git a/tests/system/Events/EventsTest.php b/tests/system/Events/EventsTest.php index c8ef2ffa5df8..cc11be2690d6 100644 --- a/tests/system/Events/EventsTest.php +++ b/tests/system/Events/EventsTest.php @@ -2,240 +2,240 @@ class EventsTest extends \CIUnitTestCase { - /** - * @var \UnitTester - */ - protected $tester; + /** + * @var \UnitTester + */ + protected $tester; - protected function setUp() - { - Events::removeAllListeners(); - } + protected function setUp() + { + Events::removeAllListeners(); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testListeners() - { - $callback1 = function() {}; - $callback2 = function() {}; + public function testListeners() + { + $callback1 = function() {}; + $callback2 = function() {}; - Events::on('foo', $callback1, EVENT_PRIORITY_HIGH); - Events::on('foo', $callback2, EVENT_PRIORITY_NORMAL); + Events::on('foo', $callback1, EVENT_PRIORITY_HIGH); + Events::on('foo', $callback2, EVENT_PRIORITY_NORMAL); - $this->assertEquals([$callback2, $callback1], Events::listeners('foo')); - } + $this->assertEquals([$callback2, $callback1], Events::listeners('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHandleEvent() - { - $result = null; + public function testHandleEvent() + { + $result = null; - Events::on('foo', function($arg) use(&$result) { - $result = $arg; - }); + Events::on('foo', function($arg) use(&$result) { + $result = $arg; + }); - $this->assertTrue(Events::trigger('foo', 'bar') ); + $this->assertTrue(Events::trigger('foo', 'bar') ); - $this->assertEquals('bar', $result); - } + $this->assertEquals('bar', $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCancelEvent() - { - $result = 0; + public function testCancelEvent() + { + $result = 0; - // This should cancel the flow of events, and leave - // $result = 1. - Events::on('foo', function($arg) use (&$result) { - $result = 1; - return false; - }); - Events::on('foo', function($arg) use (&$result) { - $result = 2; - }); + // This should cancel the flow of events, and leave + // $result = 1. + Events::on('foo', function($arg) use (&$result) { + $result = 1; + return false; + }); + Events::on('foo', function($arg) use (&$result) { + $result = 2; + }); - $this->assertFalse(Events::trigger('foo', 'bar')); - $this->assertEquals(1, $result); - } + $this->assertFalse(Events::trigger('foo', 'bar')); + $this->assertEquals(1, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPriority() - { - $result = 0; + public function testPriority() + { + $result = 0; - Events::on('foo', function() use (&$result) { - $result = 1; - return false; - }, EVENT_PRIORITY_NORMAL); - // Since this has a higher priority, it will - // run first. - Events::on('foo', function() use (&$result) { - $result = 2; - return false; - }, EVENT_PRIORITY_HIGH); + Events::on('foo', function() use (&$result) { + $result = 1; + return false; + }, EVENT_PRIORITY_NORMAL); + // Since this has a higher priority, it will + // run first. + Events::on('foo', function() use (&$result) { + $result = 2; + return false; + }, EVENT_PRIORITY_HIGH); - $this->assertFalse(Events::trigger('foo', 'bar')); - $this->assertEquals(2, $result); - } + $this->assertFalse(Events::trigger('foo', 'bar')); + $this->assertEquals(2, $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPriorityWithMultiple() - { - $result = []; + public function testPriorityWithMultiple() + { + $result = []; - Events::on('foo', function() use (&$result) { - $result[] = 'a'; - }, EVENT_PRIORITY_NORMAL); + Events::on('foo', function() use (&$result) { + $result[] = 'a'; + }, EVENT_PRIORITY_NORMAL); - Events::on('foo', function() use (&$result) { - $result[] = 'b'; - }, EVENT_PRIORITY_LOW); + Events::on('foo', function() use (&$result) { + $result[] = 'b'; + }, EVENT_PRIORITY_LOW); - Events::on('foo', function() use (&$result) { - $result[] = 'c'; - }, EVENT_PRIORITY_HIGH); + Events::on('foo', function() use (&$result) { + $result[] = 'c'; + }, EVENT_PRIORITY_HIGH); - Events::on('foo', function() use (&$result) { - $result[] = 'd'; - }, 75); + Events::on('foo', function() use (&$result) { + $result[] = 'd'; + }, 75); - Events::trigger('foo'); - $this->assertEquals(['c', 'd', 'a', 'b'], $result); - } + Events::trigger('foo'); + $this->assertEquals(['c', 'd', 'a', 'b'], $result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRemoveListener() - { - $result = false; + public function testRemoveListener() + { + $result = false; - $callback = function() use (&$result) - { - $result = true; - }; + $callback = function() use (&$result) + { + $result = true; + }; - Events::on('foo', $callback); + Events::on('foo', $callback); - Events::trigger('foo'); - $this->assertTrue($result); + Events::trigger('foo'); + $this->assertTrue($result); - $result = false; - $this->assertTrue(Events::removeListener('foo', $callback)); + $result = false; + $this->assertTrue(Events::removeListener('foo', $callback)); - Events::trigger('foo'); - $this->assertFalse($result); - } + Events::trigger('foo'); + $this->assertFalse($result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRemoveListenerTwice() - { - $result = false; + public function testRemoveListenerTwice() + { + $result = false; - $callback = function() use (&$result) - { - $result = true; - }; + $callback = function() use (&$result) + { + $result = true; + }; - Events::on('foo', $callback); + Events::on('foo', $callback); - Events::trigger('foo'); - $this->assertTrue($result); + Events::trigger('foo'); + $this->assertTrue($result); - $result = false; - $this->assertTrue(Events::removeListener('foo', $callback)); - $this->assertFalse(Events::removeListener('foo', $callback)); + $result = false; + $this->assertTrue(Events::removeListener('foo', $callback)); + $this->assertFalse(Events::removeListener('foo', $callback)); - Events::trigger('foo'); - $this->assertFalse($result); - } + Events::trigger('foo'); + $this->assertFalse($result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRemoveUnknownListener() - { - $result = false; + public function testRemoveUnknownListener() + { + $result = false; - $callback = function() use (&$result) - { - $result = true; - }; + $callback = function() use (&$result) + { + $result = true; + }; - Events::on('foo', $callback); + Events::on('foo', $callback); - Events::trigger('foo'); - $this->assertTrue($result); + Events::trigger('foo'); + $this->assertTrue($result); - $result = false; - $this->assertFalse(Events::removeListener('bar', $callback)); + $result = false; + $this->assertFalse(Events::removeListener('bar', $callback)); - Events::trigger('foo'); - $this->assertTrue($result); - } + Events::trigger('foo'); + $this->assertTrue($result); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRemoveAllListenersWithSingleEvent() - { - $result = false; + public function testRemoveAllListenersWithSingleEvent() + { + $result = false; - $callback = function() use (&$result) - { - $result = true; - }; + $callback = function() use (&$result) + { + $result = true; + }; - Events::on('foo', $callback); + Events::on('foo', $callback); - Events::removeAllListeners('foo'); + Events::removeAllListeners('foo'); - $listeners = Events::listeners('foo'); + $listeners = Events::listeners('foo'); - $this->assertEquals([], $listeners); - } + $this->assertEquals([], $listeners); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRemoveAllListenersWithMultipleEvents() - { - $result = false; + public function testRemoveAllListenersWithMultipleEvents() + { + $result = false; - $callback = function() use (&$result) - { - $result = true; - }; + $callback = function() use (&$result) + { + $result = true; + }; - Events::on('foo', $callback); - Events::on('bar', $callback); + Events::on('foo', $callback); + Events::on('bar', $callback); - Events::removeAllListeners(); + Events::removeAllListeners(); - $this->assertEquals([], Events::listeners('foo')); - $this->assertEquals([], Events::listeners('bar')); - } + $this->assertEquals([], Events::listeners('foo')); + $this->assertEquals([], Events::listeners('bar')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSimulate() - { - $result = 0; + public function testSimulate() + { + $result = 0; - $callback = function() use (&$result) - { - $result += 2; - }; + $callback = function() use (&$result) + { + $result += 2; + }; - Events::on('foo', $callback); + Events::on('foo', $callback); - Events::simulate(true); - Events::trigger('foo'); + Events::simulate(true); + Events::trigger('foo'); - $this->assertEquals(0, $result); - } + $this->assertEquals(0, $result); + } } diff --git a/tests/system/Files/FileTest.php b/tests/system/Files/FileTest.php index 1bfae9817e1b..43c18397a0f6 100644 --- a/tests/system/Files/FileTest.php +++ b/tests/system/Files/FileTest.php @@ -2,37 +2,37 @@ class FileTest extends \CIUnitTestCase { - public function testCanAccessSPLFileInfoMethods() - { - $file = new File(BASEPATH.'Common.php'); + public function testCanAccessSPLFileInfoMethods() + { + $file = new File(BASEPATH.'Common.php'); - $this->assertEquals('file', $file->getType()); - } + $this->assertEquals('file', $file->getType()); + } - public function testGetSizeReturnsKB() - { - $file = new File(BASEPATH.'Common.php'); + public function testGetSizeReturnsKB() + { + $file = new File(BASEPATH.'Common.php'); - $size = number_format(filesize(BASEPATH.'Common.php') / 1024, 3); + $size = number_format(filesize(BASEPATH.'Common.php') / 1024, 3); - $this->assertEquals($size, $file->getSize('kb')); - } + $this->assertEquals($size, $file->getSize('kb')); + } - public function testGetSizeReturnsMB() - { - $file = new File(BASEPATH.'Common.php'); + public function testGetSizeReturnsMB() + { + $file = new File(BASEPATH.'Common.php'); - $size = number_format(filesize(BASEPATH.'Common.php') / 1024 / 1024, 3); + $size = number_format(filesize(BASEPATH.'Common.php') / 1024 / 1024, 3); - $this->assertEquals($size, $file->getSize('mb')); - } + $this->assertEquals($size, $file->getSize('mb')); + } - /** - * @expectedException \CodeIgniter\Files\Exceptions\FileNotFoundException - */ - public function testThrowsExceptionIfNotAFile() - { - $file = new File(BASEPATH.'Commoner.php',true); - } + /** + * @expectedException \CodeIgniter\Files\Exceptions\FileNotFoundException + */ + public function testThrowsExceptionIfNotAFile() + { + $file = new File(BASEPATH.'Commoner.php',true); + } } diff --git a/tests/system/Filters/FiltersTest.php b/tests/system/Filters/FiltersTest.php index 0fc0c5954db2..e67aefafe9a4 100644 --- a/tests/system/Filters/FiltersTest.php +++ b/tests/system/Filters/FiltersTest.php @@ -11,319 +11,319 @@ */ class FiltersTest extends \CIUnitTestCase { - protected $request; - protected $response; + protected $request; + protected $response; - public function __construct() - { - parent::__construct(); + public function __construct() + { + parent::__construct(); - $this->request = Services::request(); - $this->response = Services::response(); - } - - //-------------------------------------------------------------------- - - public function setUp() - { - - } - - //-------------------------------------------------------------------- - - public function tearDown() - { + $this->request = Services::request(); + $this->response = Services::response(); + } + + //-------------------------------------------------------------------- + + public function setUp() + { + + } + + //-------------------------------------------------------------------- + + public function tearDown() + { - } - - //-------------------------------------------------------------------- - - public function testProcessMethodDetectsCLI() - { - $config = [ - 'methods' => [ - 'cli' => ['foo'] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - - $expected = [ - 'before' => ['foo'], - 'after' => [] - ]; - - $this->assertEquals($expected, $filters->initialize()->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodDetectsGetRequests() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'methods' => [ - 'get' => ['foo'] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - - $expected = [ - 'before' => ['foo'], - 'after' => [] - ]; - - $this->assertEquals($expected, $filters->initialize()->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodRespectsMethod() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'methods' => [ - 'post' => ['foo'], - 'get' => ['bar'] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - - $expected = [ - 'before' => ['bar'], - 'after' => [] - ]; - - $this->assertEquals($expected, $filters->initialize()->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodProcessGlobals() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'globals' => [ - 'before' => [ - 'foo' => ['bar'], - 'bar' - ], - 'after' => [ - 'baz' - ] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - - $expected = [ - 'before' => [ - 'foo' => ['bar'], - 'bar' - ], - 'after' => ['baz'] - ]; - - $this->assertEquals($expected, $filters->initialize()->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodProcessGlobalsWithExcept() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'globals' => [ - 'before' => [ - 'foo' => ['except' => ['admin/*']], - 'bar' - ], - 'after' => [ - 'baz' - ] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'admin/foo/bar'; - - $expected = [ - 'before' => [ - 'bar' - ], - 'after' => ['baz'] - ]; - - $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodProcessesFiltersBefore() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'filters' => [ - 'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'admin/foo/bar'; - - $expected = [ - 'before' => ['foo'], - 'after' => [] - ]; - - $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodProcessesFiltersAfter() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'filters' => [ - 'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'users/foo/bar'; - - $expected = [ - 'before' => [], - 'after' => ['foo'] - ]; - - $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testProcessMethodProcessesCombined() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'globals' => [ - 'before' => [ - 'foog' => ['except' => ['admin/*']], - 'barg' - ], - 'after' => [ - 'bazg' - ] - ], - 'methods' => [ - 'post' => ['foo'], - 'get' => ['bar'] - ], - 'filters' => [ - 'foof' => ['before' => ['admin/*'], 'after' => ['/users/*']] - ] - ]; - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'admin/foo/bar'; - - $expected = [ - 'before' => ['barg', 'bar', 'foof'], - 'after' => ['bazg'] - ]; - - $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); - } - - //-------------------------------------------------------------------- - - public function testRunThrowsWithInvalidAlias() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'aliases' => [], - 'globals' => [ - 'before' => ['invalid'], - 'after' => [] - ] - ]; - - $filters = new Filters((object)$config, $this->request, $this->response); - - $this->expectException(FilterException::class); - $uri = 'admin/foo/bar'; - - $filters->run($uri); - } - - //-------------------------------------------------------------------- - - public function testRunThrowsWithInvalidClassType() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'aliases' => ['invalid' => 'CodeIgniter\Filters\fixtures\InvalidClass'], - 'globals' => [ - 'before' => ['invalid'], - 'after' => [] - ] - ]; - - $filters = new Filters((object)$config, $this->request, $this->response); - - $this->expectException(FilterException::class); - $uri = 'admin/foo/bar'; - - $filters->run($uri); - } - - //-------------------------------------------------------------------- - - public function testRunDoesBefore() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'], - 'globals' => [ - 'before' => ['google'], - 'after' => [] - ] - ]; - - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'admin/foo/bar'; - - $request = $filters->run($uri, 'before'); - - $this->assertEquals('http://google.com', $request->url); - } - - //-------------------------------------------------------------------- - - public function testRunDoesAfter() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; - - $config = [ - 'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'], - 'globals' => [ - 'before' => [], - 'after' => ['google'] - ] - ]; + } + + //-------------------------------------------------------------------- + + public function testProcessMethodDetectsCLI() + { + $config = [ + 'methods' => [ + 'cli' => ['foo'] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + + $expected = [ + 'before' => ['foo'], + 'after' => [] + ]; + + $this->assertEquals($expected, $filters->initialize()->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodDetectsGetRequests() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'methods' => [ + 'get' => ['foo'] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + + $expected = [ + 'before' => ['foo'], + 'after' => [] + ]; + + $this->assertEquals($expected, $filters->initialize()->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodRespectsMethod() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'methods' => [ + 'post' => ['foo'], + 'get' => ['bar'] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + + $expected = [ + 'before' => ['bar'], + 'after' => [] + ]; + + $this->assertEquals($expected, $filters->initialize()->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodProcessGlobals() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'globals' => [ + 'before' => [ + 'foo' => ['bar'], + 'bar' + ], + 'after' => [ + 'baz' + ] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + + $expected = [ + 'before' => [ + 'foo' => ['bar'], + 'bar' + ], + 'after' => ['baz'] + ]; + + $this->assertEquals($expected, $filters->initialize()->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodProcessGlobalsWithExcept() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'globals' => [ + 'before' => [ + 'foo' => ['except' => ['admin/*']], + 'bar' + ], + 'after' => [ + 'baz' + ] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'admin/foo/bar'; + + $expected = [ + 'before' => [ + 'bar' + ], + 'after' => ['baz'] + ]; + + $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodProcessesFiltersBefore() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'filters' => [ + 'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'admin/foo/bar'; + + $expected = [ + 'before' => ['foo'], + 'after' => [] + ]; + + $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodProcessesFiltersAfter() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'filters' => [ + 'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'users/foo/bar'; + + $expected = [ + 'before' => [], + 'after' => ['foo'] + ]; + + $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testProcessMethodProcessesCombined() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'globals' => [ + 'before' => [ + 'foog' => ['except' => ['admin/*']], + 'barg' + ], + 'after' => [ + 'bazg' + ] + ], + 'methods' => [ + 'post' => ['foo'], + 'get' => ['bar'] + ], + 'filters' => [ + 'foof' => ['before' => ['admin/*'], 'after' => ['/users/*']] + ] + ]; + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'admin/foo/bar'; + + $expected = [ + 'before' => ['barg', 'bar', 'foof'], + 'after' => ['bazg'] + ]; + + $this->assertEquals($expected, $filters->initialize($uri)->getFilters()); + } + + //-------------------------------------------------------------------- + + public function testRunThrowsWithInvalidAlias() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'aliases' => [], + 'globals' => [ + 'before' => ['invalid'], + 'after' => [] + ] + ]; + + $filters = new Filters((object)$config, $this->request, $this->response); + + $this->expectException(FilterException::class); + $uri = 'admin/foo/bar'; + + $filters->run($uri); + } + + //-------------------------------------------------------------------- + + public function testRunThrowsWithInvalidClassType() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'aliases' => ['invalid' => 'CodeIgniter\Filters\fixtures\InvalidClass'], + 'globals' => [ + 'before' => ['invalid'], + 'after' => [] + ] + ]; + + $filters = new Filters((object)$config, $this->request, $this->response); + + $this->expectException(FilterException::class); + $uri = 'admin/foo/bar'; + + $filters->run($uri); + } + + //-------------------------------------------------------------------- + + public function testRunDoesBefore() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'], + 'globals' => [ + 'before' => ['google'], + 'after' => [] + ] + ]; + + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'admin/foo/bar'; + + $request = $filters->run($uri, 'before'); + + $this->assertEquals('http://google.com', $request->url); + } + + //-------------------------------------------------------------------- + + public function testRunDoesAfter() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $config = [ + 'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'], + 'globals' => [ + 'before' => [], + 'after' => ['google'] + ] + ]; - $filters = new Filters((object)$config, $this->request, $this->response); - $uri = 'admin/foo/bar'; + $filters = new Filters((object)$config, $this->request, $this->response); + $uri = 'admin/foo/bar'; - $response = $filters->run($uri, 'after'); + $response = $filters->run($uri, 'after'); - $this->assertEquals('http://google.com', $response->csp); - } + $this->assertEquals('http://google.com', $response->csp); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Filters/fixtures/GoogleMe.php b/tests/system/Filters/fixtures/GoogleMe.php index 86859c8d8604..08f316ac9052 100644 --- a/tests/system/Filters/fixtures/GoogleMe.php +++ b/tests/system/Filters/fixtures/GoogleMe.php @@ -6,21 +6,21 @@ class GoogleMe implements FilterInterface { - public function before(RequestInterface $request) - { - $request->url = 'http://google.com'; + public function before(RequestInterface $request) + { + $request->url = 'http://google.com'; - return $request; - } + return $request; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function after(RequestInterface $request, ResponseInterface $response) - { - $response->csp = 'http://google.com'; + public function after(RequestInterface $request, ResponseInterface $response) + { + $response->csp = 'http://google.com'; - return $response; - } + return $response; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Filters/fixtures/InvalidClass.php b/tests/system/Filters/fixtures/InvalidClass.php index e627fd38b29f..806dafafc50a 100644 --- a/tests/system/Filters/fixtures/InvalidClass.php +++ b/tests/system/Filters/fixtures/InvalidClass.php @@ -2,11 +2,11 @@ class InvalidClass { - public function index() - { - return 'bad'; - } + public function index() + { + return 'bad'; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Format/JSONFormatterTest.php b/tests/system/Format/JSONFormatterTest.php index bd2b1ef03140..173f26c52022 100644 --- a/tests/system/Format/JSONFormatterTest.php +++ b/tests/system/Format/JSONFormatterTest.php @@ -23,41 +23,41 @@ public function testBasicJSON() $this->assertEquals($expected, $this->jsonFormatter->format($data)); } - public function testUnicodeOutput() - { - $data = [ - 'foo' => 'База данни грешка' - ]; + public function testUnicodeOutput() + { + $data = [ + 'foo' => 'База данни грешка' + ]; - $expected = '{ + $expected = '{ "foo": "База данни грешка" }'; - $this->assertEquals($expected, $this->jsonFormatter->format($data)); + $this->assertEquals($expected, $this->jsonFormatter->format($data)); } - public function testKeepsURLs() - { - $data = [ - 'foo' => 'https://www.example.com/foo/bar' - ]; + public function testKeepsURLs() + { + $data = [ + 'foo' => 'https://www.example.com/foo/bar' + ]; - $expected = '{ + $expected = '{ "foo": "https://www.example.com/foo/bar" }'; - $this->assertEquals($expected, $this->jsonFormatter->format($data)); - } + $this->assertEquals($expected, $this->jsonFormatter->format($data)); + } + - /** * @expectedException RuntimeException */ - public function testJSONError() - { + public function testJSONError() + { $data = ["\xB1\x31"]; - $expected = "Boom"; - $this->assertEquals($expected, $this->jsonFormatter->format($data)); - } + $expected = "Boom"; + $this->assertEquals($expected, $this->jsonFormatter->format($data)); + } } diff --git a/tests/system/Format/XMLFormatterTest.php b/tests/system/Format/XMLFormatterTest.php index 5b97c084bcfe..b8b90dbffbe7 100644 --- a/tests/system/Format/XMLFormatterTest.php +++ b/tests/system/Format/XMLFormatterTest.php @@ -54,9 +54,9 @@ public function testFormatXMLWithMultilevelArrayAndNumericKey() $this->assertEquals($expected, $this->xmlFormatter->format($data)); } - - public function testStringFormatting() { - $data = ['Something']; + + public function testStringFormatting() { + $data = ['Something']; $expected = << <0>Something @@ -64,5 +64,5 @@ public function testStringFormatting() { EOH; $this->assertEquals($expected, $this->xmlFormatter->format($data)); - } + } } diff --git a/tests/system/HTTP/CURLRequestTest.php b/tests/system/HTTP/CURLRequestTest.php index 86b70653be35..4b2bf460c3de 100644 --- a/tests/system/HTTP/CURLRequestTest.php +++ b/tests/system/HTTP/CURLRequestTest.php @@ -4,333 +4,333 @@ class CURLRequestTest extends \CIUnitTestCase { - protected $request; + protected $request; - public function setUp() - { - $this->request = new MockCURLRequest(new App(), new URI(), new Response(new \Config\App())); - } + public function setUp() + { + $this->request = new MockCURLRequest(new App(), new URI(), new Response(new \Config\App())); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSendReturnsResponse() - { - $output = "Howdy Stranger."; + public function testSendReturnsResponse() + { + $output = "Howdy Stranger."; - $response = $this->request->setOutput($output) - ->send('get', 'http://example.com'); + $response = $this->request->setOutput($output) + ->send('get', 'http://example.com'); - $this->assertInstanceOf('CodeIgniter\\HTTP\\Response', $response); - $this->assertEquals($output, $response->getBody()); - } + $this->assertInstanceOf('CodeIgniter\\HTTP\\Response', $response); + $this->assertEquals($output, $response->getBody()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetSetsCorrectMethod() - { - $response = $this->request->get('http://example.com'); + public function testGetSetsCorrectMethod() + { + $response = $this->request->get('http://example.com'); - $this->assertEquals('get', $this->request->getMethod()); + $this->assertEquals('get', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('GET', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('GET', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDeleteSetsCorrectMethod() - { - $response = $this->request->delete('http://example.com'); + public function testDeleteSetsCorrectMethod() + { + $response = $this->request->delete('http://example.com'); - $this->assertEquals('delete', $this->request->getMethod()); + $this->assertEquals('delete', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('DELETE', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('DELETE', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeadSetsCorrectMethod() - { - $response = $this->request->head('http://example.com'); + public function testHeadSetsCorrectMethod() + { + $response = $this->request->head('http://example.com'); - $this->assertEquals('head', $this->request->getMethod()); + $this->assertEquals('head', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('HEAD', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('HEAD', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testOptionsSetsCorrectMethod() - { - $response = $this->request->options('http://example.com'); + public function testOptionsSetsCorrectMethod() + { + $response = $this->request->options('http://example.com'); - $this->assertEquals('options', $this->request->getMethod()); + $this->assertEquals('options', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('OPTIONS', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('OPTIONS', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPatchSetsCorrectMethod() - { - $response = $this->request->patch('http://example.com'); + public function testPatchSetsCorrectMethod() + { + $response = $this->request->patch('http://example.com'); - $this->assertEquals('patch', $this->request->getMethod()); + $this->assertEquals('patch', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('PATCH', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('PATCH', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPostSetsCorrectMethod() - { - $response = $this->request->post('http://example.com'); + public function testPostSetsCorrectMethod() + { + $response = $this->request->post('http://example.com'); - $this->assertEquals('post', $this->request->getMethod()); + $this->assertEquals('post', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('POST', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('POST', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPutSetsCorrectMethod() - { - $response = $this->request->put('http://example.com'); + public function testPutSetsCorrectMethod() + { + $response = $this->request->put('http://example.com'); - $this->assertEquals('put', $this->request->getMethod()); + $this->assertEquals('put', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('PUT', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('PUT', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCustomMethodSetsCorrectMethod() - { - $response = $this->request->request('custom', 'http://example.com'); + public function testCustomMethodSetsCorrectMethod() + { + $response = $this->request->request('custom', 'http://example.com'); - $this->assertEquals('custom', $this->request->getMethod()); + $this->assertEquals('custom', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('CUSTOM', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('CUSTOM', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRequestMethodGetsSanitized() - { - $response = $this->request->request('', 'http://example.com'); + public function testRequestMethodGetsSanitized() + { + $response = $this->request->request('', 'http://example.com'); - $this->assertEquals('custom', $this->request->getMethod()); + $this->assertEquals('custom', $this->request->getMethod()); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); - $this->assertEquals('CUSTOM', $options[CURLOPT_CUSTOMREQUEST]); - } + $this->assertArrayHasKey(CURLOPT_CUSTOMREQUEST, $options); + $this->assertEquals('CUSTOM', $options[CURLOPT_CUSTOMREQUEST]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testRequestSetsBasicCurlOptions() - { - $response = $this->request->request('get', 'http://example.com'); + public function testRequestSetsBasicCurlOptions() + { + $response = $this->request->request('get', 'http://example.com'); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_URL, $options); - $this->assertEquals('http://example.com', $options[CURLOPT_URL]); + $this->assertArrayHasKey(CURLOPT_URL, $options); + $this->assertEquals('http://example.com', $options[CURLOPT_URL]); - $this->assertArrayHasKey(CURLOPT_RETURNTRANSFER, $options); - $this->assertTrue($options[CURLOPT_RETURNTRANSFER]); + $this->assertArrayHasKey(CURLOPT_RETURNTRANSFER, $options); + $this->assertTrue($options[CURLOPT_RETURNTRANSFER]); - $this->assertArrayHasKey(CURLOPT_HEADER, $options); - $this->assertTrue($options[CURLOPT_HEADER]); + $this->assertArrayHasKey(CURLOPT_HEADER, $options); + $this->assertTrue($options[CURLOPT_HEADER]); - $this->assertArrayHasKey(CURLOPT_FRESH_CONNECT, $options); - $this->assertTrue($options[CURLOPT_FRESH_CONNECT]); + $this->assertArrayHasKey(CURLOPT_FRESH_CONNECT, $options); + $this->assertTrue($options[CURLOPT_FRESH_CONNECT]); - $this->assertArrayHasKey(CURLOPT_TIMEOUT_MS, $options); - $this->assertEquals(0.0, $options[CURLOPT_TIMEOUT_MS]); + $this->assertArrayHasKey(CURLOPT_TIMEOUT_MS, $options); + $this->assertEquals(0.0, $options[CURLOPT_TIMEOUT_MS]); - $this->assertArrayHasKey(CURLOPT_CONNECTTIMEOUT_MS, $options); - $this->assertEquals(150 * 1000, $options[CURLOPT_CONNECTTIMEOUT_MS]); - } + $this->assertArrayHasKey(CURLOPT_CONNECTTIMEOUT_MS, $options); + $this->assertEquals(150 * 1000, $options[CURLOPT_CONNECTTIMEOUT_MS]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAuthBasicOption() - { - $response = $this->request->request('get', 'http://example.com', [ - 'auth' => ['username', 'password'] - ]); + public function testAuthBasicOption() + { + $response = $this->request->request('get', 'http://example.com', [ + 'auth' => ['username', 'password'] + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_USERPWD, $options); - $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); + $this->assertArrayHasKey(CURLOPT_USERPWD, $options); + $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); - $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); - $this->assertEquals(CURLAUTH_BASIC, $options[CURLOPT_HTTPAUTH]); - } + $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); + $this->assertEquals(CURLAUTH_BASIC, $options[CURLOPT_HTTPAUTH]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAuthBasicOptionExplicit() - { - $response = $this->request->request('get', 'http://example.com', [ - 'auth' => ['username', 'password', 'basic'] - ]); + public function testAuthBasicOptionExplicit() + { + $response = $this->request->request('get', 'http://example.com', [ + 'auth' => ['username', 'password', 'basic'] + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_USERPWD, $options); - $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); + $this->assertArrayHasKey(CURLOPT_USERPWD, $options); + $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); - $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); - $this->assertEquals(CURLAUTH_BASIC, $options[CURLOPT_HTTPAUTH]); - } + $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); + $this->assertEquals(CURLAUTH_BASIC, $options[CURLOPT_HTTPAUTH]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAuthDigestOption() - { - $response = $this->request->request('get', 'http://example.com', [ - 'auth' => ['username', 'password', 'digest'] - ]); + public function testAuthDigestOption() + { + $response = $this->request->request('get', 'http://example.com', [ + 'auth' => ['username', 'password', 'digest'] + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_USERPWD, $options); - $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); + $this->assertArrayHasKey(CURLOPT_USERPWD, $options); + $this->assertEquals('username:password', $options[CURLOPT_USERPWD]); - $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); - $this->assertEquals(CURLAUTH_DIGEST, $options[CURLOPT_HTTPAUTH]); - } + $this->assertArrayHasKey(CURLOPT_HTTPAUTH, $options); + $this->assertEquals(CURLAUTH_DIGEST, $options[CURLOPT_HTTPAUTH]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCertOption() - { - $file = __FILE__; + public function testCertOption() + { + $file = __FILE__; - $response = $this->request->request('get', 'http://example.com', [ - 'cert' => $file - ]); + $response = $this->request->request('get', 'http://example.com', [ + 'cert' => $file + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_SSLCERT, $options); - $this->assertEquals($file, $options[CURLOPT_SSLCERT]); - } + $this->assertArrayHasKey(CURLOPT_SSLCERT, $options); + $this->assertEquals($file, $options[CURLOPT_SSLCERT]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCertOptionWithPassword() - { - $file = __FILE__; + public function testCertOptionWithPassword() + { + $file = __FILE__; - $response = $this->request->request('get', 'http://example.com', [ - 'cert' => [$file, 'password'] - ]); + $response = $this->request->request('get', 'http://example.com', [ + 'cert' => [$file, 'password'] + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_SSLCERT, $options); - $this->assertEquals($file, $options[CURLOPT_SSLCERT]); + $this->assertArrayHasKey(CURLOPT_SSLCERT, $options); + $this->assertEquals($file, $options[CURLOPT_SSLCERT]); - $this->assertArrayHasKey(CURLOPT_SSLCERTPASSWD, $options); - $this->assertEquals('password', $options[CURLOPT_SSLCERTPASSWD]); - } + $this->assertArrayHasKey(CURLOPT_SSLCERTPASSWD, $options); + $this->assertEquals('password', $options[CURLOPT_SSLCERTPASSWD]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDebugOption() - { - $response = $this->request->request('get', 'http://example.com', [ - 'debug' => true - ]); + public function testDebugOption() + { + $response = $this->request->request('get', 'http://example.com', [ + 'debug' => true + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_VERBOSE, $options); - $this->assertEquals(1, $options[CURLOPT_VERBOSE]); + $this->assertArrayHasKey(CURLOPT_VERBOSE, $options); + $this->assertEquals(1, $options[CURLOPT_VERBOSE]); - $this->assertArrayHasKey(CURLOPT_STDERR, $options); - } + $this->assertArrayHasKey(CURLOPT_STDERR, $options); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAllowRedirectsOptionFalse() - { - $response = $this->request->request('get', 'http://example.com', [ - 'allow_redirects' => false - ]); + public function testAllowRedirectsOptionFalse() + { + $response = $this->request->request('get', 'http://example.com', [ + 'allow_redirects' => false + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); - $this->assertEquals(0, $options[CURLOPT_FOLLOWLOCATION]); + $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); + $this->assertEquals(0, $options[CURLOPT_FOLLOWLOCATION]); - $this->assertArrayNotHasKey(CURLOPT_MAXREDIRS, $options); - $this->assertArrayNotHasKey(CURLOPT_REDIR_PROTOCOLS, $options); - } + $this->assertArrayNotHasKey(CURLOPT_MAXREDIRS, $options); + $this->assertArrayNotHasKey(CURLOPT_REDIR_PROTOCOLS, $options); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAllowRedirectsOptionTrue() - { - $response = $this->request->request('get', 'http://example.com', [ - 'allow_redirects' => true - ]); + public function testAllowRedirectsOptionTrue() + { + $response = $this->request->request('get', 'http://example.com', [ + 'allow_redirects' => true + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); - $this->assertEquals(1, $options[CURLOPT_FOLLOWLOCATION]); + $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); + $this->assertEquals(1, $options[CURLOPT_FOLLOWLOCATION]); - $this->assertArrayHasKey(CURLOPT_MAXREDIRS, $options); - $this->assertEquals(5, $options[CURLOPT_MAXREDIRS]); - $this->assertArrayHasKey(CURLOPT_REDIR_PROTOCOLS, $options); - $this->assertEquals(CURLPROTO_HTTP|CURLPROTO_HTTPS, $options[CURLOPT_REDIR_PROTOCOLS]); - } + $this->assertArrayHasKey(CURLOPT_MAXREDIRS, $options); + $this->assertEquals(5, $options[CURLOPT_MAXREDIRS]); + $this->assertArrayHasKey(CURLOPT_REDIR_PROTOCOLS, $options); + $this->assertEquals(CURLPROTO_HTTP|CURLPROTO_HTTPS, $options[CURLOPT_REDIR_PROTOCOLS]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAllowRedirectsOptionDefaults() - { - $response = $this->request->request('get', 'http://example.com', [ - 'allow_redirects' => true - ]); + public function testAllowRedirectsOptionDefaults() + { + $response = $this->request->request('get', 'http://example.com', [ + 'allow_redirects' => true + ]); - $options = $this->request->curl_options; + $options = $this->request->curl_options; - $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); - $this->assertEquals(1, $options[CURLOPT_FOLLOWLOCATION]); + $this->assertArrayHasKey(CURLOPT_FOLLOWLOCATION, $options); + $this->assertEquals(1, $options[CURLOPT_FOLLOWLOCATION]); - $this->assertArrayHasKey(CURLOPT_MAXREDIRS, $options); - $this->assertArrayHasKey(CURLOPT_REDIR_PROTOCOLS, $options); - } + $this->assertArrayHasKey(CURLOPT_MAXREDIRS, $options); + $this->assertArrayHasKey(CURLOPT_REDIR_PROTOCOLS, $options); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/HTTP/Files/FileCollectionTest.php b/tests/system/HTTP/Files/FileCollectionTest.php index e8960b23e358..ea6265d4549c 100644 --- a/tests/system/HTTP/Files/FileCollectionTest.php +++ b/tests/system/HTTP/Files/FileCollectionTest.php @@ -2,281 +2,281 @@ class FileCollectionTest extends \CIUnitTestCase { - public function setUp() - { - $_FILES = []; - } - - //-------------------------------------------------------------------- - - public function testAllReturnsArrayWithNoFiles() - { - $files = new FileCollection(); - - $this->assertEquals([], $files->all()); - } - - //-------------------------------------------------------------------- - - public function testAllReturnsValidSingleFile() - { - $_FILES = [ - 'userfile' => [ - 'name' => 'someFile.txt', - 'type' => 'text/plain', - 'size' => '124', - 'tmp_name' => '/tmp/myTempFile.txt', - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - $files = $collection->all(); - $this->assertCount(1, $files); - - $file = array_shift($files); - $this->assertInstanceOf(UploadedFile::class, $file); - - $this->assertEquals('someFile.txt', $file->getName()); - $this->assertEquals(124, $file->getSize()); - } - - //-------------------------------------------------------------------- - - public function testAllReturnsValidMultipleFilesSameName() - { - $_FILES = [ - 'userfile' => [ - 'name' => ['fileA.txt', 'fileB.txt'], - 'type' => ['text/plain', 'text/csv'], - 'size' => ['124', '248'], - 'tmp_name' => ['/tmp/fileA.txt', '/tmp/fileB.txt'], - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - $files = $collection->all(); - $this->assertCount(1, $files); - $this->assertEquals('userfile', key($files)); - - $files = array_shift($files); - $this->assertCount(2, $files); - - $file = $files[0]; - $this->assertInstanceOf(UploadedFile::class, $file); - - $this->assertEquals('fileA.txt', $file->getName()); - $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); - $this->assertEquals('txt', $file->getClientExtension()); - $this->assertEquals('text/plain', $file->getClientMimeType()); - $this->assertEquals(124, $file->getSize()); - } - - //-------------------------------------------------------------------- - - - public function testAllReturnsValidMultipleFilesDifferentName() - { - $_FILES = [ - 'userfile1' => [ - 'name' => 'fileA.txt', - 'type' => 'text/plain', - 'size' => 124, - 'tmp_name' => '/tmp/fileA.txt', - 'error' => 0 - ], - 'userfile2' => [ - 'name' => 'fileB.txt', - 'type' => 'text/csv', - 'size' => 248, - 'tmp_name' => '/tmp/fileB.txt', - 'error' => 0 - ], - ]; - - $collection = new FileCollection(); - $files = $collection->all(); - $this->assertCount(2, $files); - $this->assertEquals('userfile1', key($files)); - - $file = array_shift($files); - $this->assertInstanceOf(UploadedFile::class, $file); - - $this->assertEquals('fileA.txt', $file->getName()); - $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); - $this->assertEquals('txt', $file->getClientExtension()); - $this->assertEquals('text/plain', $file->getClientMimeType()); - $this->assertEquals(124, $file->getSize()); - - $file = array_pop($files); - $this->assertInstanceOf(UploadedFile::class, $file); - - $this->assertEquals('fileB.txt', $file->getName()); - $this->assertEquals('/tmp/fileB.txt', $file->getTempName()); - $this->assertEquals('txt', $file->getClientExtension()); - $this->assertEquals('text/csv', $file->getClientMimeType()); - $this->assertEquals(248, $file->getSize()); - } - - //-------------------------------------------------------------------- - - /** - * @group single - */ - public function testAllReturnsValidSingleFileNestedName() - { - $_FILES = [ - 'userfile' => [ - 'name' => [ - 'foo' => [ - 'bar' => 'fileA.txt' - ] - ], - 'type' => [ - 'foo' => [ - 'bar' => 'text/plain' - ] - ], - 'size' => [ - 'foo' => [ - 'bar' => 124 - ] - ], - 'tmp_name' => [ - 'foo' => [ - 'bar' => '/tmp/fileA.txt' - ] - ], - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - $files = $collection->all(); - $this->assertCount(1, $files); - $this->assertEquals('userfile', key($files)); - - $this->assertArrayHasKey('bar', $files['userfile']['foo']); - - $file = $files['userfile']['foo']['bar']; - $this->assertInstanceOf(UploadedFile::class, $file); - - $this->assertEquals('fileA.txt', $file->getName()); - $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); - $this->assertEquals('txt', $file->getClientExtension()); - $this->assertEquals('text/plain', $file->getClientMimeType()); - $this->assertEquals(124, $file->getSize()); - } - - //-------------------------------------------------------------------- - - public function testHasFileWithSingleFile() - { - $_FILES = [ - 'userfile' => [ - 'name' => 'someFile.txt', - 'type' => 'text/plain', - 'size' => '124', - 'tmp_name' => '/tmp/myTempFile.txt', - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - - $this->assertTrue($collection->hasFile('userfile')); - $this->assertFalse($collection->hasFile('foo')); - } - - //-------------------------------------------------------------------- - - public function testHasFileWithMultipleFilesWithDifferentNames() - { - $_FILES = [ - 'userfile1' => [ - 'name' => 'fileA.txt', - 'type' => 'text/plain', - 'size' => 124, - 'tmp_name' => '/tmp/fileA.txt', - 'error' => 0 - ], - 'userfile2' => [ - 'name' => 'fileB.txt', - 'type' => 'text/csv', - 'size' => 248, - 'tmp_name' => '/tmp/fileB.txt', - 'error' => 0 - ], - ]; - - $collection = new FileCollection(); - - $this->assertTrue($collection->hasFile('userfile1')); - $this->assertTrue($collection->hasFile('userfile2')); - } - - //-------------------------------------------------------------------- - - /** - * @group single - */ - public function testHasFileWithSingleFileNestedName() - { - $_FILES = [ - 'userfile' => [ - 'name' => [ - 'foo' => [ - 'bar' => 'fileA.txt' - ] - ], - 'type' => [ - 'foo' => [ - 'bar' => 'text/plain' - ] - ], - 'size' => [ - 'foo' => [ - 'bar' => 124 - ] - ], - 'tmp_name' => [ - 'foo' => [ - 'bar' => '/tmp/fileA.txt' - ] - ], - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - - $this->assertTrue($collection->hasFile('userfile')); - $this->assertTrue($collection->hasFile('userfile.foo')); - $this->assertTrue($collection->hasFile('userfile.foo.bar')); - } - - //-------------------------------------------------------------------- - - public function testErrorString() - { - $_FILES = [ - 'userfile' => [ - 'name' => 'someFile.txt', - 'type' => 'text/plain', - 'size' => '124', - 'tmp_name' => '/tmp/myTempFile.txt', - 'error' => UPLOAD_ERR_INI_SIZE - ] - ]; - - $expected = 'The file "someFile.txt" exceeds your upload_max_filesize ini directive.'; - - $collection = new FileCollection(); - $file = $collection->getFile('userfile'); - - $this->assertEquals($expected, $file->getErrorString()); - } + public function setUp() + { + $_FILES = []; + } + + //-------------------------------------------------------------------- + + public function testAllReturnsArrayWithNoFiles() + { + $files = new FileCollection(); + + $this->assertEquals([], $files->all()); + } + + //-------------------------------------------------------------------- + + public function testAllReturnsValidSingleFile() + { + $_FILES = [ + 'userfile' => [ + 'name' => 'someFile.txt', + 'type' => 'text/plain', + 'size' => '124', + 'tmp_name' => '/tmp/myTempFile.txt', + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + $files = $collection->all(); + $this->assertCount(1, $files); + + $file = array_shift($files); + $this->assertInstanceOf(UploadedFile::class, $file); + + $this->assertEquals('someFile.txt', $file->getName()); + $this->assertEquals(124, $file->getSize()); + } + + //-------------------------------------------------------------------- + + public function testAllReturnsValidMultipleFilesSameName() + { + $_FILES = [ + 'userfile' => [ + 'name' => ['fileA.txt', 'fileB.txt'], + 'type' => ['text/plain', 'text/csv'], + 'size' => ['124', '248'], + 'tmp_name' => ['/tmp/fileA.txt', '/tmp/fileB.txt'], + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + $files = $collection->all(); + $this->assertCount(1, $files); + $this->assertEquals('userfile', key($files)); + + $files = array_shift($files); + $this->assertCount(2, $files); + + $file = $files[0]; + $this->assertInstanceOf(UploadedFile::class, $file); + + $this->assertEquals('fileA.txt', $file->getName()); + $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); + $this->assertEquals('txt', $file->getClientExtension()); + $this->assertEquals('text/plain', $file->getClientMimeType()); + $this->assertEquals(124, $file->getSize()); + } + + //-------------------------------------------------------------------- + + + public function testAllReturnsValidMultipleFilesDifferentName() + { + $_FILES = [ + 'userfile1' => [ + 'name' => 'fileA.txt', + 'type' => 'text/plain', + 'size' => 124, + 'tmp_name' => '/tmp/fileA.txt', + 'error' => 0 + ], + 'userfile2' => [ + 'name' => 'fileB.txt', + 'type' => 'text/csv', + 'size' => 248, + 'tmp_name' => '/tmp/fileB.txt', + 'error' => 0 + ], + ]; + + $collection = new FileCollection(); + $files = $collection->all(); + $this->assertCount(2, $files); + $this->assertEquals('userfile1', key($files)); + + $file = array_shift($files); + $this->assertInstanceOf(UploadedFile::class, $file); + + $this->assertEquals('fileA.txt', $file->getName()); + $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); + $this->assertEquals('txt', $file->getClientExtension()); + $this->assertEquals('text/plain', $file->getClientMimeType()); + $this->assertEquals(124, $file->getSize()); + + $file = array_pop($files); + $this->assertInstanceOf(UploadedFile::class, $file); + + $this->assertEquals('fileB.txt', $file->getName()); + $this->assertEquals('/tmp/fileB.txt', $file->getTempName()); + $this->assertEquals('txt', $file->getClientExtension()); + $this->assertEquals('text/csv', $file->getClientMimeType()); + $this->assertEquals(248, $file->getSize()); + } + + //-------------------------------------------------------------------- + + /** + * @group single + */ + public function testAllReturnsValidSingleFileNestedName() + { + $_FILES = [ + 'userfile' => [ + 'name' => [ + 'foo' => [ + 'bar' => 'fileA.txt' + ] + ], + 'type' => [ + 'foo' => [ + 'bar' => 'text/plain' + ] + ], + 'size' => [ + 'foo' => [ + 'bar' => 124 + ] + ], + 'tmp_name' => [ + 'foo' => [ + 'bar' => '/tmp/fileA.txt' + ] + ], + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + $files = $collection->all(); + $this->assertCount(1, $files); + $this->assertEquals('userfile', key($files)); + + $this->assertArrayHasKey('bar', $files['userfile']['foo']); + + $file = $files['userfile']['foo']['bar']; + $this->assertInstanceOf(UploadedFile::class, $file); + + $this->assertEquals('fileA.txt', $file->getName()); + $this->assertEquals('/tmp/fileA.txt', $file->getTempName()); + $this->assertEquals('txt', $file->getClientExtension()); + $this->assertEquals('text/plain', $file->getClientMimeType()); + $this->assertEquals(124, $file->getSize()); + } + + //-------------------------------------------------------------------- + + public function testHasFileWithSingleFile() + { + $_FILES = [ + 'userfile' => [ + 'name' => 'someFile.txt', + 'type' => 'text/plain', + 'size' => '124', + 'tmp_name' => '/tmp/myTempFile.txt', + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + + $this->assertTrue($collection->hasFile('userfile')); + $this->assertFalse($collection->hasFile('foo')); + } + + //-------------------------------------------------------------------- + + public function testHasFileWithMultipleFilesWithDifferentNames() + { + $_FILES = [ + 'userfile1' => [ + 'name' => 'fileA.txt', + 'type' => 'text/plain', + 'size' => 124, + 'tmp_name' => '/tmp/fileA.txt', + 'error' => 0 + ], + 'userfile2' => [ + 'name' => 'fileB.txt', + 'type' => 'text/csv', + 'size' => 248, + 'tmp_name' => '/tmp/fileB.txt', + 'error' => 0 + ], + ]; + + $collection = new FileCollection(); + + $this->assertTrue($collection->hasFile('userfile1')); + $this->assertTrue($collection->hasFile('userfile2')); + } + + //-------------------------------------------------------------------- + + /** + * @group single + */ + public function testHasFileWithSingleFileNestedName() + { + $_FILES = [ + 'userfile' => [ + 'name' => [ + 'foo' => [ + 'bar' => 'fileA.txt' + ] + ], + 'type' => [ + 'foo' => [ + 'bar' => 'text/plain' + ] + ], + 'size' => [ + 'foo' => [ + 'bar' => 124 + ] + ], + 'tmp_name' => [ + 'foo' => [ + 'bar' => '/tmp/fileA.txt' + ] + ], + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + + $this->assertTrue($collection->hasFile('userfile')); + $this->assertTrue($collection->hasFile('userfile.foo')); + $this->assertTrue($collection->hasFile('userfile.foo.bar')); + } + + //-------------------------------------------------------------------- + + public function testErrorString() + { + $_FILES = [ + 'userfile' => [ + 'name' => 'someFile.txt', + 'type' => 'text/plain', + 'size' => '124', + 'tmp_name' => '/tmp/myTempFile.txt', + 'error' => UPLOAD_ERR_INI_SIZE + ] + ]; + + $expected = 'The file "someFile.txt" exceeds your upload_max_filesize ini directive.'; + + $collection = new FileCollection(); + $file = $collection->getFile('userfile'); + + $this->assertEquals($expected, $file->getErrorString()); + } //-------------------------------------------------------------------- @@ -321,84 +321,84 @@ public function testFileNoExistSingleFile() { public function testFileReturnValidMultipleFiles() { $_FILES = [ - 'userfile' => [ - 'name' => ['fileA.txt', 'fileB.txt'], - 'type' => ['text/plain', 'text/csv'], - 'size' => ['124', '248'], - 'tmp_name' => ['/tmp/fileA.txt', '/tmp/fileB.txt'], - 'error' => 0 - ] - ]; - - $collection = new FileCollection(); - - $file_1 = $collection->getFile('userfile.0'); - $this->assertInstanceOf(UploadedFile::class, $file_1); - $this->assertEquals('fileA.txt', $file_1->getName()); - $this->assertEquals('/tmp/fileA.txt', $file_1->getTempName()); - $this->assertEquals('txt', $file_1->getClientExtension()); - $this->assertEquals('text/plain', $file_1->getClientMimeType()); - $this->assertEquals(124, $file_1->getSize()); - - $file_2 = $collection->getFile('userfile.1'); - $this->assertInstanceOf(UploadedFile::class, $file_2); - $this->assertEquals('fileB.txt', $file_2->getName()); - $this->assertEquals('/tmp/fileB.txt', $file_2->getTempName()); - $this->assertEquals('txt', $file_2->getClientExtension()); - $this->assertEquals('text/csv', $file_2->getClientMimeType()); - $this->assertEquals(248, $file_2->getSize()); + 'userfile' => [ + 'name' => ['fileA.txt', 'fileB.txt'], + 'type' => ['text/plain', 'text/csv'], + 'size' => ['124', '248'], + 'tmp_name' => ['/tmp/fileA.txt', '/tmp/fileB.txt'], + 'error' => 0 + ] + ]; + + $collection = new FileCollection(); + + $file_1 = $collection->getFile('userfile.0'); + $this->assertInstanceOf(UploadedFile::class, $file_1); + $this->assertEquals('fileA.txt', $file_1->getName()); + $this->assertEquals('/tmp/fileA.txt', $file_1->getTempName()); + $this->assertEquals('txt', $file_1->getClientExtension()); + $this->assertEquals('text/plain', $file_1->getClientMimeType()); + $this->assertEquals(124, $file_1->getSize()); + + $file_2 = $collection->getFile('userfile.1'); + $this->assertInstanceOf(UploadedFile::class, $file_2); + $this->assertEquals('fileB.txt', $file_2->getName()); + $this->assertEquals('/tmp/fileB.txt', $file_2->getTempName()); + $this->assertEquals('txt', $file_2->getClientExtension()); + $this->assertEquals('text/csv', $file_2->getClientMimeType()); + $this->assertEquals(248, $file_2->getSize()); } //-------------------------------------------------------------------- public function testFileWithMultipleFilesNestedName() { $_FILES = [ - 'my-form' => [ - 'name' => [ - 'details' => [ - 'avatars' => ['fileA.txt','fileB.txt'] - ] - ], - 'type' => [ - 'details' => [ - 'avatars' => ['text/plain','text/plain'] - ] - ], - 'size' => [ - 'details' => [ - 'avatars' => [125,243] - ] - ], - 'tmp_name' => [ - 'details' => [ - 'avatars' => ['/tmp/fileA.txt','/tmp/fileB.txt'] - ] - ], - 'error' => [ - 'details' => [ - 'avatars' => [0,0] - ] - ], - ] - ]; + 'my-form' => [ + 'name' => [ + 'details' => [ + 'avatars' => ['fileA.txt','fileB.txt'] + ] + ], + 'type' => [ + 'details' => [ + 'avatars' => ['text/plain','text/plain'] + ] + ], + 'size' => [ + 'details' => [ + 'avatars' => [125,243] + ] + ], + 'tmp_name' => [ + 'details' => [ + 'avatars' => ['/tmp/fileA.txt','/tmp/fileB.txt'] + ] + ], + 'error' => [ + 'details' => [ + 'avatars' => [0,0] + ] + ], + ] + ]; $collection = new FileCollection(); $file_1 = $collection->getFile('my-form.details.avatars.0'); $this->assertInstanceOf(UploadedFile::class, $file_1); $this->assertEquals('fileA.txt', $file_1->getName()); - $this->assertEquals('/tmp/fileA.txt', $file_1->getTempName()); - $this->assertEquals('txt', $file_1->getClientExtension()); - $this->assertEquals('text/plain', $file_1->getClientMimeType()); - $this->assertEquals(125, $file_1->getSize()); + $this->assertEquals('/tmp/fileA.txt', $file_1->getTempName()); + $this->assertEquals('txt', $file_1->getClientExtension()); + $this->assertEquals('text/plain', $file_1->getClientMimeType()); + $this->assertEquals(125, $file_1->getSize()); $file_2 = $collection->getFile('my-form.details.avatars.1'); $this->assertInstanceOf(UploadedFile::class, $file_2); $this->assertEquals('fileB.txt', $file_2->getName()); - $this->assertEquals('/tmp/fileB.txt', $file_2->getTempName()); - $this->assertEquals('txt', $file_2->getClientExtension()); - $this->assertEquals('text/plain', $file_2->getClientMimeType()); - $this->assertEquals(243, $file_2->getSize()); + $this->assertEquals('/tmp/fileB.txt', $file_2->getTempName()); + $this->assertEquals('txt', $file_2->getClientExtension()); + $this->assertEquals('text/plain', $file_2->getClientMimeType()); + $this->assertEquals(243, $file_2->getSize()); } /** @@ -512,7 +512,7 @@ public function testMoveWhereOverwriteIsTrueWithMultipleFilesWithSameName() rmdir($destination); } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } /* diff --git a/tests/system/HTTP/HeaderTest.php b/tests/system/HTTP/HeaderTest.php index 1c805d2967b5..963ffdef3b04 100644 --- a/tests/system/HTTP/HeaderTest.php +++ b/tests/system/HTTP/HeaderTest.php @@ -2,124 +2,124 @@ class HeaderTest extends \CIUnitTestCase { - public function testHeaderStoresBasics() - { - $name = 'foo'; - $value = 'bar'; + public function testHeaderStoresBasics() + { + $name = 'foo'; + $value = 'bar'; - $header = new \CodeIgniter\HTTP\Header($name, $value); + $header = new \CodeIgniter\HTTP\Header($name, $value); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($value, $header->getValue()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($value, $header->getValue()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderStoresArrayValues() - { - $name = 'foo'; - $value = ['bar', 'baz']; + public function testHeaderStoresArrayValues() + { + $name = 'foo'; + $value = ['bar', 'baz']; - $header = new \CodeIgniter\HTTP\Header($name, $value); + $header = new \CodeIgniter\HTTP\Header($name, $value); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($value, $header->getValue()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($value, $header->getValue()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderSetters() - { - $name = 'foo'; - $value = ['bar', 'baz']; + public function testHeaderSetters() + { + $name = 'foo'; + $value = ['bar', 'baz']; - $header = new \CodeIgniter\HTTP\Header(); + $header = new \CodeIgniter\HTTP\Header(); - $header->setName($name)->setValue($value); + $header->setName($name)->setValue($value); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($value, $header->getValue()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($value, $header->getValue()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderConvertsSingleToArray() - { - $name = 'foo'; - $value = 'bar'; + public function testHeaderConvertsSingleToArray() + { + $name = 'foo'; + $value = 'bar'; - $expected = ['bar', 'baz']; + $expected = ['bar', 'baz']; - $header = new \CodeIgniter\HTTP\Header($name, $value); + $header = new \CodeIgniter\HTTP\Header($name, $value); - $header->appendValue('baz'); + $header->appendValue('baz'); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($expected, $header->getValue()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($expected, $header->getValue()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderPrependsValue() - { - $name = 'foo'; - $value = 'bar'; + public function testHeaderPrependsValue() + { + $name = 'foo'; + $value = 'bar'; - $expected = ['baz', 'bar']; + $expected = ['baz', 'bar']; - $header = new \CodeIgniter\HTTP\Header($name, $value); + $header = new \CodeIgniter\HTTP\Header($name, $value); - $header->prependValue('baz'); + $header->prependValue('baz'); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($expected, $header->getValue()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($expected, $header->getValue()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderLineSimple() - { - $name = 'foo'; - $value = ['bar', 'baz']; + public function testHeaderLineSimple() + { + $name = 'foo'; + $value = ['bar', 'baz']; - $expected = 'bar, baz'; + $expected = 'bar, baz'; - $header = new \CodeIgniter\HTTP\Header($name, $value); + $header = new \CodeIgniter\HTTP\Header($name, $value); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($expected, $header->getValueLine()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($expected, $header->getValueLine()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderLineWithArrayValues() - { - $name = 'foo'; + public function testHeaderLineWithArrayValues() + { + $name = 'foo'; - $expected = 'bar, baz=fuzz'; + $expected = 'bar, baz=fuzz'; - $header = new \CodeIgniter\HTTP\Header($name); + $header = new \CodeIgniter\HTTP\Header($name); - $header->setValue('bar') - ->appendValue(['baz' => 'fuzz']); + $header->setValue('bar') + ->appendValue(['baz' => 'fuzz']); - $this->assertEquals($name, $header->getName()); - $this->assertEquals($expected, $header->getValueLine()); - } + $this->assertEquals($name, $header->getName()); + $this->assertEquals($expected, $header->getValueLine()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHeaderToStringShowsEntireHeader() - { - $name = 'foo'; + public function testHeaderToStringShowsEntireHeader() + { + $name = 'foo'; - $expected = 'foo: bar, baz=fuzz'; + $expected = 'foo: bar, baz=fuzz'; - $header = new \CodeIgniter\HTTP\Header($name); + $header = new \CodeIgniter\HTTP\Header($name); - $header->setValue('bar') - ->appendValue(['baz' => 'fuzz']); + $header->setValue('bar') + ->appendValue(['baz' => 'fuzz']); - $this->assertEquals($expected, (string)$header); - } + $this->assertEquals($expected, (string)$header); + } } diff --git a/tests/system/HTTP/IncomingRequestTest.php b/tests/system/HTTP/IncomingRequestTest.php index eef7b028e66c..a133fda7fa73 100644 --- a/tests/system/HTTP/IncomingRequestTest.php +++ b/tests/system/HTTP/IncomingRequestTest.php @@ -7,60 +7,60 @@ */ class IncomingRequestTest extends \CIUnitTestCase { - /** - * @var \CodeIgniter\HTTP\IncomingRequest - */ - protected $request; + /** + * @var \CodeIgniter\HTTP\IncomingRequest + */ + protected $request; - public function setUp() - { - $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent()); + public function setUp() + { + $this->request = new IncomingRequest(new App(), new URI(), null, new UserAgent()); - $_POST = $_GET = $_SERVER = $_REQUEST = $_ENV = $_COOKIE = $_SESSION = []; - } + $_POST = $_GET = $_SERVER = $_REQUEST = $_ENV = $_COOKIE = $_SESSION = []; + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCanGrabRequestVars() - { - $_REQUEST['TEST'] = 5; + public function testCanGrabRequestVars() + { + $_REQUEST['TEST'] = 5; - $this->assertEquals(5, $this->request->getVar('TEST')); - $this->assertNull($this->request->getVar('TESTY')); - } + $this->assertEquals(5, $this->request->getVar('TEST')); + $this->assertNull($this->request->getVar('TESTY')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCanGrabGetVars() - { - $_GET['TEST'] = 5; + public function testCanGrabGetVars() + { + $_GET['TEST'] = 5; - $this->assertEquals(5, $this->request->getGet('TEST')); - $this->assertNull($this->request->getGEt('TESTY')); - } + $this->assertEquals(5, $this->request->getGet('TEST')); + $this->assertNull($this->request->getGEt('TESTY')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCanGrabPostVars() - { - $_POST['TEST'] = 5; + public function testCanGrabPostVars() + { + $_POST['TEST'] = 5; - $this->assertEquals(5, $this->request->getPost('TEST')); - $this->assertNull($this->request->getPost('TESTY')); - } + $this->assertEquals(5, $this->request->getPost('TEST')); + $this->assertNull($this->request->getPost('TESTY')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCanGrabPostBeforeGet() - { - $_POST['TEST'] = 5; - $_GET['TEST'] = 3; + public function testCanGrabPostBeforeGet() + { + $_POST['TEST'] = 5; + $_GET['TEST'] = 3; - $this->assertEquals(5, $this->request->getPostGet('TEST')); - $this->assertEquals(3, $this->request->getGetPost('TEST')); - } + $this->assertEquals(5, $this->request->getPostGet('TEST')); + $this->assertEquals(3, $this->request->getGetPost('TEST')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- /** * @group single @@ -77,110 +77,110 @@ public function testCanGetOldInput() } - public function testCanGrabServerVars() - { - $_SERVER['TEST'] = 5; - - $this->assertEquals(5, $this->request->getServer('TEST')); - $this->assertNull($this->request->getServer('TESTY')); - } - - //-------------------------------------------------------------------- - - public function testCanGrabEnvVars() - { - $_ENV['TEST'] = 5; - - $this->assertEquals(5, $this->request->getEnv('TEST')); - $this->assertNull($this->request->getEnv('TESTY')); - } - - //-------------------------------------------------------------------- - - public function testCanGrabCookieVars() - { - $_COOKIE['TEST'] = 5; - - $this->assertEquals(5, $this->request->getCookie('TEST')); - $this->assertNull($this->request->getCookie('TESTY')); - } - - //-------------------------------------------------------------------- - - public function testFetchGlobalReturnsSingleValue() - { - $_POST = [ - 'foo' => 'bar', - 'bar' => 'baz', - 'xxx' => 'yyy', - 'yyy' => 'zzz' - ]; - - $this->assertEquals('baz', $this->request->getPost('bar')); - } - - //-------------------------------------------------------------------- - - public function testFetchGlobalWithArrayTop() - { - $_POST = [ - 'clients' => [ - 'address' => [ - 'zipcode' => 90210 - ] - ] - ]; - - $this->assertEquals(['address' => ['zipcode' => 90210]], $this->request->getPost('clients')); - } - - public function testFetchGlobalWithArrayChildNumeric() - { - $_POST = [ - 'clients' => [ - [ - 'address' => [ - 'zipcode' => 90210 - ], - ], - [ - 'address' => [ - 'zipcode' => 60610 - ], - ], - ] - ]; - - $this->assertEquals(['zipcode' => 60610], $this->request->getPost('clients[1][address]')); - } - - public function testFetchGlobalWithArrayChildElement() - { - $_POST = [ - 'clients' => [ - 'address' => [ - 'zipcode' => 90210 - ], - ] - ]; - - $this->assertEquals(['zipcode' => 90210], $this->request->getPost('clients[address]')); - } - - public function testFetchGlobalWithArrayLastElement() - { - $_POST = [ - 'clients' => [ - 'address' => [ - 'zipcode' => 90210 - ] - ] - ]; - - $this->assertEquals(90210, $this->request->getPost('clients[address][zipcode]')); - } - - /** + public function testCanGrabServerVars() + { + $_SERVER['TEST'] = 5; + + $this->assertEquals(5, $this->request->getServer('TEST')); + $this->assertNull($this->request->getServer('TESTY')); + } + + //-------------------------------------------------------------------- + + public function testCanGrabEnvVars() + { + $_ENV['TEST'] = 5; + + $this->assertEquals(5, $this->request->getEnv('TEST')); + $this->assertNull($this->request->getEnv('TESTY')); + } + + //-------------------------------------------------------------------- + + public function testCanGrabCookieVars() + { + $_COOKIE['TEST'] = 5; + + $this->assertEquals(5, $this->request->getCookie('TEST')); + $this->assertNull($this->request->getCookie('TESTY')); + } + + //-------------------------------------------------------------------- + + public function testFetchGlobalReturnsSingleValue() + { + $_POST = [ + 'foo' => 'bar', + 'bar' => 'baz', + 'xxx' => 'yyy', + 'yyy' => 'zzz' + ]; + + $this->assertEquals('baz', $this->request->getPost('bar')); + } + + //-------------------------------------------------------------------- + + public function testFetchGlobalWithArrayTop() + { + $_POST = [ + 'clients' => [ + 'address' => [ + 'zipcode' => 90210 + ] + ] + ]; + + $this->assertEquals(['address' => ['zipcode' => 90210]], $this->request->getPost('clients')); + } + + public function testFetchGlobalWithArrayChildNumeric() + { + $_POST = [ + 'clients' => [ + [ + 'address' => [ + 'zipcode' => 90210 + ], + ], + [ + 'address' => [ + 'zipcode' => 60610 + ], + ], + ] + ]; + + $this->assertEquals(['zipcode' => 60610], $this->request->getPost('clients[1][address]')); + } + + public function testFetchGlobalWithArrayChildElement() + { + $_POST = [ + 'clients' => [ + 'address' => [ + 'zipcode' => 90210 + ], + ] + ]; + + $this->assertEquals(['zipcode' => 90210], $this->request->getPost('clients[address]')); + } + + public function testFetchGlobalWithArrayLastElement() + { + $_POST = [ + 'clients' => [ + 'address' => [ + 'zipcode' => 90210 + ] + ] + ]; + + $this->assertEquals(90210, $this->request->getPost('clients[address][zipcode]')); + } + + /** * @see https://github.com/bcit-ci/CodeIgniter4/issues/353 */ public function testGetPostReturnsArrayValues() @@ -206,221 +206,221 @@ public function testGetPostReturnsArrayValues() //-------------------------------------------------------------------- - public function testFetchGlobalFiltersValue() - { - $_POST = [ - 'foo' => 'bar', - script_tag('http://site.com/js/mystyles.js') - ); - } - - // ------------------------------------------------------------------------ - - public function testLinkTag() - { - $this->assertEquals - ( - '', - link_tag('http://site.com/css/mystyles.css') - ); - } - - // ------------------------------------------------------------------------ - - public function testDocType() - { - $this->assertEquals - ( - '', - doctype('html4-strict') - ); - } - - // ------------------------------------------------------------------------ - - public function testVideo() - { - $expected = <<assertEquals(ltrim($expected), ol($list)); + } + + // ------------------------------------------------------------------------ + + public function testIMG() + { + //TODO: Mock baseURL and siteURL. + $this->assertEquals + ( + '', + img('http://site.com/images/picture.jpg') + ); + } + + // ------------------------------------------------------------------------ + + public function testScriptTag() + { + $this->assertEquals + ( + '', + script_tag('http://site.com/js/mystyles.js') + ); + } + + // ------------------------------------------------------------------------ + + public function testLinkTag() + { + $this->assertEquals + ( + '', + link_tag('http://site.com/css/mystyles.css') + ); + } + + // ------------------------------------------------------------------------ + + public function testDocType() + { + $this->assertEquals + ( + '', + doctype('html4-strict') + ); + } + + // ------------------------------------------------------------------------ + + public function testVideo() + { + $expected = << Your browser does not support the video tag. EOH; - $video = video - ( - 'test.mp4', - 'Your browser does not support the video tag.', - 'controls' - ); + $video = video + ( + 'test.mp4', + 'Your browser does not support the video tag.', + 'controls' + ); - $this->assertEquals($expected, $video); + $this->assertEquals($expected, $video); - $expected = << @@ -204,16 +204,16 @@ public function testVideo() EOH; - $video = video - ( - 'http://www.codeigniter.com/test.mp4', - 'Your browser does not support the video tag.', - 'controls', - $this->tracks - ); - $this->assertEquals($expected, $video); + $video = video + ( + 'http://www.codeigniter.com/test.mp4', + 'Your browser does not support the video tag.', + 'controls', + $this->tracks + ); + $this->assertEquals($expected, $video); - $expected = << @@ -226,27 +226,27 @@ public function testVideo() EOH; - $video = video - ( - [ - source('movie.mp4', 'video/mp4', 'class="test"'), - source('movie.ogg', 'video/ogg'), - source('movie.mov', 'video/quicktime'), - source('movie.ogv', 'video/ogv; codecs=dirac, speex') - ], - 'Your browser does not support the video tag.', - 'class="test" controls', - $this->tracks - ); - - $this->assertEquals($expected, $video); - } - - // ------------------------------------------------------------------------ - - public function testAudio() - { - $expected = <<tracks + ); + + $this->assertEquals($expected, $video); + } + + // ------------------------------------------------------------------------ + + public function testAudio() + { + $expected = << @@ -257,70 +257,70 @@ public function testAudio() EOH; - $audio = audio - ( - [ - source('sound.ogg', 'audio/ogg'), - source('sound.mpeg', 'audio/mpeg') - ], - 'Your browser does not support the audio tag.', - 'id="test" controls', - $this->tracks - ); - - $this->assertEquals($expected, $audio); - } - - // ------------------------------------------------------------------------ - - public function testEmbed() - { - $expected = <<tracks + ); + + $this->assertEquals($expected, $audio); + } + + // ------------------------------------------------------------------------ + + public function testEmbed() + { + $expected = << EOH; - $embed = embed('movie.mov', 'video/quicktime', 'class="test"'); - $this->assertEquals($expected, $embed); - } + $embed = embed('movie.mov', 'video/quicktime', 'class="test"'); + $this->assertEquals($expected, $embed); + } - public function testObject() - { - $expected = << EOH; - - $object = object - ( - 'movie.swf', - 'application/x-shockwave-flash', - 'class="test"' - ); - - $this->assertEquals($expected, $object); - - $expected = <<assertEquals($expected, $object); + + $expected = << EOH; - - $object = object - ( - 'movie.swf', - 'application/x-shockwave-flash', - 'class="test"', - [ - param('foo', 'bar', 'ref', 'class="test"'), - param('hello', 'world', 'ref', 'class="test"') - ] - ); - $this->assertEquals($expected, $object); - } - - // ------------------------------------------------------------------------ + + $object = object + ( + 'movie.swf', + 'application/x-shockwave-flash', + 'class="test"', + [ + param('foo', 'bar', 'ref', 'class="test"'), + param('hello', 'world', 'ref', 'class="test"') + ] + ); + $this->assertEquals($expected, $object); + } + + // ------------------------------------------------------------------------ } diff --git a/tests/system/Helpers/InflectorHelperTest.php b/tests/system/Helpers/InflectorHelperTest.php index 4afe56f49017..29cca3bab3df 100755 --- a/tests/system/Helpers/InflectorHelperTest.php +++ b/tests/system/Helpers/InflectorHelperTest.php @@ -4,226 +4,226 @@ final class InflectorHelperTest extends \CIUnitTestCase { - public function setUp() - { - helper('inflector'); - } - - //-------------------------------------------------------------------- - - public function testSingular() - { - $strings = - [ - 'matrices' => 'matrix', - 'oxen' => 'ox', - 'aliases' => 'alias', - 'octupus' => 'octupus', - 'shoes' => 'shoe', - 'buses' => 'bus', - 'campus' => 'campus', - 'campuses' => 'campus', - 'mice' => 'mouse', - 'movies' => 'movie', - 'series' => 'series', - 'hives' => 'hive', - 'lives' => 'life', - 'analyses' => 'analysis', - 'men' => 'man', - 'people' => 'person', - 'children' => 'child', - 'statuses' => 'status', - 'news' => 'news', - 'us' => 'us', - 'tests' => 'test', - 'queries' => 'query', - 'dogs' => 'dog', - 'cats' => 'cat', - 'families' => 'family', - 'countries' => 'country' - ]; - - foreach ($strings as $pluralizedString => $singularizedString) - { - $singular = singular($pluralizedString); - $this->assertEquals($singular, $singularizedString); - } - } - - //-------------------------------------------------------------------- - - public function testPlural() - { - $strings = - [ - 'searches' => 'search', - 'matrices' => 'matrix', - 'oxen' => 'ox', - 'aliases' => 'alias', - 'octupus' => 'octupus', - 'shoes' => 'shoe', - 'buses' => 'bus', - 'mice' => 'mouse', - 'movies' => 'movie', - 'series' => 'series', - 'hives' => 'hive', - 'lives' => 'life', - 'analyses' => 'analysis', - 'men' => 'man', - 'people' => 'person', - 'children' => 'child', - 'statuses' => 'status', - 'news' => 'news', - 'us' => 'us', - 'tests' => 'test', - 'queries' => 'query', - 'dogs' => 'dog', - 'cats' => 'cat', - 'families' => 'family', - 'countries' => 'country' - ]; - - foreach ($strings as $pluralizedString => $singularizedString) - { - $plural = plural($singularizedString); - $this->assertEquals($plural, $pluralizedString); - } - } - - //-------------------------------------------------------------------- - - public function testCamelize() - { - $strings = - [ - 'hello from codeIgniter 4' => 'helloFromCodeIgniter4', - 'hello_world' => 'helloWorld' - ]; - - foreach ($strings as $lowerCasedString => $camelizedString) - { - $camelized = camelize($lowerCasedString); - $this->assertEquals($camelized, $camelizedString); - } - } - - //-------------------------------------------------------------------- - - public function testUnderscore() - { - $strings = - [ - 'Hello From CodeIgniter 4' => 'Hello_From_CodeIgniter_4', - 'hello world' => 'hello_world' - ]; - - foreach ($strings as $spaced => $underscore) - { - $underscored = underscore($spaced); - $this->assertEquals($underscored, $underscore); - } - } - - //-------------------------------------------------------------------- - - public function testHumanize() - { - $underscored = ['Hello_From_CodeIgniter_4', 'Hello From CodeIgniter 4']; - $dashed = ['hello-world' , 'Hello World']; - - $humanizedUnderscore = humanize($underscored[0]); - $humanizedDash = humanize($dashed[0], '-'); - - $this->assertEquals($humanizedUnderscore, $underscored[1]); - $this->assertEquals($humanizedDash, $dashed[1]); - } - - //-------------------------------------------------------------------- - - public function testIsCountable() - { - $words = - [ - 'tip' => 'advice', - 'fight' => 'bravery', - 'thing' => 'equipment', - 'deocration' => 'jewelry', - 'line' => 'series', - 'letter' => 'spelling' - ]; - - foreach ($words as $countable => $unCountable) - { - $this->assertTrue(is_countable($countable)); - $this->assertFalse(is_countable($unCountable)); - } - } - - //-------------------------------------------------------------------- - - public function testDasherize() - { - $strings = - [ - 'hello_world' => 'hello-world', - 'Hello_From_CodeIgniter_4' => 'Hello-From-CodeIgniter-4' - ]; - - foreach ($strings as $underscored => $dashed) - { - $dasherized = dasherize($underscored); - $this->assertEquals($dasherized, $dashed); - } - } - - //-------------------------------------------------------------------- - - public function testOrdinal() - { - $suffixes = - [ - 'st' => 1, - 'nd' => 2, - 'rd' => 3, - 'th' => 4, - 'th' => 11, - 'th' => 20, - 'st' => 21, - 'nd' => 22, - 'rd' => 23, - 'th' => 24 - ]; - - foreach ($suffixes as $suffix => $number) - { - $ordinal = ordinal($number); - $this->assertEquals($suffix, $ordinal); - } - } - - //-------------------------------------------------------------------- - - public function testOrdinalize() - { - $suffixedNumbers = - [ - '1st' => 1, - '2nd' => 2, - '3rd' => 3, - '4th' => 4, - '11th' => 11, - '20th' => 20, - '21st' => 21, - '22nd' => 22, - '23rd' => 23, - '24th' => 24 - ]; - - foreach ($suffixedNumbers as $suffixed => $number) - { - $ordinalized = ordinalize($number); - $this->assertEquals($suffixed, $ordinalized); - } - } + public function setUp() + { + helper('inflector'); + } + + //-------------------------------------------------------------------- + + public function testSingular() + { + $strings = + [ + 'matrices' => 'matrix', + 'oxen' => 'ox', + 'aliases' => 'alias', + 'octupus' => 'octupus', + 'shoes' => 'shoe', + 'buses' => 'bus', + 'campus' => 'campus', + 'campuses' => 'campus', + 'mice' => 'mouse', + 'movies' => 'movie', + 'series' => 'series', + 'hives' => 'hive', + 'lives' => 'life', + 'analyses' => 'analysis', + 'men' => 'man', + 'people' => 'person', + 'children' => 'child', + 'statuses' => 'status', + 'news' => 'news', + 'us' => 'us', + 'tests' => 'test', + 'queries' => 'query', + 'dogs' => 'dog', + 'cats' => 'cat', + 'families' => 'family', + 'countries' => 'country' + ]; + + foreach ($strings as $pluralizedString => $singularizedString) + { + $singular = singular($pluralizedString); + $this->assertEquals($singular, $singularizedString); + } + } + + //-------------------------------------------------------------------- + + public function testPlural() + { + $strings = + [ + 'searches' => 'search', + 'matrices' => 'matrix', + 'oxen' => 'ox', + 'aliases' => 'alias', + 'octupus' => 'octupus', + 'shoes' => 'shoe', + 'buses' => 'bus', + 'mice' => 'mouse', + 'movies' => 'movie', + 'series' => 'series', + 'hives' => 'hive', + 'lives' => 'life', + 'analyses' => 'analysis', + 'men' => 'man', + 'people' => 'person', + 'children' => 'child', + 'statuses' => 'status', + 'news' => 'news', + 'us' => 'us', + 'tests' => 'test', + 'queries' => 'query', + 'dogs' => 'dog', + 'cats' => 'cat', + 'families' => 'family', + 'countries' => 'country' + ]; + + foreach ($strings as $pluralizedString => $singularizedString) + { + $plural = plural($singularizedString); + $this->assertEquals($plural, $pluralizedString); + } + } + + //-------------------------------------------------------------------- + + public function testCamelize() + { + $strings = + [ + 'hello from codeIgniter 4' => 'helloFromCodeIgniter4', + 'hello_world' => 'helloWorld' + ]; + + foreach ($strings as $lowerCasedString => $camelizedString) + { + $camelized = camelize($lowerCasedString); + $this->assertEquals($camelized, $camelizedString); + } + } + + //-------------------------------------------------------------------- + + public function testUnderscore() + { + $strings = + [ + 'Hello From CodeIgniter 4' => 'Hello_From_CodeIgniter_4', + 'hello world' => 'hello_world' + ]; + + foreach ($strings as $spaced => $underscore) + { + $underscored = underscore($spaced); + $this->assertEquals($underscored, $underscore); + } + } + + //-------------------------------------------------------------------- + + public function testHumanize() + { + $underscored = ['Hello_From_CodeIgniter_4', 'Hello From CodeIgniter 4']; + $dashed = ['hello-world' , 'Hello World']; + + $humanizedUnderscore = humanize($underscored[0]); + $humanizedDash = humanize($dashed[0], '-'); + + $this->assertEquals($humanizedUnderscore, $underscored[1]); + $this->assertEquals($humanizedDash, $dashed[1]); + } + + //-------------------------------------------------------------------- + + public function testIsCountable() + { + $words = + [ + 'tip' => 'advice', + 'fight' => 'bravery', + 'thing' => 'equipment', + 'deocration' => 'jewelry', + 'line' => 'series', + 'letter' => 'spelling' + ]; + + foreach ($words as $countable => $unCountable) + { + $this->assertTrue(is_countable($countable)); + $this->assertFalse(is_countable($unCountable)); + } + } + + //-------------------------------------------------------------------- + + public function testDasherize() + { + $strings = + [ + 'hello_world' => 'hello-world', + 'Hello_From_CodeIgniter_4' => 'Hello-From-CodeIgniter-4' + ]; + + foreach ($strings as $underscored => $dashed) + { + $dasherized = dasherize($underscored); + $this->assertEquals($dasherized, $dashed); + } + } + + //-------------------------------------------------------------------- + + public function testOrdinal() + { + $suffixes = + [ + 'st' => 1, + 'nd' => 2, + 'rd' => 3, + 'th' => 4, + 'th' => 11, + 'th' => 20, + 'st' => 21, + 'nd' => 22, + 'rd' => 23, + 'th' => 24 + ]; + + foreach ($suffixes as $suffix => $number) + { + $ordinal = ordinal($number); + $this->assertEquals($suffix, $ordinal); + } + } + + //-------------------------------------------------------------------- + + public function testOrdinalize() + { + $suffixedNumbers = + [ + '1st' => 1, + '2nd' => 2, + '3rd' => 3, + '4th' => 4, + '11th' => 11, + '20th' => 20, + '21st' => 21, + '22nd' => 22, + '23rd' => 23, + '24th' => 24 + ]; + + foreach ($suffixedNumbers as $suffixed => $number) + { + $ordinalized = ordinalize($number); + $this->assertEquals($suffixed, $ordinalized); + } + } } diff --git a/tests/system/Helpers/TextHelperTest.php b/tests/system/Helpers/TextHelperTest.php index 813f6ba999d7..90dca6d022fa 100755 --- a/tests/system/Helpers/TextHelperTest.php +++ b/tests/system/Helpers/TextHelperTest.php @@ -3,107 +3,107 @@ class TextHelperTest extends \CIUnitTestCase { private $_long_string = 'Once upon a time, a framework had no tests. It sad. So some nice people began to write tests. The more time that went on, the happier it became. Everyone was happy.'; - + public function setUp() { helper('text'); } - + // -------------------------------------------------------------------- - + public function test_strip_slashes() - { - $expected = [ - "Is your name O'reilly?", - "No, my name is O'connor." - ]; - $str = [ - "Is your name O\'reilly?", - "No, my name is O\'connor." - ]; - $this->assertEquals($expected, strip_slashes($str)); - } - // -------------------------------------------------------------------- - public function test_strip_quotes() - { - $strs = [ - '"me oh my!"' => 'me oh my!', - "it's a winner!" => 'its a winner!', - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, strip_quotes($str)); - } - } - // -------------------------------------------------------------------- - public function test_quotes_to_entities() - { - $strs = [ - '"me oh my!"' => '"me oh my!"', - "it's a winner!" => 'it's a winner!', - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, quotes_to_entities($str)); - } - } - // -------------------------------------------------------------------- - public function test_reduce_double_slashes() - { - $strs = [ - 'http://codeigniter.com' => 'http://codeigniter.com', - '//var/www/html/example.com/' => '/var/www/html/example.com/', - '/var/www/html//index.php' => '/var/www/html/index.php' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_double_slashes($str)); - } - } - // -------------------------------------------------------------------- - public function test_reduce_multiples() - { - $strs = [ - 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', - 'Ringo, John, Paul,,' => 'Ringo, John, Paul,' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_multiples($str)); - } - $strs = [ - 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', - 'Ringo, John, Paul,,' => 'Ringo, John, Paul' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_multiples($str, ',', TRUE)); - } - } - // -------------------------------------------------------------------- - public function test_random_string() - { - $this->assertEquals(16, strlen(random_string('alnum', 16))); - $this->assertInternalType('string', random_string('numeric', 16)); + { + $expected = [ + "Is your name O'reilly?", + "No, my name is O'connor." + ]; + $str = [ + "Is your name O\'reilly?", + "No, my name is O\'connor." + ]; + $this->assertEquals($expected, strip_slashes($str)); + } + // -------------------------------------------------------------------- + public function test_strip_quotes() + { + $strs = [ + '"me oh my!"' => 'me oh my!', + "it's a winner!" => 'its a winner!', + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, strip_quotes($str)); + } + } + // -------------------------------------------------------------------- + public function test_quotes_to_entities() + { + $strs = [ + '"me oh my!"' => '"me oh my!"', + "it's a winner!" => 'it's a winner!', + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, quotes_to_entities($str)); + } + } + // -------------------------------------------------------------------- + public function test_reduce_double_slashes() + { + $strs = [ + 'http://codeigniter.com' => 'http://codeigniter.com', + '//var/www/html/example.com/' => '/var/www/html/example.com/', + '/var/www/html//index.php' => '/var/www/html/index.php' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_double_slashes($str)); + } + } + // -------------------------------------------------------------------- + public function test_reduce_multiples() + { + $strs = [ + 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', + 'Ringo, John, Paul,,' => 'Ringo, John, Paul,' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_multiples($str)); + } + $strs = [ + 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', + 'Ringo, John, Paul,,' => 'Ringo, John, Paul' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_multiples($str, ',', TRUE)); + } + } + // -------------------------------------------------------------------- + public function test_random_string() + { + $this->assertEquals(16, strlen(random_string('alnum', 16))); + $this->assertInternalType('string', random_string('numeric', 16)); $this->assertEquals(16, strlen($random = random_string('crypto', 16))); $this->assertInternalType('string', $random); - } - // -------------------------------------------------------------------- - public function test_increment_string() - { - $this->assertEquals('my-test_1', increment_string('my-test')); - $this->assertEquals('my-test-1', increment_string('my-test', '-')); - $this->assertEquals('file_5', increment_string('file_4')); - $this->assertEquals('file-5', increment_string('file-4', '-')); - $this->assertEquals('file-5', increment_string('file-4', '-')); - $this->assertEquals('file-1', increment_string('file', '-', '1')); - $this->assertEquals(124, increment_string('123', '')); - } - - // ------------------------------------------------------------------- - // Functions from text_helper_test.php - // ------------------------------------------------------------------- - + } + // -------------------------------------------------------------------- + public function test_increment_string() + { + $this->assertEquals('my-test_1', increment_string('my-test')); + $this->assertEquals('my-test-1', increment_string('my-test', '-')); + $this->assertEquals('file_5', increment_string('file_4')); + $this->assertEquals('file-5', increment_string('file-4', '-')); + $this->assertEquals('file-5', increment_string('file-4', '-')); + $this->assertEquals('file-1', increment_string('file', '-', '1')); + $this->assertEquals(124, increment_string('123', '')); + } + + // ------------------------------------------------------------------- + // Functions from text_helper_test.php + // ------------------------------------------------------------------- + public function test_word_limiter() { $this->assertEquals('Once upon a time,…', word_limiter($this->_long_string, 4)); @@ -122,8 +122,8 @@ public function test_character_limiter() public function test_ascii_to_entities() { $strs = [ - '“‘ “test”' => '“‘ “test”', - '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' + '“‘ “test”' => '“‘ “test”', + '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' ]; foreach ($strs as $str => $expect) { @@ -154,11 +154,11 @@ public function test_censored_words() { $censored = ['boob', 'nerd', 'ass', 'fart']; $strs = [ - 'Ted bobbled the ball' => 'Ted bobbled the ball', - 'Jake is a nerdo' => 'Jake is a nerdo', - 'The borg will assimilate you' => 'The borg will assimilate you', - 'Did Mary Fart?' => 'Did Mary $*#?', - 'Jake is really a boob' => 'Jake is really a $*#' + 'Ted bobbled the ball' => 'Ted bobbled the ball', + 'Jake is a nerdo' => 'Jake is a nerdo', + 'The borg will assimilate you' => 'The borg will assimilate you', + 'Did Mary Fart?' => 'Did Mary $*#?', + 'Jake is really a boob' => 'Jake is really a $*#' ]; foreach ($strs as $str => $expect) { @@ -193,23 +193,23 @@ public function test_highlight_phrase() public function test_ellipsize() { $strs = [ - '0' => [ - 'this is my string' => '… my string', - "here's another one" => '…nother one', - 'this one is just a bit longer' => '…bit longer', - 'short' => 'short' + '0' => [ + 'this is my string' => '… my string', + "here's another one" => '…nother one', + 'this one is just a bit longer' => '…bit longer', + 'short' => 'short' ], - '.5' => [ - 'this is my string' => 'this …tring', - "here's another one" => "here'…r one", - 'this one is just a bit longer' => 'this …onger', - 'short' => 'short' + '.5' => [ + 'this is my string' => 'this …tring', + "here's another one" => "here'…r one", + 'this one is just a bit longer' => 'this …onger', + 'short' => 'short' ], - '1' => [ - 'this is my string' => 'this is my…', - "here's another one" => "here's ano…", - 'this one is just a bit longer' => 'this one i…', - 'short' => 'short' + '1' => [ + 'this is my string' => 'this is my…', + "here's another one" => "here's ano…", + 'this one is just a bit longer' => 'this one i…', + 'short' => 'short' ], ]; foreach ($strs as $pos => $s) @@ -232,18 +232,18 @@ public function test_default_word_wrap_charlim() $string = "Here is a longer string of text that will help us demonstrate the default charlim of this function."; $this->assertEquals(strpos(word_wrap($string), "\n"), 73); } - + // ----------------------------------------------------------------------- - + public function test_excerpt() { $string = $this->_long_string; $result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...'; $this->assertEquals(excerpt($string), $result); } - + // ----------------------------------------------------------------------- - + public function test_excerpt_radius() { $string = $this->_long_string; diff --git a/tests/system/Helpers/URLHelperTest.php b/tests/system/Helpers/URLHelperTest.php index 71b1c5d0eb19..ce17aafdb623 100644 --- a/tests/system/Helpers/URLHelperTest.php +++ b/tests/system/Helpers/URLHelperTest.php @@ -12,370 +12,370 @@ class URLHelperTest extends \CIUnitTestCase { - public function setUp() - { - helper('url'); - Services::reset(); - } + public function setUp() + { + helper('url'); + Services::reset(); + } + + //-------------------------------------------------------------------- + // Test site_url + + public function testSiteURLBasics() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/index.php/', site_url('', null, $config)); + } + + public function testSiteURLHTTPS() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + $_SERVER['HTTPS'] = 'on'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals('https://example.com/index.php/', site_url('', null, $config)); + } - //-------------------------------------------------------------------- - // Test site_url - - public function testSiteURLBasics() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); + public function testSiteURLNoIndex() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = ''; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - $this->assertEquals('http://example.com/index.php/', site_url('', null, $config)); - } - - public function testSiteURLHTTPS() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - $_SERVER['HTTPS'] = 'on'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/', site_url('', null, $config)); + } + + public function testSiteURLDifferentIndex() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'banana.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/banana.php/', site_url('', null, $config)); + } + + public function testSiteURLNoIndexButPath() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; - $this->assertEquals('https://example.com/index.php/', site_url('', null, $config)); - } - - public function testSiteURLNoIndex() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = ''; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = ''; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - $this->assertEquals('http://example.com/', site_url('', null, $config)); - } - - public function testSiteURLDifferentIndex() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'banana.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/banana.php/', site_url('', null, $config)); - } - - public function testSiteURLNoIndexButPath() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = ''; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/abc', site_url('abc', null, $config)); - } - - public function testSiteURLAttachesPath() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/index.php/foo', site_url('foo', null, $config)); - } + Services::injectMock('request', $request); - public function testSiteURLAttachesScheme() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); + $this->assertEquals('http://example.com/abc', site_url('abc', null, $config)); + } - Services::injectMock('request', $request); + public function testSiteURLAttachesPath() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; - $this->assertEquals('ftp://example.com/index.php/foo', site_url('foo', 'ftp', $config)); - } + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - public function testSiteURLExample() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); + Services::injectMock('request', $request); - Services::injectMock('request', $request); + $this->assertEquals('http://example.com/index.php/foo', site_url('foo', null, $config)); + } - $this->assertEquals('http://example.com/index.php/news/local/123', site_url('news/local/123', null, $config)); - } + public function testSiteURLAttachesScheme() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; - public function testSiteURLSegments() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - Services::injectMock('request', $request); + Services::injectMock('request', $request); - $this->assertEquals('http://example.com/index.php/news/local/123', site_url(['news', 'local', '123'], null, $config)); - } + $this->assertEquals('ftp://example.com/index.php/foo', site_url('foo', 'ftp', $config)); + } - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 - */ - public function testSiteURLWithSegments() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/test'; - - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/'; - $request = Services::request($config, false); - $request->uri = new URI('http://example.com/test'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/index.php/', site_url()); - } - - //-------------------------------------------------------------------- - - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 - */ - public function testSiteURLWithSegmentsAgain() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/test/page'; - - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com'; - $request = Services::request($config, false); - $request->uri = new URI('http://example.com/test/page'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/index.php/', site_url()); - $this->assertEquals('http://example.com/index.php/profile', site_url('profile')); - } - - //-------------------------------------------------------------------- - - //-------------------------------------------------------------------- - // Test base_url - - public function testBaseURLBasics() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $this->assertEquals('http://example.com', base_url()); - } - - public function testBaseURLAttachesPath() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $this->assertEquals('http://example.com/foo', base_url('foo')); - } - - public function testBaseURLAttachesPathArray() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $this->assertEquals('http://example.com/foo/bar', base_url(['foo', 'bar'])); - } - - public function testBaseURLAttachesScheme() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $this->assertEquals('https://example.com/foo', base_url('foo', 'https')); - } - - public function testBaseURLHeedsBaseURL() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/public'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/public'); - - Services::injectMock('request', $request); - - $this->assertEquals('http://example.com/public', base_url()); - } - - public function testBaseURLExample() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $this->assertEquals('http://example.com/blog/post/123', base_url('blog/post/123')); - } - - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 - */ - public function testBaseURLWithSegments() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/test'; - - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/'; - $request = Services::request($config, false); - $request->uri = new URI('http://example.com/test'); + public function testSiteURLExample() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; - Services::injectMock('request', $request); + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - $this->assertEquals('http://example.com/', base_url()); - } + Services::injectMock('request', $request); - //-------------------------------------------------------------------- - - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/867 - */ - public function testBaseURLHTTPS() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - $_SERVER['HTTPS'] = 'on'; + $this->assertEquals('http://example.com/index.php/news/local/123', site_url('news/local/123', null, $config)); + } - $this->assertEquals('https://example.com/blog/post/123', base_url('blog/post/123')); - } + public function testSiteURLSegments() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 - */ - public function testBaseURLWithSegmentsAgain() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/test/page'; + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com'; - $request = Services::request($config, false); - $request->uri = new URI('http://example.com/test/page'); + Services::injectMock('request', $request); - Services::injectMock('request', $request); + $this->assertEquals('http://example.com/index.php/news/local/123', site_url(['news', 'local', '123'], null, $config)); + } - $this->assertEquals('http://example.com', base_url()); - $this->assertEquals('http://example.com/profile', base_url('profile')); - } - - //-------------------------------------------------------------------- + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 + */ + public function testSiteURLWithSegments() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/test'; - //-------------------------------------------------------------------- - // Test current_url - - public function testCurrentURLReturnsBasicURL() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/'; + $request = Services::request($config, false); + $request->uri = new URI('http://example.com/test'); - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/public'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/public'); - - Services::injectMock('request', $request); + Services::injectMock('request', $request); - $this->assertEquals('http://example.com/public', current_url()); - } - - public function testCurrentURLReturnsObject() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; + $this->assertEquals('http://example.com/index.php/', site_url()); + } - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/public'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/public'); + //-------------------------------------------------------------------- - Services::injectMock('request', $request); + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 + */ + public function testSiteURLWithSegmentsAgain() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/test/page'; - $url = current_url(true); + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com'; + $request = Services::request($config, false); + $request->uri = new URI('http://example.com/test/page'); - $this->assertInstanceOf(URI::class, $url); - $this->assertEquals('http://example.com/public', (string) $url); - } - - public function testCurrentURLEquivalence() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - // Since we're on a CLI, we must provide our own URI - $config = new App(); - $config->baseURL = 'http://example.com/'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/public'); + Services::injectMock('request', $request); - Services::injectMock('request', $request); + $this->assertEquals('http://example.com/index.php/', site_url()); + $this->assertEquals('http://example.com/index.php/profile', site_url('profile')); + } - $this->assertEquals(base_url(uri_string()), current_url()); - } + //-------------------------------------------------------------------- + + //-------------------------------------------------------------------- + // Test base_url + + public function testBaseURLBasics() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $this->assertEquals('http://example.com', base_url()); + } + + public function testBaseURLAttachesPath() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $this->assertEquals('http://example.com/foo', base_url('foo')); + } + + public function testBaseURLAttachesPathArray() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $this->assertEquals('http://example.com/foo/bar', base_url(['foo', 'bar'])); + } + + public function testBaseURLAttachesScheme() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $this->assertEquals('https://example.com/foo', base_url('foo', 'https')); + } + + public function testBaseURLHeedsBaseURL() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/public'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/public'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/public', base_url()); + } + + public function testBaseURLExample() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $this->assertEquals('http://example.com/blog/post/123', base_url('blog/post/123')); + } + + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 + */ + public function testBaseURLWithSegments() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/test'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/'; + $request = Services::request($config, false); + $request->uri = new URI('http://example.com/test'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/', base_url()); + } + + //-------------------------------------------------------------------- + + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/867 + */ + public function testBaseURLHTTPS() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + $_SERVER['HTTPS'] = 'on'; + + $this->assertEquals('https://example.com/blog/post/123', base_url('blog/post/123')); + } + + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/240 + */ + public function testBaseURLWithSegmentsAgain() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/test/page'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com'; + $request = Services::request($config, false); + $request->uri = new URI('http://example.com/test/page'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com', base_url()); + $this->assertEquals('http://example.com/profile', base_url('profile')); + } + + //-------------------------------------------------------------------- + + //-------------------------------------------------------------------- + // Test current_url + + public function testCurrentURLReturnsBasicURL() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/public'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/public'); + + Services::injectMock('request', $request); + + $this->assertEquals('http://example.com/public', current_url()); + } + + public function testCurrentURLReturnsObject() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/public'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/public'); + + Services::injectMock('request', $request); + + $url = current_url(true); + + $this->assertInstanceOf(URI::class, $url); + $this->assertEquals('http://example.com/public', (string) $url); + } + + public function testCurrentURLEquivalence() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + // Since we're on a CLI, we must provide our own URI + $config = new App(); + $config->baseURL = 'http://example.com/'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/public'); + + Services::injectMock('request', $request); + + $this->assertEquals(base_url(uri_string()), current_url()); + } //-------------------------------------------------------------------- // Test previous_url @@ -401,7 +401,7 @@ public function testPreviousURLUsesSessionFirst() $this->assertEquals($uri2, previous_url()); } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testPreviousURLUsesRefererIfNeeded() { @@ -424,465 +424,465 @@ public function testPreviousURLUsesRefererIfNeeded() } //-------------------------------------------------------------------- - // Test uri_string - - public function testUriString() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $url = current_url(); - $this->assertEquals('/', uri_string()); - } - - public function testUriStringExample() - { - - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/assets/image.jpg'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/assets/image.jpg'); - - Services::injectMock('request', $request); - - $url = current_url(); - $this->assertEquals('/assets/image.jpg', uri_string()); - } - - //-------------------------------------------------------------------- - // Test index_page - - public function testIndexPage() - { - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals('index.php', index_page()); - } - - public function testIndexPageAlt() - { - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'banana.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals('banana.php', index_page($config)); - } - - //-------------------------------------------------------------------- - // Test anchor - - public function anchorNormalPatterns() - { - return [ - 'normal01' => ['http://example.com/index.php', ''], - 'normal02' => ['Bananas', '/', 'Bananas'], - 'normal03' => ['http://example.com/index.php', '/', '', 'fruit="peach"'], - 'normal04' => ['Bananas', '/', 'Bananas', 'fruit=peach'], - 'normal05' => ['http://example.com/index.php', '/', '', ['fruit' => 'peach']], - 'normal06' => ['Bananas', '/', 'Bananas', ['fruit' => 'peach']], - 'normal07' => ['http://example.com/index.php', '/'], - ]; - } - - /** - * @dataProvider anchorNormalPatterns - */ - public function testAnchor($expected = '', $uri = '', $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); - } - - public function anchorNoindexPatterns() - { - return [ - 'noindex01' => ['http://example.com', ''], - 'noindex02' => ['Bananas', '', 'Bananas'], - 'noindex03' => ['http://example.com', '', '', 'fruit="peach"'], - 'noindex04' => ['Bananas', '', 'Bananas', 'fruit=peach'], - 'noindex05' => ['http://example.com', '', '', ['fruit' => 'peach']], - 'noindex06' => ['Bananas', '', 'Bananas', ['fruit' => 'peach']], - 'noindex07' => ['http://example.com', '/'], - ]; - } - - /** - * @dataProvider anchorNoindexPatterns - */ - public function testAnchorNoindex($expected = '', $uri = '', $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = ''; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); - } - - public function anchorSubpagePatterns() - { - return [ - 'subpage01' => ['http://example.com/mush', '/mush'], - 'subpage02' => ['Bananas', '/mush', 'Bananas'], - 'subpage03' => ['http://example.com/mush', '/mush', '', 'fruit="peach"'], - 'subpage04' => ['Bananas', '/mush', 'Bananas', 'fruit=peach'], - 'subpage05' => ['http://example.com/mush', '/mush', '', ['fruit' => 'peach']], - 'subpage06' => ['Bananas', '/mush', 'Bananas', ['fruit' => 'peach']], - ]; - } - - /** - * @dataProvider anchorSubpagePatterns - */ - public function testAnchorTargetted($expected = '', $uri = '', $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = ''; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); - } - - public function anchorExamplePatterns() - { - return [ - 'egpage01' => ['My News', 'news/local/123', 'My News', 'title="News title"'], - 'egpage02' => ['My News', 'news/local/123', 'My News', ['title' => 'The best news!']], - 'egpage03' => ['Click here', '', 'Click here'], - 'egpage04' => ['Click here', '/', 'Click here'], - ]; - } - - /** - * @dataProvider anchorExamplePatterns - */ - public function testAnchorExamples($expected = '', $uri = '', $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); - } - - //-------------------------------------------------------------------- - // Test anchor_popup - - public function anchorPopupPatterns() - { - return [ - 'normal01' => ['http://example.com/index.php', ''], - 'normal02' => ['Bananas', '/', 'Bananas'], - 'normal07' => ['http://example.com/index.php', '/'], - 'normal08' => ['Click Me!', - 'news/local/123', 'Click Me!', [ - 'width' => 800, - 'height' => 600, - 'scrollbars' => 'yes', - 'status' => 'yes', - 'resizable' => 'yes', - 'screenx' => 0, - 'screeny' => 0, - 'window_name' => '_blank' - ]], - 'normal09' => [ - 'Click Me!', - 'news/local/123', - 'Click Me!', - []], - ]; - } - - /** - * @dataProvider anchorPopupPatterns - */ - public function testAnchorPopup($expected = '', $uri = '', $title = '', $attributes = false) - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - $this->assertEquals($expected, anchor_popup($uri, $title, $attributes, $config)); - } - - //-------------------------------------------------------------------- - // Test mailto - - public function mailtoPatterns() - { - return [ - 'page01' => ['Click Here to Contact Me', 'me@my-site.com', 'Click Here to Contact Me'], - 'page02' => ['Contact Me', 'me@my-site.com', 'Contact Me', ['title' => 'Mail me']], - 'page03' => ['me@my-site.com', 'me@my-site.com'], - ]; - } - - /** - * @dataProvider mailtoPatterns - */ - public function testMailto($expected = '', $email, $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals($expected, mailto($email, $title, $attributes)); - } - - //-------------------------------------------------------------------- - // Test safe_mailto - - public function safeMailtoPatterns() - { - return [ - 'page01' => ["", - 'me@my-site.com', 'Click Here to Contact Me'], - 'page02' => ["", - 'me@my-site.com', 'Contact Me', ['title' => 'Mail me']], - 'page03' => ["", - 'me@my-site.com'], - ]; - } - - /** - * @dataProvider safeMailtoPatterns - */ - public function testSafeMailto($expected = '', $email, $title = '', $attributes = '') - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_SERVER['REQUEST_URI'] = '/'; - - $config = new App(); - $config->baseURL = 'http://example.com'; - $config->indexPage = 'index.php'; - $request = Services::request($config); - $request->uri = new URI('http://example.com/'); - - Services::injectMock('request', $request); - - $this->assertEquals($expected, safe_mailto($email, $title, $attributes)); - } - - //-------------------------------------------------------------------- - // Test auto_link - - public function autolinkUrls() - { - return [ - 'test01' => ['www.codeigniter.com test', - 'www.codeigniter.com test'], - 'test02' => ['This is my noreply@codeigniter.com test', - 'This is my noreply@codeigniter.com test'], - 'test03' => ['
www.google.com', - '
www.google.com'], - 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', - 'Download CodeIgniter at www.codeigniter.com. Period test.'], - 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', - 'Download CodeIgniter at www.codeigniter.com, comma test'], - 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], - 'test07' => ['Visit example.com or email foo@bar.com', - 'Visit example.com or email foo@bar.com'], - 'test08' => ['Visit www.example.com or email foo@bar.com', - 'Visit www.example.com or email foo@bar.com'], - ]; - } - - /** - * @dataProvider autolinkUrls - */ - public function testAutoLinkUrl($in, $out) - { - $this->assertEquals($out, auto_link($in, 'url')); - } - - public function autolinkEmails() - { - return [ - 'test01' => ['www.codeigniter.com test', - 'www.codeigniter.com test'], - 'test02' => ['This is my noreply@codeigniter.com test', - "This is my test"], - 'test03' => ['
www.google.com', - '
www.google.com'], - 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', - 'Download CodeIgniter at www.codeigniter.com. Period test.'], - 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', - 'Download CodeIgniter at www.codeigniter.com, comma test'], - 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], - 'test07' => ['Visit example.com or email foo@bar.com', - "Visit example.com or email "], - 'test08' => ['Visit www.example.com or email foo@bar.com', - "Visit www.example.com or email "], - ]; - } - - /** - * @dataProvider autolinkEmails - */ - public function testAutoLinkEmail($in, $out) - { - $this->assertEquals($out, auto_link($in, 'email')); - } - - public function autolinkBoth() - { - return [ - 'test01' => ['www.codeigniter.com test', - 'www.codeigniter.com test'], - 'test02' => ['This is my noreply@codeigniter.com test', - "This is my test"], - 'test03' => ['
www.google.com', - '
www.google.com'], - 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', - 'Download CodeIgniter at www.codeigniter.com. Period test.'], - 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', - 'Download CodeIgniter at www.codeigniter.com, comma test'], - 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], - 'test07' => ['Visit example.com or email foo@bar.com', - "Visit example.com or email "], - 'test08' => ['Visit www.example.com or email foo@bar.com', - "Visit www.example.com or email "], - ]; - } - - /** - * @dataProvider autolinkBoth - */ - public function testAutolinkBoth($in, $out) - { - $this->assertEquals($out, auto_link($in)); - } - - public function autolinkPopup() - { - return [ - 'test01' => ['www.codeigniter.com test', - 'www.codeigniter.com test'], - 'test02' => ['This is my noreply@codeigniter.com test', - 'This is my noreply@codeigniter.com test'], - 'test03' => ['
www.google.com', - '
www.google.com'], - 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', - 'Download CodeIgniter at www.codeigniter.com. Period test.'], - 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', - 'Download CodeIgniter at www.codeigniter.com, comma test'], - 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', - 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], - 'test07' => ['Visit example.com or email foo@bar.com', - 'Visit example.com or email foo@bar.com'], - 'test08' => ['Visit www.example.com or email foo@bar.com', - 'Visit www.example.com or email foo@bar.com'], - ]; - } - - /** - * @dataProvider autolinkPopup - */ - public function testAutoLinkPopup($in, $out) - { - $this->assertEquals($out, auto_link($in, 'url', true)); - } - - //-------------------------------------------------------------------- - // Test prep_url - - public function testPrepUrl() - { - $this->assertEquals('http://codeigniter.com', prep_url('codeigniter.com')); - $this->assertEquals('http://www.codeigniter.com', prep_url('www.codeigniter.com')); - } - - //-------------------------------------------------------------------- - // Test url_title - - public function testUrlTitle() - { - $words = [ - 'foo bar /' => 'foo-bar', - '\ testing 12' => 'testing-12' - ]; - - foreach ($words as $in => $out) - { - $this->assertEquals($out, url_title($in, '-', TRUE)); - } - } - - public function testUrlTitleExtraDashes() - { - $words = [ - '_foo bar_' => 'foo_bar', - '_What\'s wrong with CSS?_' => 'Whats_wrong_with_CSS' - ]; - - foreach ($words as $in => $out) - { - $this->assertEquals($out, url_title($in, '_')); - } - } + // Test uri_string + + public function testUriString() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $url = current_url(); + $this->assertEquals('/', uri_string()); + } + + public function testUriStringExample() + { + + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/assets/image.jpg'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/assets/image.jpg'); + + Services::injectMock('request', $request); + + $url = current_url(); + $this->assertEquals('/assets/image.jpg', uri_string()); + } + + //-------------------------------------------------------------------- + // Test index_page + + public function testIndexPage() + { + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals('index.php', index_page()); + } + + public function testIndexPageAlt() + { + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'banana.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals('banana.php', index_page($config)); + } + + //-------------------------------------------------------------------- + // Test anchor + + public function anchorNormalPatterns() + { + return [ + 'normal01' => ['http://example.com/index.php', ''], + 'normal02' => ['Bananas', '/', 'Bananas'], + 'normal03' => ['http://example.com/index.php', '/', '', 'fruit="peach"'], + 'normal04' => ['Bananas', '/', 'Bananas', 'fruit=peach'], + 'normal05' => ['http://example.com/index.php', '/', '', ['fruit' => 'peach']], + 'normal06' => ['Bananas', '/', 'Bananas', ['fruit' => 'peach']], + 'normal07' => ['http://example.com/index.php', '/'], + ]; + } + + /** + * @dataProvider anchorNormalPatterns + */ + public function testAnchor($expected = '', $uri = '', $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); + } + + public function anchorNoindexPatterns() + { + return [ + 'noindex01' => ['http://example.com', ''], + 'noindex02' => ['Bananas', '', 'Bananas'], + 'noindex03' => ['http://example.com', '', '', 'fruit="peach"'], + 'noindex04' => ['Bananas', '', 'Bananas', 'fruit=peach'], + 'noindex05' => ['http://example.com', '', '', ['fruit' => 'peach']], + 'noindex06' => ['Bananas', '', 'Bananas', ['fruit' => 'peach']], + 'noindex07' => ['http://example.com', '/'], + ]; + } + + /** + * @dataProvider anchorNoindexPatterns + */ + public function testAnchorNoindex($expected = '', $uri = '', $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = ''; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); + } + + public function anchorSubpagePatterns() + { + return [ + 'subpage01' => ['http://example.com/mush', '/mush'], + 'subpage02' => ['Bananas', '/mush', 'Bananas'], + 'subpage03' => ['http://example.com/mush', '/mush', '', 'fruit="peach"'], + 'subpage04' => ['Bananas', '/mush', 'Bananas', 'fruit=peach'], + 'subpage05' => ['http://example.com/mush', '/mush', '', ['fruit' => 'peach']], + 'subpage06' => ['Bananas', '/mush', 'Bananas', ['fruit' => 'peach']], + ]; + } + + /** + * @dataProvider anchorSubpagePatterns + */ + public function testAnchorTargetted($expected = '', $uri = '', $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = ''; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); + } + + public function anchorExamplePatterns() + { + return [ + 'egpage01' => ['My News', 'news/local/123', 'My News', 'title="News title"'], + 'egpage02' => ['My News', 'news/local/123', 'My News', ['title' => 'The best news!']], + 'egpage03' => ['Click here', '', 'Click here'], + 'egpage04' => ['Click here', '/', 'Click here'], + ]; + } + + /** + * @dataProvider anchorExamplePatterns + */ + public function testAnchorExamples($expected = '', $uri = '', $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + $this->assertEquals($expected, anchor($uri, $title, $attributes, $config)); + } + + //-------------------------------------------------------------------- + // Test anchor_popup + + public function anchorPopupPatterns() + { + return [ + 'normal01' => ['http://example.com/index.php', ''], + 'normal02' => ['Bananas', '/', 'Bananas'], + 'normal07' => ['http://example.com/index.php', '/'], + 'normal08' => ['Click Me!', + 'news/local/123', 'Click Me!', [ + 'width' => 800, + 'height' => 600, + 'scrollbars' => 'yes', + 'status' => 'yes', + 'resizable' => 'yes', + 'screenx' => 0, + 'screeny' => 0, + 'window_name' => '_blank' + ]], + 'normal09' => [ + 'Click Me!', + 'news/local/123', + 'Click Me!', + []], + ]; + } + + /** + * @dataProvider anchorPopupPatterns + */ + public function testAnchorPopup($expected = '', $uri = '', $title = '', $attributes = false) + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + $this->assertEquals($expected, anchor_popup($uri, $title, $attributes, $config)); + } + + //-------------------------------------------------------------------- + // Test mailto + + public function mailtoPatterns() + { + return [ + 'page01' => ['Click Here to Contact Me', 'me@my-site.com', 'Click Here to Contact Me'], + 'page02' => ['Contact Me', 'me@my-site.com', 'Contact Me', ['title' => 'Mail me']], + 'page03' => ['me@my-site.com', 'me@my-site.com'], + ]; + } + + /** + * @dataProvider mailtoPatterns + */ + public function testMailto($expected = '', $email, $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals($expected, mailto($email, $title, $attributes)); + } + + //-------------------------------------------------------------------- + // Test safe_mailto + + public function safeMailtoPatterns() + { + return [ + 'page01' => ["", + 'me@my-site.com', 'Click Here to Contact Me'], + 'page02' => ["", + 'me@my-site.com', 'Contact Me', ['title' => 'Mail me']], + 'page03' => ["", + 'me@my-site.com'], + ]; + } + + /** + * @dataProvider safeMailtoPatterns + */ + public function testSafeMailto($expected = '', $email, $title = '', $attributes = '') + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_SERVER['REQUEST_URI'] = '/'; + + $config = new App(); + $config->baseURL = 'http://example.com'; + $config->indexPage = 'index.php'; + $request = Services::request($config); + $request->uri = new URI('http://example.com/'); + + Services::injectMock('request', $request); + + $this->assertEquals($expected, safe_mailto($email, $title, $attributes)); + } + + //-------------------------------------------------------------------- + // Test auto_link + + public function autolinkUrls() + { + return [ + 'test01' => ['www.codeigniter.com test', + 'www.codeigniter.com test'], + 'test02' => ['This is my noreply@codeigniter.com test', + 'This is my noreply@codeigniter.com test'], + 'test03' => ['
www.google.com', + '
www.google.com'], + 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', + 'Download CodeIgniter at www.codeigniter.com. Period test.'], + 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', + 'Download CodeIgniter at www.codeigniter.com, comma test'], + 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], + 'test07' => ['Visit example.com or email foo@bar.com', + 'Visit example.com or email foo@bar.com'], + 'test08' => ['Visit www.example.com or email foo@bar.com', + 'Visit www.example.com or email foo@bar.com'], + ]; + } + + /** + * @dataProvider autolinkUrls + */ + public function testAutoLinkUrl($in, $out) + { + $this->assertEquals($out, auto_link($in, 'url')); + } + + public function autolinkEmails() + { + return [ + 'test01' => ['www.codeigniter.com test', + 'www.codeigniter.com test'], + 'test02' => ['This is my noreply@codeigniter.com test', + "This is my test"], + 'test03' => ['
www.google.com', + '
www.google.com'], + 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', + 'Download CodeIgniter at www.codeigniter.com. Period test.'], + 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', + 'Download CodeIgniter at www.codeigniter.com, comma test'], + 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], + 'test07' => ['Visit example.com or email foo@bar.com', + "Visit example.com or email "], + 'test08' => ['Visit www.example.com or email foo@bar.com', + "Visit www.example.com or email "], + ]; + } + + /** + * @dataProvider autolinkEmails + */ + public function testAutoLinkEmail($in, $out) + { + $this->assertEquals($out, auto_link($in, 'email')); + } + + public function autolinkBoth() + { + return [ + 'test01' => ['www.codeigniter.com test', + 'www.codeigniter.com test'], + 'test02' => ['This is my noreply@codeigniter.com test', + "This is my test"], + 'test03' => ['
www.google.com', + '
www.google.com'], + 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', + 'Download CodeIgniter at www.codeigniter.com. Period test.'], + 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', + 'Download CodeIgniter at www.codeigniter.com, comma test'], + 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], + 'test07' => ['Visit example.com or email foo@bar.com', + "Visit example.com or email "], + 'test08' => ['Visit www.example.com or email foo@bar.com', + "Visit www.example.com or email "], + ]; + } + + /** + * @dataProvider autolinkBoth + */ + public function testAutolinkBoth($in, $out) + { + $this->assertEquals($out, auto_link($in)); + } + + public function autolinkPopup() + { + return [ + 'test01' => ['www.codeigniter.com test', + 'www.codeigniter.com test'], + 'test02' => ['This is my noreply@codeigniter.com test', + 'This is my noreply@codeigniter.com test'], + 'test03' => ['
www.google.com', + '
www.google.com'], + 'test04' => ['Download CodeIgniter at www.codeigniter.com. Period test.', + 'Download CodeIgniter at www.codeigniter.com. Period test.'], + 'test05' => ['Download CodeIgniter at www.codeigniter.com, comma test', + 'Download CodeIgniter at www.codeigniter.com, comma test'], + 'test06' => ['This one: ://codeigniter.com must not break this one: http://codeigniter.com', + 'This one: ://codeigniter.com must not break this one: http://codeigniter.com'], + 'test07' => ['Visit example.com or email foo@bar.com', + 'Visit example.com or email foo@bar.com'], + 'test08' => ['Visit www.example.com or email foo@bar.com', + 'Visit www.example.com or email foo@bar.com'], + ]; + } + + /** + * @dataProvider autolinkPopup + */ + public function testAutoLinkPopup($in, $out) + { + $this->assertEquals($out, auto_link($in, 'url', true)); + } + + //-------------------------------------------------------------------- + // Test prep_url + + public function testPrepUrl() + { + $this->assertEquals('http://codeigniter.com', prep_url('codeigniter.com')); + $this->assertEquals('http://www.codeigniter.com', prep_url('www.codeigniter.com')); + } + + //-------------------------------------------------------------------- + // Test url_title + + public function testUrlTitle() + { + $words = [ + 'foo bar /' => 'foo-bar', + '\ testing 12' => 'testing-12' + ]; + + foreach ($words as $in => $out) + { + $this->assertEquals($out, url_title($in, '-', TRUE)); + } + } + + public function testUrlTitleExtraDashes() + { + $words = [ + '_foo bar_' => 'foo_bar', + '_What\'s wrong with CSS?_' => 'Whats_wrong_with_CSS' + ]; + + foreach ($words as $in => $out) + { + $this->assertEquals($out, url_title($in, '_')); + } + } } diff --git a/tests/system/I18n/TimeDifferenceTest.php b/tests/system/I18n/TimeDifferenceTest.php index d66aff1d018c..20001612558a 100644 --- a/tests/system/I18n/TimeDifferenceTest.php +++ b/tests/system/I18n/TimeDifferenceTest.php @@ -2,182 +2,182 @@ class TimeDifferenceTest extends \CIUnitTestCase { - public function setUp() - { - parent::setUp(); - - helper('date'); - \Locale::setDefault('America/Chicago'); - } - - public function testDifferenceBasics() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $test = Time::parse('March 10, 2010', 'America/Chicago'); - - $diff = $current->getTimestamp() - $test->getTimestamp(); + public function setUp() + { + parent::setUp(); + + helper('date'); + \Locale::setDefault('America/Chicago'); + } + + public function testDifferenceBasics() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $test = Time::parse('March 10, 2010', 'America/Chicago'); + + $diff = $current->getTimestamp() - $test->getTimestamp(); - $obj = $current->difference($test); - - $this->assertEquals(-7, $obj->getYears()); - $this->assertEquals(-84, $obj->getMonths()); - $this->assertEquals(-365, $obj->getWeeks()); - $this->assertEquals(-2557, $obj->getDays()); - $this->assertEquals(-61368, $obj->getHours()); - $this->assertEquals(-3682080, $obj->getMinutes()); - $this->assertEquals(-220924800, $obj->getSeconds()); - - $this->assertEquals($diff / YEAR, $obj->getYears(true)); - $this->assertEquals($diff / MONTH, $obj->getMonths(true)); - $this->assertEquals($diff / WEEK, $obj->getWeeks(true)); - $this->assertEquals($diff / DAY, $obj->getDays(true)); - $this->assertEquals($diff / HOUR, $obj->getHours(true)); - $this->assertEquals($diff / MINUTE, $obj->getMinutes(true)); - $this->assertEquals($diff / SECOND, $obj->getSeconds(true)); - } - - public function testHumanizeYearsSingle() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - - $diff = $current->difference('March 9, 2016 12:00:00', 'America/Chicago'); - - $this->assertEquals('1 year ago', $diff->humanize('en')); - } - - public function testHumanizeYearsPlural() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 9, 2014 12:00:00', 'America/Chicago'); - - $this->assertEquals('3 years ago', $diff->humanize('en')); - } - - public function testHumanizeYearsForward() - { - $current = Time::parse('January 1, 2017', 'America/Chicago'); - $diff = $current->difference('January 1, 2018 12:00:00', 'America/Chicago'); - - $this->assertEquals('in 1 year', $diff->humanize('en')); - } - - public function testHumanizeMonthsSingle() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('February 9, 2017', 'America/Chicago'); - - $this->assertEquals('1 month ago', $diff->humanize('en')); - } - - public function testHumanizeMonthsPlural() - { - $current = Time::parse('March 1, 2017', 'America/Chicago'); - $diff = $current->difference('January 1, 2017', 'America/Chicago'); - - $this->assertEquals('2 months ago', $diff->humanize('en')); - } - - public function testHumanizeMonthsForward() - { - $current = Time::parse('March 1, 2017', 'America/Chicago'); - $diff = $current->difference('May 1, 2017', 'America/Chicago'); - - $this->assertEquals('in 1 month', $diff->humanize('en')); - } - - public function testHumanizeDaysSingle() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 9, 2017', 'America/Chicago'); - - $this->assertEquals('1 day ago', $diff->humanize('en')); - } - - public function testHumanizeDaysPlural() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 8, 2017', 'America/Chicago'); - - $this->assertEquals('2 days ago', $diff->humanize('en')); - } - - public function testHumanizeDaysForward() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 11, 2017', 'America/Chicago'); + $obj = $current->difference($test); + + $this->assertEquals(-7, $obj->getYears()); + $this->assertEquals(-84, $obj->getMonths()); + $this->assertEquals(-365, $obj->getWeeks()); + $this->assertEquals(-2557, $obj->getDays()); + $this->assertEquals(-61368, $obj->getHours()); + $this->assertEquals(-3682080, $obj->getMinutes()); + $this->assertEquals(-220924800, $obj->getSeconds()); + + $this->assertEquals($diff / YEAR, $obj->getYears(true)); + $this->assertEquals($diff / MONTH, $obj->getMonths(true)); + $this->assertEquals($diff / WEEK, $obj->getWeeks(true)); + $this->assertEquals($diff / DAY, $obj->getDays(true)); + $this->assertEquals($diff / HOUR, $obj->getHours(true)); + $this->assertEquals($diff / MINUTE, $obj->getMinutes(true)); + $this->assertEquals($diff / SECOND, $obj->getSeconds(true)); + } + + public function testHumanizeYearsSingle() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + + $diff = $current->difference('March 9, 2016 12:00:00', 'America/Chicago'); + + $this->assertEquals('1 year ago', $diff->humanize('en')); + } + + public function testHumanizeYearsPlural() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 9, 2014 12:00:00', 'America/Chicago'); + + $this->assertEquals('3 years ago', $diff->humanize('en')); + } + + public function testHumanizeYearsForward() + { + $current = Time::parse('January 1, 2017', 'America/Chicago'); + $diff = $current->difference('January 1, 2018 12:00:00', 'America/Chicago'); + + $this->assertEquals('in 1 year', $diff->humanize('en')); + } + + public function testHumanizeMonthsSingle() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('February 9, 2017', 'America/Chicago'); + + $this->assertEquals('1 month ago', $diff->humanize('en')); + } + + public function testHumanizeMonthsPlural() + { + $current = Time::parse('March 1, 2017', 'America/Chicago'); + $diff = $current->difference('January 1, 2017', 'America/Chicago'); + + $this->assertEquals('2 months ago', $diff->humanize('en')); + } + + public function testHumanizeMonthsForward() + { + $current = Time::parse('March 1, 2017', 'America/Chicago'); + $diff = $current->difference('May 1, 2017', 'America/Chicago'); + + $this->assertEquals('in 1 month', $diff->humanize('en')); + } + + public function testHumanizeDaysSingle() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 9, 2017', 'America/Chicago'); + + $this->assertEquals('1 day ago', $diff->humanize('en')); + } + + public function testHumanizeDaysPlural() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 8, 2017', 'America/Chicago'); + + $this->assertEquals('2 days ago', $diff->humanize('en')); + } + + public function testHumanizeDaysForward() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 11, 2017', 'America/Chicago'); - $this->assertEquals('in 1 day', $diff->humanize('en')); - } - - public function testHumanizeHoursSingle() - { - $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 11:00', 'America/Chicago'); + $this->assertEquals('in 1 day', $diff->humanize('en')); + } + + public function testHumanizeHoursSingle() + { + $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 11:00', 'America/Chicago'); - $this->assertEquals('1 hour ago', $diff->humanize('en')); - } - - public function testHumanizeHoursPlural() - { - $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 10:00', 'America/Chicago'); - - $this->assertEquals('2 hours ago', $diff->humanize('en')); - } - - public function testHumanizeHoursForward() - { - $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 13:00', 'America/Chicago'); + $this->assertEquals('1 hour ago', $diff->humanize('en')); + } + + public function testHumanizeHoursPlural() + { + $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 10:00', 'America/Chicago'); + + $this->assertEquals('2 hours ago', $diff->humanize('en')); + } + + public function testHumanizeHoursForward() + { + $current = Time::parse('March 10, 2017 12:00', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 13:00', 'America/Chicago'); - $this->assertEquals('in 1 hour', $diff->humanize('en')); - } + $this->assertEquals('in 1 hour', $diff->humanize('en')); + } - public function testHumanizeMinutesSingle() - { - $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 12:29', 'America/Chicago'); + public function testHumanizeMinutesSingle() + { + $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 12:29', 'America/Chicago'); - $this->assertEquals('1 minute ago', $diff->humanize('en')); - } + $this->assertEquals('1 minute ago', $diff->humanize('en')); + } - public function testHumanizeMinutesPlural() - { - $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 12:28', 'America/Chicago'); + public function testHumanizeMinutesPlural() + { + $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 12:28', 'America/Chicago'); - $this->assertEquals('2 minutes ago', $diff->humanize('en')); - } + $this->assertEquals('2 minutes ago', $diff->humanize('en')); + } - public function testHumanizeMinutesForward() - { - $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); - $diff = $current->difference('March 10, 2017 12:31', 'America/Chicago'); + public function testHumanizeMinutesForward() + { + $current = Time::parse('March 10, 2017 12:30', 'America/Chicago'); + $diff = $current->difference('March 10, 2017 12:31', 'America/Chicago'); - $this->assertEquals('in 1 minute', $diff->humanize('en')); - } + $this->assertEquals('in 1 minute', $diff->humanize('en')); + } - public function testHumanizeWeeksSingle() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 2, 2017', 'America/Chicago'); + public function testHumanizeWeeksSingle() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 2, 2017', 'America/Chicago'); - $this->assertEquals('1 week ago', $diff->humanize('en')); - } + $this->assertEquals('1 week ago', $diff->humanize('en')); + } - public function testHumanizeWeeksPlural() - { - $current = Time::parse('March 30, 2017', 'America/Chicago'); - $diff = $current->difference('March 15, 2017', 'America/Chicago'); + public function testHumanizeWeeksPlural() + { + $current = Time::parse('March 30, 2017', 'America/Chicago'); + $diff = $current->difference('March 15, 2017', 'America/Chicago'); - $this->assertEquals('2 weeks ago', $diff->humanize('en')); - } + $this->assertEquals('2 weeks ago', $diff->humanize('en')); + } - public function testHumanizeWeeksForward() - { - $current = Time::parse('March 10, 2017', 'America/Chicago'); - $diff = $current->difference('March 18, 2017', 'America/Chicago'); + public function testHumanizeWeeksForward() + { + $current = Time::parse('March 10, 2017', 'America/Chicago'); + $diff = $current->difference('March 18, 2017', 'America/Chicago'); - $this->assertEquals('in 1 week', $diff->humanize('en')); - } + $this->assertEquals('in 1 week', $diff->humanize('en')); + } } diff --git a/tests/system/I18n/TimeTest.php b/tests/system/I18n/TimeTest.php index 8470b5d2d1b8..a390f589a499 100644 --- a/tests/system/I18n/TimeTest.php +++ b/tests/system/I18n/TimeTest.php @@ -4,923 +4,923 @@ class TimeTest extends \CIUnitTestCase { - public function setUp() - { - parent::setUp(); - - helper('date'); - \Locale::setDefault('America/Chicago'); - } - - public function testNewTimeNow() - { - $time = new Time(null, 'America/Chicago'); - - $formatter = new IntlDateFormatter( - 'en_US', - IntlDateFormatter::SHORT, - IntlDateFormatter::SHORT, - 'America/Chicago', // Default for CodeIgniter - IntlDateFormatter::GREGORIAN, - 'yyyy-MM-dd HH:mm:ss' - ); - - $this->assertEquals($formatter->format(strtotime('now')), (string)$time); - } - - public function testTimeWithTimezone() - { - $time = new Time('now', 'Europe/London'); - - $formatter = new IntlDateFormatter( - 'en_US', - IntlDateFormatter::SHORT, - IntlDateFormatter::SHORT, - 'Europe/London', // Default for CodeIgniter - IntlDateFormatter::GREGORIAN, - 'yyyy-MM-dd HH:mm:ss' - ); - - $this->assertEquals($formatter->format(strtotime('now')), (string)$time); - } - - public function testTimeWithTimezoneAndLocale() - { - $time = new Time('now', 'Europe/London', 'fr_FR'); - - $formatter = new IntlDateFormatter( - 'fr_FR', - IntlDateFormatter::SHORT, - IntlDateFormatter::SHORT, - 'Europe/London', // Default for CodeIgniter - IntlDateFormatter::GREGORIAN, - 'yyyy-MM-dd HH:mm:ss' - ); - - $this->assertEquals($formatter->format(strtotime('now')), (string)$time); - } - - public function testTimeWithDateTimeZone() - { - $time = new Time('now', new \DateTimeZone('Europe/London'), 'fr_FR'); - - $formatter = new IntlDateFormatter( - 'fr_FR', - IntlDateFormatter::SHORT, - IntlDateFormatter::SHORT, - 'Europe/London', - IntlDateFormatter::GREGORIAN, - 'yyyy-MM-dd HH:mm:ss' - ); - - $this->assertEquals($formatter->format(strtotime('now')), (string)$time); - } - - public function testToDateTime() - { - $time = new Time(); - - $obj = $time->toDateTime(); - - $this->assertInstanceOf(\DateTime::class, $obj); - } - - public function testNow() - { - $time = Time::now(); - $time1 = new \DateTime(); + public function setUp() + { + parent::setUp(); + + helper('date'); + \Locale::setDefault('America/Chicago'); + } + + public function testNewTimeNow() + { + $time = new Time(null, 'America/Chicago'); + + $formatter = new IntlDateFormatter( + 'en_US', + IntlDateFormatter::SHORT, + IntlDateFormatter::SHORT, + 'America/Chicago', // Default for CodeIgniter + IntlDateFormatter::GREGORIAN, + 'yyyy-MM-dd HH:mm:ss' + ); + + $this->assertEquals($formatter->format(strtotime('now')), (string)$time); + } + + public function testTimeWithTimezone() + { + $time = new Time('now', 'Europe/London'); + + $formatter = new IntlDateFormatter( + 'en_US', + IntlDateFormatter::SHORT, + IntlDateFormatter::SHORT, + 'Europe/London', // Default for CodeIgniter + IntlDateFormatter::GREGORIAN, + 'yyyy-MM-dd HH:mm:ss' + ); + + $this->assertEquals($formatter->format(strtotime('now')), (string)$time); + } + + public function testTimeWithTimezoneAndLocale() + { + $time = new Time('now', 'Europe/London', 'fr_FR'); + + $formatter = new IntlDateFormatter( + 'fr_FR', + IntlDateFormatter::SHORT, + IntlDateFormatter::SHORT, + 'Europe/London', // Default for CodeIgniter + IntlDateFormatter::GREGORIAN, + 'yyyy-MM-dd HH:mm:ss' + ); + + $this->assertEquals($formatter->format(strtotime('now')), (string)$time); + } + + public function testTimeWithDateTimeZone() + { + $time = new Time('now', new \DateTimeZone('Europe/London'), 'fr_FR'); + + $formatter = new IntlDateFormatter( + 'fr_FR', + IntlDateFormatter::SHORT, + IntlDateFormatter::SHORT, + 'Europe/London', + IntlDateFormatter::GREGORIAN, + 'yyyy-MM-dd HH:mm:ss' + ); + + $this->assertEquals($formatter->format(strtotime('now')), (string)$time); + } + + public function testToDateTime() + { + $time = new Time(); + + $obj = $time->toDateTime(); + + $this->assertInstanceOf(\DateTime::class, $obj); + } + + public function testNow() + { + $time = Time::now(); + $time1 = new \DateTime(); - $this->assertInstanceOf(Time::class, $time); - $this->assertEquals($time->getTimestamp(), $time1->getTimestamp()); - } + $this->assertInstanceOf(Time::class, $time); + $this->assertEquals($time->getTimestamp(), $time1->getTimestamp()); + } - public function testParse() - { - $time = Time::parse('next Tuesday', 'America/Chicago'); - $time1 = new \DateTime('now', new \DateTimeZone('America/Chicago')); - $time1->modify('next Tuesday'); - - $this->assertEquals($time->getTimestamp(), $time1->getTimestamp()); - } + public function testParse() + { + $time = Time::parse('next Tuesday', 'America/Chicago'); + $time1 = new \DateTime('now', new \DateTimeZone('America/Chicago')); + $time1->modify('next Tuesday'); + + $this->assertEquals($time->getTimestamp(), $time1->getTimestamp()); + } - public function testToDateTimeString() - { - $time = Time::parse('2017-01-12 00:00', 'America/Chicago'); + public function testToDateTimeString() + { + $time = Time::parse('2017-01-12 00:00', 'America/Chicago'); - $this->assertEquals('2017-01-12 00:00:00', (string)$time); - $this->assertEquals('2017-01-12 00:00:00', $time->toDateTimeString()); - } + $this->assertEquals('2017-01-12 00:00:00', (string)$time); + $this->assertEquals('2017-01-12 00:00:00', $time->toDateTimeString()); + } - public function testToDateTimeStringWithTimeZone() - { - $time = Time::parse('2017-01-12 00:00', 'Europe/London'); + public function testToDateTimeStringWithTimeZone() + { + $time = Time::parse('2017-01-12 00:00', 'Europe/London'); - $expects = new \DateTime('2017-01-12', new \DateTimeZone('Europe/London')); + $expects = new \DateTime('2017-01-12', new \DateTimeZone('Europe/London')); - $this->assertEquals($expects->format('Y-m-d H:i:s'), $time->toDateTimeString()); - } + $this->assertEquals($expects->format('Y-m-d H:i:s'), $time->toDateTimeString()); + } - public function testToday() - { - $time = Time::today(); + public function testToday() + { + $time = Time::today(); - $this->assertEquals(date('Y-m-d 00:00:00'), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00'), $time->toDateTimeString()); + } - public function testTodayLocalized() - { - $time = Time::today('Europe/London'); + public function testTodayLocalized() + { + $time = Time::today('Europe/London'); - $this->assertEquals(date('Y-m-d 00:00:00'), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00'), $time->toDateTimeString()); + } - public function testYesterday() - { - $time = Time::yesterday(); + public function testYesterday() + { + $time = Time::yesterday(); - $this->assertEquals(date('Y-m-d 00:00:00', strtotime('-1 day')), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00', strtotime('-1 day')), $time->toDateTimeString()); + } - public function testTomorrow() - { - $time = Time::tomorrow(); + public function testTomorrow() + { + $time = Time::tomorrow(); - $this->assertEquals(date('Y-m-d 00:00:00', strtotime('+1 day')), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00', strtotime('+1 day')), $time->toDateTimeString()); + } - public function testCreateFromDate() - { - $time = Time::createFromDate(2017, 03, 05, 'America/Chicago'); + public function testCreateFromDate() + { + $time = Time::createFromDate(2017, 03, 05, 'America/Chicago'); - $this->assertEquals(date('Y-m-d 00:00:00', strtotime('2017-03-05 00:00:00')), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00', strtotime('2017-03-05 00:00:00')), $time->toDateTimeString()); + } - public function testCreateFromDateLocalized() - { - $time = Time::createFromDate(2017, 03, 05, 'Europe/London'); + public function testCreateFromDateLocalized() + { + $time = Time::createFromDate(2017, 03, 05, 'Europe/London'); - $this->assertEquals(date('Y-m-d 00:00:00', strtotime('2017-03-05 00:00:00')), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 00:00:00', strtotime('2017-03-05 00:00:00')), $time->toDateTimeString()); + } - public function testCreateFromTime() - { - $time = Time::createFromTime(10, 03, 05, 'America/Chicago'); + public function testCreateFromTime() + { + $time = Time::createFromTime(10, 03, 05, 'America/Chicago'); - $this->assertEquals(date('Y-m-d 10:03:05'), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 10:03:05'), $time->toDateTimeString()); + } - public function testCreateFromTimeEvening() - { - $time = Time::createFromTime(20, 03, 05, 'America/Chicago'); + public function testCreateFromTimeEvening() + { + $time = Time::createFromTime(20, 03, 05, 'America/Chicago'); - $this->assertEquals(date('Y-m-d 20:03:05'), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 20:03:05'), $time->toDateTimeString()); + } - public function testCreateFromTimeLocalized() - { - $time = Time::createFromTime(10, 03, 05, 'Europe/London'); + public function testCreateFromTimeLocalized() + { + $time = Time::createFromTime(10, 03, 05, 'Europe/London'); - $this->assertEquals(date('Y-m-d 10:03:05'), $time->toDateTimeString()); - } + $this->assertEquals(date('Y-m-d 10:03:05'), $time->toDateTimeString()); + } - public function testCreateFromFormat() - { - $now = new \DateTime('now'); + public function testCreateFromFormat() + { + $now = new \DateTime('now'); - Time::setTestNow($now); - $time = Time::createFromFormat('F j, Y', 'January 15, 2017', 'America/Chicago'); + Time::setTestNow($now); + $time = Time::createFromFormat('F j, Y', 'January 15, 2017', 'America/Chicago'); - $this->assertEquals(date('2017-01-15 H:i:s', $now->getTimestamp()), $time->toDateTimeString()); - Time::setTestNow(); - } + $this->assertEquals(date('2017-01-15 H:i:s', $now->getTimestamp()), $time->toDateTimeString()); + Time::setTestNow(); + } - public function testCreateFromFormatWithTimezoneString() - { - $time = Time::createFromFormat('F j, Y', 'January 15, 2017', 'Europe/London'); + public function testCreateFromFormatWithTimezoneString() + { + $time = Time::createFromFormat('F j, Y', 'January 15, 2017', 'Europe/London'); - $this->assertEquals(date('2017-01-15 H:i:s'), $time->toDateTimeString()); - } + $this->assertEquals(date('2017-01-15 H:i:s'), $time->toDateTimeString()); + } - public function testCreateFromFormatWithTimezoneObject() - { - $tz = new \DateTimeZone('Europe/London'); + public function testCreateFromFormatWithTimezoneObject() + { + $tz = new \DateTimeZone('Europe/London'); - $time = Time::createFromFormat('F j, Y', 'January 15, 2017', $tz); + $time = Time::createFromFormat('F j, Y', 'January 15, 2017', $tz); - $this->assertEquals(date('2017-01-15 H:i:s'), $time->toDateTimeString()); - } + $this->assertEquals(date('2017-01-15 H:i:s'), $time->toDateTimeString()); + } - public function testCreateFromTimestamp() - { - $time = Time::createFromTimestamp(strtotime('2017-03-18 midnight')); + public function testCreateFromTimestamp() + { + $time = Time::createFromTimestamp(strtotime('2017-03-18 midnight')); - $this->assertEquals(date('2017-03-18 00:00:00'), $time->toDateTimeString()); - } + $this->assertEquals(date('2017-03-18 00:00:00'), $time->toDateTimeString()); + } - public function testTestNow() - { - $this->assertFalse(Time::hasTestNow()); - $this->assertEquals(date('Y-m-d H:i:s', time()), Time::now()->toDateTimeString()); + public function testTestNow() + { + $this->assertFalse(Time::hasTestNow()); + $this->assertEquals(date('Y-m-d H:i:s', time()), Time::now()->toDateTimeString()); - $t = new Time('2000-01-02'); - Time::setTestNow($t); + $t = new Time('2000-01-02'); + Time::setTestNow($t); - $this->assertTrue(Time::hasTestNow()); - $this->assertEquals('2000-01-02 00:00:00', Time::now()->toDateTimeString()); + $this->assertTrue(Time::hasTestNow()); + $this->assertEquals('2000-01-02 00:00:00', Time::now()->toDateTimeString()); - Time::setTestNow(); - $this->assertEquals(date('Y-m-d H:i:s', time()), Time::now()->toDateTimeString()); - } + Time::setTestNow(); + $this->assertEquals(date('Y-m-d H:i:s', time()), Time::now()->toDateTimeString()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetYear() - { - $time = Time::parse('January 1, 2016'); + public function testGetYear() + { + $time = Time::parse('January 1, 2016'); - $this->assertEquals(2016, $time->year); - } + $this->assertEquals(2016, $time->year); + } - public function testGetMonth() - { - $time = Time::parse('August 1, 2016'); + public function testGetMonth() + { + $time = Time::parse('August 1, 2016'); - $this->assertEquals(8, $time->month); - } + $this->assertEquals(8, $time->month); + } - public function testGetDay() - { - $time = Time::parse('August 12, 2016'); + public function testGetDay() + { + $time = Time::parse('August 12, 2016'); - $this->assertEquals(12, $time->day); - } + $this->assertEquals(12, $time->day); + } - public function testGetHour() - { - $time = Time::parse('August 12, 2016 4:15pm'); + public function testGetHour() + { + $time = Time::parse('August 12, 2016 4:15pm'); - $this->assertEquals(16, $time->hour); - } + $this->assertEquals(16, $time->hour); + } - public function testGetMinute() - { - $time = Time::parse('August 12, 2016 4:15pm'); + public function testGetMinute() + { + $time = Time::parse('August 12, 2016 4:15pm'); - $this->assertEquals(15, $time->minute); - } + $this->assertEquals(15, $time->minute); + } - public function testGetSecond() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); + public function testGetSecond() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); - $this->assertEquals(23, $time->second); - } + $this->assertEquals(23, $time->second); + } - public function testGetDayOfWeek() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); + public function testGetDayOfWeek() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); - $this->assertEquals(6, $time->dayOfWeek); - } + $this->assertEquals(6, $time->dayOfWeek); + } - public function testGetDayOfYear() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); + public function testGetDayOfYear() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); - $this->assertEquals(225, $time->dayOfYear); - } + $this->assertEquals(225, $time->dayOfYear); + } - public function testGetWeekOfMonth() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); + public function testGetWeekOfMonth() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); - $this->assertEquals(2, $time->weekOfMonth); - } + $this->assertEquals(2, $time->weekOfMonth); + } - public function testGetWeekOfYear() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); + public function testGetWeekOfYear() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); - $this->assertEquals(33, $time->weekOfYear); - } + $this->assertEquals(33, $time->weekOfYear); + } - public function testGetTimestamp() - { - $time = Time::parse('August 12, 2016 4:15:23pm'); - $expected = strtotime('August 12, 2016 4:15:23pm'); + public function testGetTimestamp() + { + $time = Time::parse('August 12, 2016 4:15:23pm'); + $expected = strtotime('August 12, 2016 4:15:23pm'); - $this->assertEquals($expected, $time->timestamp); - } + $this->assertEquals($expected, $time->timestamp); + } - public function testGetAge() - { - $time = Time::parse('5 years ago'); - - $this->assertEquals(5, $time->age); - } - - public function testGetQuarter() - { - $time = Time::parse('April 15, 2015'); - - $this->assertEquals(2, $time->quarter); - } - - public function testGetDST() - { - $this->assertFalse(Time::createFromDate(2012, 1, 1)->dst); - $this->assertTrue(Time::createFromDate(2012, 9, 1)->dst); - } - - public function testGetLocal() - { - $this->assertTrue(Time::now()->local); - $this->assertFalse(Time::now('Europe/London')->local); - } - - public function testGetUtc() - { - $this->assertFalse(Time::now('America/Chicago')->utc); - $this->assertTrue(Time::now('UTC')->utc); - } - - public function testGetTimezone() - { - $instance = Time::now()->getTimezone(); - - $this->assertInstanceOf(\DateTimeZone::class, $instance); - } - - public function testGetTimezonename() - { - $this->assertEquals('America/Chicago', Time::now('America/Chicago')->getTimezoneName()); - $this->assertEquals('Europe/London', Time::now('Europe/London')->timezoneName); - } - - public function testSetYear() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setYear(2015); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2015-05-10 00:00:00', $time2->toDateTimeString()); - } - - public function testSetMonthNumber() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setMonth(4); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-04-10 00:00:00', $time2->toDateTimeString()); - } - - public function testSetMonthLongName() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setMonth('April'); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-04-10 00:00:00', $time2->toDateTimeString()); - } - - public function testSetMonthShortName() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setMonth('Feb'); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-02-10 00:00:00', $time2->toDateTimeString()); - } - - public function testSetDay() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setDay(15); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-05-15 00:00:00', $time2->toDateTimeString()); - } - - public function testSetHour() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setHour(15); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-05-10 15:00:00', $time2->toDateTimeString()); - } - - public function testSetMinute() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setMinute(30); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-05-10 00:30:00', $time2->toDateTimeString()); - } - - public function testSetSecond() - { - $time = Time::parse('May 10, 2017'); - $time2 = $time->setSecond(20); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-05-10 00:00:20', $time2->toDateTimeString()); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetMonthTooSmall() - { - $time = Time::parse('May 10, 2017'); - $time->setMonth(-5); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetMonthTooBig() - { - $time = Time::parse('May 10, 2017'); - $time->setMonth(30); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetDayTooSmall() - { - $time = Time::parse('May 10, 2017'); - $time->setDay(-5); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetDayTooBig() - { - $time = Time::parse('May 10, 2017'); - $time->setDay(80); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetHourTooSmall() - { - $time = Time::parse('May 10, 2017'); - $time->setHour(-5); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetHourTooBig() - { - $time = Time::parse('May 10, 2017'); - $time->setHour(80); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetMinuteTooSmall() - { - $time = Time::parse('May 10, 2017'); - $time->setMinute(-5); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetMinuteTooBig() - { - $time = Time::parse('May 10, 2017'); - $time->setMinute(80); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetSecondTooSmall() - { - $time = Time::parse('May 10, 2017'); - $time->setSecond(-5); - } - - /** - * @expectedException \CodeIgniter\I18n\Exceptions\I18nException - */ - public function testSetSecondTooBig() - { - $time = Time::parse('May 10, 2017'); - $time->setSecond(80); - } - - public function testSetTimezone() - { - $time = Time::parse('May 10, 2017', 'America/Chicago'); - $time2 = $time->setTimezone('Europe/London'); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('America/Chicago', $time->getTimezoneName()); - $this->assertEquals('Europe/London', $time2->getTimezoneName()); - } - - public function testSetTimestamp() - { - $time = Time::parse('May 10, 2017', 'America/Chicago'); - $stamp = strtotime('April 1, 2017'); - $time2 = $time->setTimestamp($stamp); - - $this->assertInstanceOf(Time::class, $time2); - $this->assertNotSame($time, $time2); - $this->assertEquals('2017-04-01 00:00:00', $time2->toDateTimeString()); - } - - public function testToDateString() - { - $time = Time::parse('May 10, 2017', 'America/Chicago'); - $this->assertEquals('2017-05-10', $time->toDateString()); - } - - /** - * Unfortunately, ubuntu 14.04 (on TravisCI) fails this test and - * shows a numeric version of the month instead of the textual version. - * Not sure what the fix is just yet.... - */ -// public function testToFormattedDateString() -// { -// $time = Time::parse('February 10, 2017', 'America/Chicago'); -// $this->assertEquals('Feb 10, 2017', $time->toFormattedDateString()); -// } - - public function testToTimeString() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $this->assertEquals('13:20:33', $time->toTimeString()); - } - - //-------------------------------------------------------------------- - // Add/Subtract - //-------------------------------------------------------------------- - - public function testCanAddSeconds() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addSeconds(10); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 13:20:43', $newTime->toDateTimeString()); - } - - public function testCanAddMinutes() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addMinutes(10); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 13:30:33', $newTime->toDateTimeString()); - } - - public function testCanAddHours() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addHours(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 16:20:33', $newTime->toDateTimeString()); - } - - public function testCanAddDays() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addDays(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-13 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanAddMonths() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addMonths(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-04-10 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanAddMonthsOverYearBoundary() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addMonths(13); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2018-02-10 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanAddYears() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->addYears(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2020-01-10 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanSubtractSeconds() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subSeconds(10); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 13:20:23', $newTime->toDateTimeString()); - } - - public function testCanSubtractMinutes() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subMinutes(10); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 13:10:33', $newTime->toDateTimeString()); - } - - public function testCanSubtractHours() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subHours(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-10 10:20:33', $newTime->toDateTimeString()); - } - - public function testCanSubtractDays() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subDays(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2017-01-07 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanSubtractMonths() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subMonths(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2016-10-10 13:20:33', $newTime->toDateTimeString()); - } - - public function testCanSubtractYears() - { - $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); - $newTime = $time->subYears(3); - $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); - $this->assertEquals('2014-01-10 13:20:33', $newTime->toDateTimeString()); - } - - //-------------------------------------------------------------------- - // Comparison - //-------------------------------------------------------------------- - - public function testEqualWithDifferent() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London'); - - $this->assertTrue($time1->equals($time2)); - } - - public function testEqualWithSame() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertTrue($time1->equals($time2)); - } - - public function testEqualWithDateTime() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = new \DateTime('January 11, 2017 03:50:00', new \DateTimeZone('Europe/London')); - - $this->assertTrue($time1->equals($time2)); - } - - public function testEqualWithSameDateTime() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = new \DateTime('January 10, 2017 21:50:00', new \DateTimeZone('America/Chicago')); - - $this->assertTrue($time1->equals($time2)); - } - - public function testEqualWithString() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertTrue($time1->equals('January 11, 2017 03:50:00', 'Europe/London')); - } - - public function testEqualWithStringAndNotimezone() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertTrue($time1->equals('January 10, 2017 21:50:00')); - } - - public function testSameSuccess() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertTrue($time1->sameAs($time2)); - } - - public function testSameFailure() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London'); - - $this->assertFalse($time1->sameAs($time2)); - } - - public function testSameSuccessAsString() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertTrue($time1->sameAs('January 10, 2017 21:50:00', 'America/Chicago')); - } - - public function testSameFailAsString() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - - $this->assertFalse($time1->sameAs('January 11, 2017 03:50:00', 'Europe/London')); - } - - public function testBefore() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago'); - - $this->assertTrue($time1->isBefore($time2)); - $this->assertFalse($time2->isBefore($time1)); - } - - public function testAfter() - { - $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); - $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago'); + public function testGetAge() + { + $time = Time::parse('5 years ago'); + + $this->assertEquals(5, $time->age); + } + + public function testGetQuarter() + { + $time = Time::parse('April 15, 2015'); + + $this->assertEquals(2, $time->quarter); + } + + public function testGetDST() + { + $this->assertFalse(Time::createFromDate(2012, 1, 1)->dst); + $this->assertTrue(Time::createFromDate(2012, 9, 1)->dst); + } + + public function testGetLocal() + { + $this->assertTrue(Time::now()->local); + $this->assertFalse(Time::now('Europe/London')->local); + } + + public function testGetUtc() + { + $this->assertFalse(Time::now('America/Chicago')->utc); + $this->assertTrue(Time::now('UTC')->utc); + } + + public function testGetTimezone() + { + $instance = Time::now()->getTimezone(); + + $this->assertInstanceOf(\DateTimeZone::class, $instance); + } + + public function testGetTimezonename() + { + $this->assertEquals('America/Chicago', Time::now('America/Chicago')->getTimezoneName()); + $this->assertEquals('Europe/London', Time::now('Europe/London')->timezoneName); + } + + public function testSetYear() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setYear(2015); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2015-05-10 00:00:00', $time2->toDateTimeString()); + } + + public function testSetMonthNumber() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setMonth(4); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-04-10 00:00:00', $time2->toDateTimeString()); + } + + public function testSetMonthLongName() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setMonth('April'); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-04-10 00:00:00', $time2->toDateTimeString()); + } + + public function testSetMonthShortName() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setMonth('Feb'); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-02-10 00:00:00', $time2->toDateTimeString()); + } + + public function testSetDay() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setDay(15); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-05-15 00:00:00', $time2->toDateTimeString()); + } + + public function testSetHour() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setHour(15); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-05-10 15:00:00', $time2->toDateTimeString()); + } + + public function testSetMinute() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setMinute(30); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-05-10 00:30:00', $time2->toDateTimeString()); + } + + public function testSetSecond() + { + $time = Time::parse('May 10, 2017'); + $time2 = $time->setSecond(20); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-05-10 00:00:20', $time2->toDateTimeString()); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetMonthTooSmall() + { + $time = Time::parse('May 10, 2017'); + $time->setMonth(-5); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetMonthTooBig() + { + $time = Time::parse('May 10, 2017'); + $time->setMonth(30); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetDayTooSmall() + { + $time = Time::parse('May 10, 2017'); + $time->setDay(-5); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetDayTooBig() + { + $time = Time::parse('May 10, 2017'); + $time->setDay(80); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetHourTooSmall() + { + $time = Time::parse('May 10, 2017'); + $time->setHour(-5); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetHourTooBig() + { + $time = Time::parse('May 10, 2017'); + $time->setHour(80); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetMinuteTooSmall() + { + $time = Time::parse('May 10, 2017'); + $time->setMinute(-5); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetMinuteTooBig() + { + $time = Time::parse('May 10, 2017'); + $time->setMinute(80); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetSecondTooSmall() + { + $time = Time::parse('May 10, 2017'); + $time->setSecond(-5); + } + + /** + * @expectedException \CodeIgniter\I18n\Exceptions\I18nException + */ + public function testSetSecondTooBig() + { + $time = Time::parse('May 10, 2017'); + $time->setSecond(80); + } + + public function testSetTimezone() + { + $time = Time::parse('May 10, 2017', 'America/Chicago'); + $time2 = $time->setTimezone('Europe/London'); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('America/Chicago', $time->getTimezoneName()); + $this->assertEquals('Europe/London', $time2->getTimezoneName()); + } + + public function testSetTimestamp() + { + $time = Time::parse('May 10, 2017', 'America/Chicago'); + $stamp = strtotime('April 1, 2017'); + $time2 = $time->setTimestamp($stamp); + + $this->assertInstanceOf(Time::class, $time2); + $this->assertNotSame($time, $time2); + $this->assertEquals('2017-04-01 00:00:00', $time2->toDateTimeString()); + } + + public function testToDateString() + { + $time = Time::parse('May 10, 2017', 'America/Chicago'); + $this->assertEquals('2017-05-10', $time->toDateString()); + } + + /** + * Unfortunately, ubuntu 14.04 (on TravisCI) fails this test and + * shows a numeric version of the month instead of the textual version. + * Not sure what the fix is just yet.... + */ +// public function testToFormattedDateString() +// { +// $time = Time::parse('February 10, 2017', 'America/Chicago'); +// $this->assertEquals('Feb 10, 2017', $time->toFormattedDateString()); +// } + + public function testToTimeString() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $this->assertEquals('13:20:33', $time->toTimeString()); + } + + //-------------------------------------------------------------------- + // Add/Subtract + //-------------------------------------------------------------------- + + public function testCanAddSeconds() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addSeconds(10); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 13:20:43', $newTime->toDateTimeString()); + } + + public function testCanAddMinutes() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addMinutes(10); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 13:30:33', $newTime->toDateTimeString()); + } + + public function testCanAddHours() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addHours(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 16:20:33', $newTime->toDateTimeString()); + } + + public function testCanAddDays() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addDays(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-13 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanAddMonths() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addMonths(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-04-10 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanAddMonthsOverYearBoundary() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addMonths(13); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2018-02-10 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanAddYears() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->addYears(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2020-01-10 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanSubtractSeconds() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subSeconds(10); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 13:20:23', $newTime->toDateTimeString()); + } + + public function testCanSubtractMinutes() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subMinutes(10); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 13:10:33', $newTime->toDateTimeString()); + } + + public function testCanSubtractHours() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subHours(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-10 10:20:33', $newTime->toDateTimeString()); + } + + public function testCanSubtractDays() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subDays(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2017-01-07 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanSubtractMonths() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subMonths(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2016-10-10 13:20:33', $newTime->toDateTimeString()); + } + + public function testCanSubtractYears() + { + $time = Time::parse('January 10, 2017 13:20:33', 'America/Chicago'); + $newTime = $time->subYears(3); + $this->assertEquals('2017-01-10 13:20:33', $time->toDateTimeString()); + $this->assertEquals('2014-01-10 13:20:33', $newTime->toDateTimeString()); + } + + //-------------------------------------------------------------------- + // Comparison + //-------------------------------------------------------------------- + + public function testEqualWithDifferent() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London'); + + $this->assertTrue($time1->equals($time2)); + } + + public function testEqualWithSame() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertTrue($time1->equals($time2)); + } + + public function testEqualWithDateTime() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = new \DateTime('January 11, 2017 03:50:00', new \DateTimeZone('Europe/London')); + + $this->assertTrue($time1->equals($time2)); + } + + public function testEqualWithSameDateTime() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = new \DateTime('January 10, 2017 21:50:00', new \DateTimeZone('America/Chicago')); + + $this->assertTrue($time1->equals($time2)); + } + + public function testEqualWithString() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertTrue($time1->equals('January 11, 2017 03:50:00', 'Europe/London')); + } + + public function testEqualWithStringAndNotimezone() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertTrue($time1->equals('January 10, 2017 21:50:00')); + } + + public function testSameSuccess() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertTrue($time1->sameAs($time2)); + } + + public function testSameFailure() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London'); + + $this->assertFalse($time1->sameAs($time2)); + } + + public function testSameSuccessAsString() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertTrue($time1->sameAs('January 10, 2017 21:50:00', 'America/Chicago')); + } + + public function testSameFailAsString() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + + $this->assertFalse($time1->sameAs('January 11, 2017 03:50:00', 'Europe/London')); + } + + public function testBefore() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago'); + + $this->assertTrue($time1->isBefore($time2)); + $this->assertFalse($time2->isBefore($time1)); + } + + public function testAfter() + { + $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago'); + $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago'); - $this->assertFalse($time1->isAfter($time2)); - $this->assertTrue($time2->isAfter($time1)); - } + $this->assertFalse($time1->isAfter($time2)); + $this->assertTrue($time2->isAfter($time1)); + } - public function testHumanizeYearsSingle() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago'); + public function testHumanizeYearsSingle() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago'); - $this->assertEquals('1 year ago', $time->humanize()); - } + $this->assertEquals('1 year ago', $time->humanize()); + } - public function testHumanizeYearsPlural() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 9, 2014 12:00:00', 'America/Chicago'); + public function testHumanizeYearsPlural() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 9, 2014 12:00:00', 'America/Chicago'); - $this->assertEquals('3 years ago', $time->humanize()); - } + $this->assertEquals('3 years ago', $time->humanize()); + } - public function testHumanizeYearsForward() - { - Time::setTestNow('January 1, 2017', 'America/Chicago'); - $time = Time::parse('January 1, 2018 12:00:00', 'America/Chicago'); + public function testHumanizeYearsForward() + { + Time::setTestNow('January 1, 2017', 'America/Chicago'); + $time = Time::parse('January 1, 2018 12:00:00', 'America/Chicago'); - $this->assertEquals('in 1 year', $time->humanize()); - } + $this->assertEquals('in 1 year', $time->humanize()); + } - public function testHumanizeMonthsSingle() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('February 9, 2017', 'America/Chicago'); + public function testHumanizeMonthsSingle() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('February 9, 2017', 'America/Chicago'); - $this->assertEquals('1 month ago', $time->humanize()); - } + $this->assertEquals('1 month ago', $time->humanize()); + } - public function testHumanizeMonthsPlural() - { - Time::setTestNow('March 1, 2017', 'America/Chicago'); - $time = Time::parse('January 1, 2017', 'America/Chicago'); + public function testHumanizeMonthsPlural() + { + Time::setTestNow('March 1, 2017', 'America/Chicago'); + $time = Time::parse('January 1, 2017', 'America/Chicago'); - $this->assertEquals('2 months ago', $time->humanize()); - } + $this->assertEquals('2 months ago', $time->humanize()); + } - public function testHumanizeMonthsForward() - { - Time::setTestNow('March 1, 2017', 'America/Chicago'); - $time = Time::parse('April 1, 2017', 'America/Chicago'); + public function testHumanizeMonthsForward() + { + Time::setTestNow('March 1, 2017', 'America/Chicago'); + $time = Time::parse('April 1, 2017', 'America/Chicago'); - $this->assertEquals('in 1 month', $time->humanize()); - } + $this->assertEquals('in 1 month', $time->humanize()); + } - public function testHumanizeDaysSingle() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 8, 2017', 'America/Chicago'); + public function testHumanizeDaysSingle() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 8, 2017', 'America/Chicago'); - $this->assertEquals('2 days ago', $time->humanize()); - } + $this->assertEquals('2 days ago', $time->humanize()); + } - public function testHumanizeDaysPlural() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 8, 2017', 'America/Chicago'); + public function testHumanizeDaysPlural() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 8, 2017', 'America/Chicago'); - $this->assertEquals('2 days ago', $time->humanize()); - } + $this->assertEquals('2 days ago', $time->humanize()); + } - public function testHumanizeDaysForward() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 12, 2017', 'America/Chicago'); + public function testHumanizeDaysForward() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 12, 2017', 'America/Chicago'); - $this->assertEquals('in 2 days', $time->humanize()); - } + $this->assertEquals('in 2 days', $time->humanize()); + } - public function testHumanizeDaysTomorrow() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 11, 2017', 'America/Chicago'); + public function testHumanizeDaysTomorrow() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 11, 2017', 'America/Chicago'); - $this->assertEquals('Tomorrow', $time->humanize()); - } - - public function testHumanizeDaysYesterday() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 9, 2017', 'America/Chicago'); + $this->assertEquals('Tomorrow', $time->humanize()); + } + + public function testHumanizeDaysYesterday() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 9, 2017', 'America/Chicago'); - $this->assertEquals('Yesterday', $time->humanize()); - } - - public function testHumanizeHoursAsTime() - { - Time::setTestNow('March 10, 2017 12:00', 'America/Chicago'); - $time = Time::parse('March 10, 2017 14:00', 'America/Chicago'); + $this->assertEquals('Yesterday', $time->humanize()); + } + + public function testHumanizeHoursAsTime() + { + Time::setTestNow('March 10, 2017 12:00', 'America/Chicago'); + $time = Time::parse('March 10, 2017 14:00', 'America/Chicago'); - $this->assertEquals('2:00 pm', $time->humanize()); - } + $this->assertEquals('2:00 pm', $time->humanize()); + } - public function testHumanizeMinutesSingle() - { - Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); - $time = Time::parse('March 10, 2017 12:29', 'America/Chicago'); + public function testHumanizeMinutesSingle() + { + Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); + $time = Time::parse('March 10, 2017 12:29', 'America/Chicago'); - $this->assertEquals('1 minute ago', $time->humanize()); - } + $this->assertEquals('1 minute ago', $time->humanize()); + } - public function testHumanizeMinutesPlural() - { - Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); - $time = Time::parse('March 10, 2017 12:28', 'America/Chicago'); + public function testHumanizeMinutesPlural() + { + Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); + $time = Time::parse('March 10, 2017 12:28', 'America/Chicago'); - $this->assertEquals('2 minutes ago', $time->humanize()); - } + $this->assertEquals('2 minutes ago', $time->humanize()); + } - public function testHumanizeMinutesForward() - { - Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); - $time = Time::parse('March 10, 2017 12:31', 'America/Chicago'); + public function testHumanizeMinutesForward() + { + Time::setTestNow('March 10, 2017 12:30', 'America/Chicago'); + $time = Time::parse('March 10, 2017 12:31', 'America/Chicago'); - $this->assertEquals('in 1 minute', $time->humanize()); - } + $this->assertEquals('in 1 minute', $time->humanize()); + } - public function testHumanizeWeeksSingle() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 2, 2017', 'America/Chicago'); + public function testHumanizeWeeksSingle() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 2, 2017', 'America/Chicago'); - $this->assertEquals('1 week ago', $time->humanize()); - } + $this->assertEquals('1 week ago', $time->humanize()); + } - public function testHumanizeWeeksPlural() - { - Time::setTestNow('March 30, 2017', 'America/Chicago'); - $time = Time::parse('March 15, 2017', 'America/Chicago'); + public function testHumanizeWeeksPlural() + { + Time::setTestNow('March 30, 2017', 'America/Chicago'); + $time = Time::parse('March 15, 2017', 'America/Chicago'); - $this->assertEquals('2 weeks ago', $time->humanize()); - } + $this->assertEquals('2 weeks ago', $time->humanize()); + } - public function testHumanizeWeeksForward() - { - Time::setTestNow('March 10, 2017', 'America/Chicago'); - $time = Time::parse('March 18, 2017', 'America/Chicago'); + public function testHumanizeWeeksForward() + { + Time::setTestNow('March 10, 2017', 'America/Chicago'); + $time = Time::parse('March 18, 2017', 'America/Chicago'); - $this->assertEquals('in 2 weeks', $time->humanize()); - } + $this->assertEquals('in 2 weeks', $time->humanize()); + } } diff --git a/tests/system/Images/GDHandlerTest.php b/tests/system/Images/GDHandlerTest.php index 739c117e8d53..5f09803d5ff0 100644 --- a/tests/system/Images/GDHandlerTest.php +++ b/tests/system/Images/GDHandlerTest.php @@ -2,13 +2,13 @@ class GDHandlerTest extends \CIUnitTestCase { - protected $path = 'tests/_support/ci-logo.png'; + protected $path = 'tests/_support/ci-logo.png'; - public function testCanReachImageMethods() - { - $image = new Image(ROOTPATH.$this->path); + public function testCanReachImageMethods() + { + $image = new Image(ROOTPATH.$this->path); - $this->assertInternalType('array', $image->getProperties(true)); - } + $this->assertInternalType('array', $image->getProperties(true)); + } } diff --git a/tests/system/Images/ImageTest.php b/tests/system/Images/ImageTest.php index bb8f76a3542c..7bb66f911acc 100644 --- a/tests/system/Images/ImageTest.php +++ b/tests/system/Images/ImageTest.php @@ -2,55 +2,55 @@ class ImageTest extends \CIUnitTestCase { - protected $path = 'tests/_support/ci-logo.png'; + protected $path = 'tests/_support/ci-logo.png'; - public function testBasicPropertiesInherited() - { - $image = new Image(ROOTPATH.$this->path); + public function testBasicPropertiesInherited() + { + $image = new Image(ROOTPATH.$this->path); - $this->assertEquals('ci-logo.png', $image->getFilename()); - $this->assertEquals(ROOTPATH.$this->path, $image->getPathname()); - $this->assertEquals(ROOTPATH.'tests/_support', $image->getPath()); - $this->assertEquals('ci-logo.png', $image->getBasename()); - } + $this->assertEquals('ci-logo.png', $image->getFilename()); + $this->assertEquals(ROOTPATH.$this->path, $image->getPathname()); + $this->assertEquals(ROOTPATH.'tests/_support', $image->getPath()); + $this->assertEquals('ci-logo.png', $image->getBasename()); + } - public function testGetProperties() - { - $image = new Image(ROOTPATH.$this->path); + public function testGetProperties() + { + $image = new Image(ROOTPATH.$this->path); - $expected = [ - 'width' => 155, - 'height' => 200, - 'image_type' => IMAGETYPE_PNG, - 'size_str' => 'width="155" height="200"', - 'mime_type' => "image/png", - ]; + $expected = [ + 'width' => 155, + 'height' => 200, + 'image_type' => IMAGETYPE_PNG, + 'size_str' => 'width="155" height="200"', + 'mime_type' => "image/png", + ]; - $this->assertEquals($expected, $image->getProperties(true)); - } + $this->assertEquals($expected, $image->getProperties(true)); + } - public function testCanCopyDefaultName() - { - $image = new Image(ROOTPATH.$this->path); + public function testCanCopyDefaultName() + { + $image = new Image(ROOTPATH.$this->path); - $image->copy(WRITEPATH); + $image->copy(WRITEPATH); - $this->assertFileExists(WRITEPATH.'ci-logo.png'); + $this->assertFileExists(WRITEPATH.'ci-logo.png'); - unlink(WRITEPATH.'ci-logo.png'); - } + unlink(WRITEPATH.'ci-logo.png'); + } - public function testCanCopyNewName() - { - $image = new Image(ROOTPATH.$this->path); + public function testCanCopyNewName() + { + $image = new Image(ROOTPATH.$this->path); - $image->copy(WRITEPATH, 'new-logo.png'); + $image->copy(WRITEPATH, 'new-logo.png'); - $this->assertFileExists(WRITEPATH.'new-logo.png'); + $this->assertFileExists(WRITEPATH.'new-logo.png'); - unlink(WRITEPATH.'new-logo.png'); - } + unlink(WRITEPATH.'new-logo.png'); + } } diff --git a/tests/system/Language/LanguageTest.php b/tests/system/Language/LanguageTest.php index 1849a9dd9de4..d4671ca1fcb5 100644 --- a/tests/system/Language/LanguageTest.php +++ b/tests/system/Language/LanguageTest.php @@ -2,95 +2,95 @@ class LanguageTest extends \CIUnitTestCase { - public function testReturnsStringWithNoFileInMessage() - { - $lang = new MockLanguage('en'); + public function testReturnsStringWithNoFileInMessage() + { + $lang = new MockLanguage('en'); - $this->assertEquals('something', $lang->getLine('something')); - } + $this->assertEquals('something', $lang->getLine('something')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetLineReturnsLine() - { - $lang = new MockLanguage('en'); + public function testGetLineReturnsLine() + { + $lang = new MockLanguage('en'); - $lang->setData([ - 'bookSaved' => 'We kept the book free from the boogeyman', - 'booksSaved' => 'We saved some more' - ]); + $lang->setData([ + 'bookSaved' => 'We kept the book free from the boogeyman', + 'booksSaved' => 'We saved some more' + ]); - $this->assertEquals('We saved some more', $lang->getLine('books.booksSaved')); - } + $this->assertEquals('We saved some more', $lang->getLine('books.booksSaved')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetLineArrayReturnsLineArray() - { - $lang = new MockLanguage('en'); + public function testGetLineArrayReturnsLineArray() + { + $lang = new MockLanguage('en'); - $lang->setData([ - 'booksList' => [ - 'The Boogeyman', - 'We Saved' - ] - ]); + $lang->setData([ + 'booksList' => [ + 'The Boogeyman', + 'We Saved' + ] + ]); - $this->assertEquals([ - 'The Boogeyman', - 'We Saved' - ], $lang->getLine('books.booksList')); - } + $this->assertEquals([ + 'The Boogeyman', + 'We Saved' + ], $lang->getLine('books.booksList')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetLineFormatsMessage() - { - // No intl extension? then we can't test this - go away.... - if (! class_exists('\MessageFormatter')) return; + public function testGetLineFormatsMessage() + { + // No intl extension? then we can't test this - go away.... + if (! class_exists('\MessageFormatter')) return; - $lang = new MockLanguage('en'); + $lang = new MockLanguage('en'); - $lang->setData([ - 'bookCount' => '{0, number, integer} books have been saved.' - ]); + $lang->setData([ + 'bookCount' => '{0, number, integer} books have been saved.' + ]); - $this->assertEquals('45 books have been saved.', $lang->getLine('books.bookCount', [91/2])); - } + $this->assertEquals('45 books have been saved.', $lang->getLine('books.bookCount', [91/2])); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetLineArrayFormatsMessages() - { - // No intl extension? Then we can't test this - go away... - if (! class_exists('\MessageFormatter')) - { - return; - } + public function testGetLineArrayFormatsMessages() + { + // No intl extension? Then we can't test this - go away... + if (! class_exists('\MessageFormatter')) + { + return; + } - $lang = new MockLanguage('en'); + $lang = new MockLanguage('en'); - $lang->setData([ - 'bookList' => [ - '{0, number, integer} related books.' - ] - ]); + $lang->setData([ + 'bookList' => [ + '{0, number, integer} related books.' + ] + ]); - $this->assertEquals(['45 related books.'], $lang->getLine('books.bookList', [91/2])); - } + $this->assertEquals(['45 related books.'], $lang->getLine('books.bookList', [91/2])); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - /** - * @see https://github.com/bcit-ci/CodeIgniter4/issues/891 - */ - public function testLangAllowsOtherLocales() - { - $str1 = lang('Language.languageGetLineInvalidArgumentException', [], 'en'); - $str2 = lang('Language.languageGetLineInvalidArgumentException', [], 'ru'); + /** + * @see https://github.com/bcit-ci/CodeIgniter4/issues/891 + */ + public function testLangAllowsOtherLocales() + { + $str1 = lang('Language.languageGetLineInvalidArgumentException', [], 'en'); + $str2 = lang('Language.languageGetLineInvalidArgumentException', [], 'ru'); - $this->assertEquals('Get line must be a string or array of strings.', $str1); - $this->assertEquals('Language.languageGetLineInvalidArgumentException', $str2); - } + $this->assertEquals('Get line must be a string or array of strings.', $str1); + $this->assertEquals('Language.languageGetLineInvalidArgumentException', $str2); + } } diff --git a/tests/system/Log/ChromeLoggerHandlerTest.php b/tests/system/Log/ChromeLoggerHandlerTest.php index 1d3ddc35e131..a431141f9fad 100644 --- a/tests/system/Log/ChromeLoggerHandlerTest.php +++ b/tests/system/Log/ChromeLoggerHandlerTest.php @@ -5,57 +5,57 @@ class ChromeLoggerHandlerTest extends \CIUnitTestCase { - public function setUp() - { - } + public function setUp() + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testCanHandleLogLevel() - { - $config = new LoggerConfig(); + { + $config = new LoggerConfig(); $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - - $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); + + $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $this->assertFalse($logger->canHandle('foo')); - } - + } + //-------------------------------------------------------------------- - + public function testHandle() { $config = new LoggerConfig(); $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - - $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); + + $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $this->assertTrue($logger->handle("warning", "This a log test") ); } - + //-------------------------------------------------------------------- - + public function testSendLogs() - { + { $config = new LoggerConfig(); $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - - $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); + + $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $logger->sendLogs(); - + $response = Services::response(null, true); - + $this->assertTrue($response->hasHeader('X-ChromeLogger-Data')); } - + //-------------------------------------------------------------------- - + public function testSetDateFormat() - { + { $config = new LoggerConfig(); $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - - $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); + + $logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $result = $logger->setDateFormat('F j, Y'); - + $this->assertObjectHasAttribute('dateFormat', $result); $this->assertObjectHasAttribute('dateFormat', $logger); } diff --git a/tests/system/Log/FileHandlerTest.php b/tests/system/Log/FileHandlerTest.php index 415b4ddd90af..e4795b2eafc0 100644 --- a/tests/system/Log/FileHandlerTest.php +++ b/tests/system/Log/FileHandlerTest.php @@ -4,17 +4,17 @@ class FileHandlerTest extends \CIUnitTestCase { - public function setUp() - { - } + public function setUp() + { + } + + //-------------------------------------------------------------------- - //-------------------------------------------------------------------- - public function testHandle() { $config = new LoggerConfig(); $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - + $logger = new FileHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']); $logger->setDateFormat("Y-m-d H:i:s:u"); $this->assertTrue($logger->handle("warning", "This is a test log") ); diff --git a/tests/system/Log/LoggerTest.php b/tests/system/Log/LoggerTest.php index 1136a71ca1bf..587e3a6fce3c 100644 --- a/tests/system/Log/LoggerTest.php +++ b/tests/system/Log/LoggerTest.php @@ -8,352 +8,352 @@ class LoggerTest extends \CIUnitTestCase { - public function setUp() - { - } + public function setUp() + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testThrowsExceptionWithBadHandlerSettings() - { - $config = new LoggerConfig(); - $config->handlers = null; + public function testThrowsExceptionWithBadHandlerSettings() + { + $config = new LoggerConfig(); + $config->handlers = null; - $this->expectException(FrameworkException::class); - $this->expectExceptionMessage(lang('Core.noHandlers', ['LoggerConfig'])); + $this->expectException(FrameworkException::class); + $this->expectExceptionMessage(lang('Core.noHandlers', ['LoggerConfig'])); - $logger = new Logger($config); - } + $logger = new Logger($config); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogThrowsExceptionOnInvalidLevel() - { - $config = new LoggerConfig(); + public function testLogThrowsExceptionOnInvalidLevel() + { + $config = new LoggerConfig(); - $this->expectException(LogException::class); - $this->expectExceptionMessage(lang('Log.invalidLogLevel', ['foo'])); + $this->expectException(LogException::class); + $this->expectExceptionMessage(lang('Log.invalidLogLevel', ['foo'])); - $logger = new Logger($config); + $logger = new Logger($config); - $logger->log('foo', ''); - } + $logger->log('foo', ''); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogReturnsFalseWhenLogNotHandled() - { - $config = new LoggerConfig(); - $config->threshold = 3; + public function testLogReturnsFalseWhenLogNotHandled() + { + $config = new LoggerConfig(); + $config->threshold = 3; - $logger = new Logger($config); + $logger = new Logger($config); - $this->assertFalse($logger->log('debug', '')); - } + $this->assertFalse($logger->log('debug', '')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogActuallyLogs() - { - $config = new LoggerConfig(); -// $Config->handlers['TestHandler']['handles'] = [LogLevel::CRITICAL]; + public function testLogActuallyLogs() + { + $config = new LoggerConfig(); +// $Config->handlers['TestHandler']['handles'] = [LogLevel::CRITICAL]; - $logger = new Logger($config); + $logger = new Logger($config); - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message'; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message'; - $logger->log('debug', 'Test message'); + $logger->log('debug', 'Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogDoesnotLogUnhandledLevels() - { - $config = new LoggerConfig(); - $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; + public function testLogDoesnotLogUnhandledLevels() + { + $config = new LoggerConfig(); + $config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical']; - $logger = new Logger($config); + $logger = new Logger($config); - $logger->log('debug', 'Test message'); + $logger->log('debug', 'Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(0, $logs); - } + $this->assertCount(0, $logs); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesMessage() - { - $config = new LoggerConfig(); + public function testLogInterpolatesMessage() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message bar baz'; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message bar baz'; - $logger->log('debug', 'Test message {foo} {bar}', ['foo' => 'bar', 'bar' => 'baz']); + $logger->log('debug', 'Test message {foo} {bar}', ['foo' => 'bar', 'bar' => 'baz']); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesPost() - { - $config = new LoggerConfig(); + public function testLogInterpolatesPost() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $_POST = ['foo' => 'bar']; - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_POST: '. print_r($_POST, true); + $_POST = ['foo' => 'bar']; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_POST: '. print_r($_POST, true); - $logger->log('debug', 'Test message {post_vars}'); + $logger->log('debug', 'Test message {post_vars}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesGet() - { - $config = new LoggerConfig(); + public function testLogInterpolatesGet() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $_GET = ['bar' => 'baz']; - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_GET: '. print_r($_GET, true); + $_GET = ['bar' => 'baz']; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_GET: '. print_r($_GET, true); - $logger->log('debug', 'Test message {get_vars}'); + $logger->log('debug', 'Test message {get_vars}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesSession() - { - $config = new LoggerConfig(); + public function testLogInterpolatesSession() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $_SESSION = ['xxx' => 'yyy']; - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_SESSION: '. print_r($_SESSION, true); + $_SESSION = ['xxx' => 'yyy']; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message $_SESSION: '. print_r($_SESSION, true); - $logger->log('debug', 'Test message {session_vars}'); + $logger->log('debug', 'Test message {session_vars}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesCurrentEnvironment() - { - $config = new LoggerConfig(); + public function testLogInterpolatesCurrentEnvironment() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message '. ENVIRONMENT; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message '. ENVIRONMENT; - $logger->log('debug', 'Test message {env}'); + $logger->log('debug', 'Test message {env}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesEnvironmentVars() - { - $config = new LoggerConfig(); + public function testLogInterpolatesEnvironmentVars() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $_ENV['foo'] = 'bar'; + $_ENV['foo'] = 'bar'; - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message bar'; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message bar'; - $logger->log('debug', 'Test message {env:foo}'); + $logger->log('debug', 'Test message {env:foo}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testLogInterpolatesFileAndLine() - { - $config = new LoggerConfig(); + public function testLogInterpolatesFileAndLine() + { + $config = new LoggerConfig(); - $logger = new Logger($config); + $logger = new Logger($config); - $_ENV['foo'] = 'bar'; + $_ENV['foo'] = 'bar'; - // For whatever reason, this will often be the class/function instead of file and line. - // Other times it actually returns the line number, so don't look for either - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message CodeIgniter\Log\LoggerTest'; + // For whatever reason, this will often be the class/function instead of file and line. + // Other times it actually returns the line number, so don't look for either + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message CodeIgniter\Log\LoggerTest'; - $logger->log('debug', 'Test message {file} {line}'); + $logger->log('debug', 'Test message {file} {line}'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertTrue(strpos($logs[0], $expected) === 0); - } + $this->assertCount(1, $logs); + $this->assertTrue(strpos($logs[0], $expected) === 0); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testEmergencyLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testEmergencyLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'EMERGENCY - '.date('Y-m-d').' --> Test message'; + $expected = 'EMERGENCY - '.date('Y-m-d').' --> Test message'; - $logger->emergency('Test message'); + $logger->emergency('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAlertLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testAlertLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'ALERT - '.date('Y-m-d').' --> Test message'; + $expected = 'ALERT - '.date('Y-m-d').' --> Test message'; - $logger->alert('Test message'); + $logger->alert('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testCriticalLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testCriticalLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'CRITICAL - '.date('Y-m-d').' --> Test message'; + $expected = 'CRITICAL - '.date('Y-m-d').' --> Test message'; - $logger->critical('Test message'); + $logger->critical('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testErrorLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testErrorLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'ERROR - '.date('Y-m-d').' --> Test message'; + $expected = 'ERROR - '.date('Y-m-d').' --> Test message'; - $logger->error('Test message'); + $logger->error('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testWarningLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testWarningLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'WARNING - '.date('Y-m-d').' --> Test message'; + $expected = 'WARNING - '.date('Y-m-d').' --> Test message'; - $logger->warning('Test message'); + $logger->warning('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testNoticeLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testNoticeLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'NOTICE - '.date('Y-m-d').' --> Test message'; + $expected = 'NOTICE - '.date('Y-m-d').' --> Test message'; - $logger->notice('Test message'); + $logger->notice('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testInfoLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testInfoLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'INFO - '.date('Y-m-d').' --> Test message'; + $expected = 'INFO - '.date('Y-m-d').' --> Test message'; - $logger->info('Test message'); + $logger->info('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDebugLogsCorrectly() - { - $config = new LoggerConfig(); - $logger = new Logger($config); + public function testDebugLogsCorrectly() + { + $config = new LoggerConfig(); + $logger = new Logger($config); - $expected = 'DEBUG - '.date('Y-m-d').' --> Test message'; + $expected = 'DEBUG - '.date('Y-m-d').' --> Test message'; - $logger->debug('Test message'); + $logger->debug('Test message'); - $logs = TestHandler::getLogs(); + $logs = TestHandler::getLogs(); - $this->assertCount(1, $logs); - $this->assertEquals($expected, $logs[0]); - } + $this->assertCount(1, $logs); + $this->assertEquals($expected, $logs[0]); + } } diff --git a/tests/system/Pager/PagerRendererTest.php b/tests/system/Pager/PagerRendererTest.php index 17571a0e450a..80cc0436f3f5 100644 --- a/tests/system/Pager/PagerRendererTest.php +++ b/tests/system/Pager/PagerRendererTest.php @@ -4,189 +4,189 @@ class PagerRendererTest extends \CIUnitTestCase { - protected $uri; + protected $uri; - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setUp() - { - $this->uri = new URI('http://example.com/foo'); - } + public function setUp() + { + $this->uri = new URI('http://example.com/foo'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHasPreviousReturnsFalseWhenFirstIsOne() - { - $details = [ - 'uri' => $this->uri, - 'pageCount' => 5, - 'currentPage' => 1, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); + public function testHasPreviousReturnsFalseWhenFirstIsOne() + { + $details = [ + 'uri' => $this->uri, + 'pageCount' => 5, + 'currentPage' => 1, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); - $this->assertFalse($pager->hasPrevious()); - } + $this->assertFalse($pager->hasPrevious()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHasPreviousReturnsTrueWhenFirstIsMoreThanOne() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); + public function testHasPreviousReturnsTrueWhenFirstIsMoreThanOne() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); - $details = [ - 'uri' => $uri, - 'pageCount' => 10, - 'currentPage' => 5, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(2); - - $this->assertTrue($pager->hasPrevious()); - $this->assertEquals('http://example.com/foo?foo=bar&page=2', $pager->getPrevious()); - } - - //-------------------------------------------------------------------- - - public function testGetPreviousWhenSurroundCountIsZero() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); - - $details = [ - 'uri' => $uri, - 'pageCount' => 50, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(0); - - $this->assertTrue($pager->hasPrevious()); - $this->assertEquals('http://example.com/foo?foo=bar&page=3', $pager->getPrevious()); - } - - //-------------------------------------------------------------------- - - public function testHasNextReturnsFalseWhenLastIsTotal() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); - - $details = [ - 'uri' => $uri, - 'pageCount' => 5, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(2); - - $this->assertFalse($pager->hasNext()); - } - - //-------------------------------------------------------------------- - - public function testHasNextReturnsTrueWhenLastIsSmallerThanTotal() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); - - $details = [ - 'uri' => $uri, - 'pageCount' => 50, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(2); - - $this->assertTrue($pager->hasNext()); - $this->assertEquals('http://example.com/foo?foo=bar&page=7', $pager->getNext()); - } - - //-------------------------------------------------------------------- - - public function testGetNextWhenSurroundCountIsZero() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); - - $details = [ - 'uri' => $uri, - 'pageCount' => 50, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(0); - - $this->assertTrue($pager->hasNext()); - $this->assertEquals('http://example.com/foo?foo=bar&page=5', $pager->getNext()); - } - - //-------------------------------------------------------------------- - - public function testLinksBasics() - { - $details = [ - 'uri' => $this->uri, - 'pageCount' => 50, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - $pager->setSurroundCount(1); - - $expected = [ - [ - 'uri' => 'http://example.com/foo?page=3', - 'title' => 3, - 'active' => false - ], - [ - 'uri' => 'http://example.com/foo?page=4', - 'title' => 4, - 'active' => true - ], - [ - 'uri' => 'http://example.com/foo?page=5', - 'title' => 5, - 'active' => false - ], - ]; - - $this->assertEquals($expected, $pager->links()); - } - - //-------------------------------------------------------------------- - - public function testGetFirstAndGetLast() - { - $uri = $this->uri; - $uri->addQuery('foo', 'bar'); - - $details = [ - 'uri' => $uri, - 'pageCount' => 50, - 'currentPage' => 4, - 'total' => 100 - ]; - - $pager = new PagerRenderer($details); - - $this->assertEquals('http://example.com/foo?foo=bar&page=1', $pager->getFirst()); - $this->assertEquals('http://example.com/foo?foo=bar&page=50', $pager->getLast()); - } - - //-------------------------------------------------------------------- + $details = [ + 'uri' => $uri, + 'pageCount' => 10, + 'currentPage' => 5, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(2); + + $this->assertTrue($pager->hasPrevious()); + $this->assertEquals('http://example.com/foo?foo=bar&page=2', $pager->getPrevious()); + } + + //-------------------------------------------------------------------- + + public function testGetPreviousWhenSurroundCountIsZero() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); + + $details = [ + 'uri' => $uri, + 'pageCount' => 50, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(0); + + $this->assertTrue($pager->hasPrevious()); + $this->assertEquals('http://example.com/foo?foo=bar&page=3', $pager->getPrevious()); + } + + //-------------------------------------------------------------------- + + public function testHasNextReturnsFalseWhenLastIsTotal() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); + + $details = [ + 'uri' => $uri, + 'pageCount' => 5, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(2); + + $this->assertFalse($pager->hasNext()); + } + + //-------------------------------------------------------------------- + + public function testHasNextReturnsTrueWhenLastIsSmallerThanTotal() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); + + $details = [ + 'uri' => $uri, + 'pageCount' => 50, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(2); + + $this->assertTrue($pager->hasNext()); + $this->assertEquals('http://example.com/foo?foo=bar&page=7', $pager->getNext()); + } + + //-------------------------------------------------------------------- + + public function testGetNextWhenSurroundCountIsZero() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); + + $details = [ + 'uri' => $uri, + 'pageCount' => 50, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(0); + + $this->assertTrue($pager->hasNext()); + $this->assertEquals('http://example.com/foo?foo=bar&page=5', $pager->getNext()); + } + + //-------------------------------------------------------------------- + + public function testLinksBasics() + { + $details = [ + 'uri' => $this->uri, + 'pageCount' => 50, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + $pager->setSurroundCount(1); + + $expected = [ + [ + 'uri' => 'http://example.com/foo?page=3', + 'title' => 3, + 'active' => false + ], + [ + 'uri' => 'http://example.com/foo?page=4', + 'title' => 4, + 'active' => true + ], + [ + 'uri' => 'http://example.com/foo?page=5', + 'title' => 5, + 'active' => false + ], + ]; + + $this->assertEquals($expected, $pager->links()); + } + + //-------------------------------------------------------------------- + + public function testGetFirstAndGetLast() + { + $uri = $this->uri; + $uri->addQuery('foo', 'bar'); + + $details = [ + 'uri' => $uri, + 'pageCount' => 50, + 'currentPage' => 4, + 'total' => 100 + ]; + + $pager = new PagerRenderer($details); + + $this->assertEquals('http://example.com/foo?foo=bar&page=1', $pager->getFirst()); + $this->assertEquals('http://example.com/foo?foo=bar&page=50', $pager->getLast()); + } + + //-------------------------------------------------------------------- } diff --git a/tests/system/Pager/PagerTest.php b/tests/system/Pager/PagerTest.php index 558a4d97bb54..ca0e9c3312f2 100644 --- a/tests/system/Pager/PagerTest.php +++ b/tests/system/Pager/PagerTest.php @@ -9,313 +9,313 @@ */ class PagerTest extends \CIUnitTestCase { - /** - * @var \CodeIgniter\Pager\Pager - */ - protected $pager; - protected $config; + /** + * @var \CodeIgniter\Pager\Pager + */ + protected $pager; + protected $config; - public function __construct() - { - parent::__construct(); - helper('url'); - } + public function __construct() + { + parent::__construct(); + helper('url'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function setUp() - { - $_SERVER['HTTP_HOST'] = 'example.com'; - $_GET = []; - $this->config = new Pager(); - $this->pager = new \CodeIgniter\Pager\Pager($this->config, Services::renderer()); - } + public function setUp() + { + $_SERVER['HTTP_HOST'] = 'example.com'; + $_GET = []; + $this->config = new Pager(); + $this->pager = new \CodeIgniter\Pager\Pager($this->config, Services::renderer()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSetPathRemembersPath() - { - $this->pager->setPath('foo/bar'); + public function testSetPathRemembersPath() + { + $this->pager->setPath('foo/bar'); - $details = $this->pager->getDetails(); + $details = $this->pager->getDetails(); - $this->assertEquals('foo/bar', $details['uri']->getPath()); - } + $this->assertEquals('foo/bar', $details['uri']->getPath()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetDetailsRecognizesPageQueryVar() - { - $_GET['page'] = 2; + public function testGetDetailsRecognizesPageQueryVar() + { + $_GET['page'] = 2; - // Need this to create the group. - $this->pager->setPath('foo/bar'); + // Need this to create the group. + $this->pager->setPath('foo/bar'); - $details = $this->pager->getDetails(); + $details = $this->pager->getDetails(); - $this->assertEquals(2, $details['currentPage']); - } + $this->assertEquals(2, $details['currentPage']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetDetailsRecognizesGroupedPageQueryVar() - { - $_GET['page_foo'] = 2; + public function testGetDetailsRecognizesGroupedPageQueryVar() + { + $_GET['page_foo'] = 2; - // Need this to create the group. - $this->pager->setPath('foo/bar', 'foo'); + // Need this to create the group. + $this->pager->setPath('foo/bar', 'foo'); - $details = $this->pager->getDetails('foo'); + $details = $this->pager->getDetails('foo'); - $this->assertEquals(2, $details['currentPage']); - } + $this->assertEquals(2, $details['currentPage']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetDetailsThrowExceptionIfGroupNotFound() - { - $this->expectException(PagerException::class); + public function testGetDetailsThrowExceptionIfGroupNotFound() + { + $this->expectException(PagerException::class); - $this->pager->getDetails('foo'); - } + $this->pager->getDetails('foo'); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testDetailsHasConfiguredPerPageValue() - { - // Need this to create the group. - $this->pager->setPath('foo/bar', 'foo'); + public function testDetailsHasConfiguredPerPageValue() + { + // Need this to create the group. + $this->pager->setPath('foo/bar', 'foo'); - $details = $this->pager->getDetails('foo'); + $details = $this->pager->getDetails('foo'); - $this->assertEquals($this->config->perPage, $details['perPage']); - } + $this->assertEquals($this->config->perPage, $details['perPage']); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testStoreDoesBasicCalcs() - { - $this->pager->store('foo', 3, 25, 100); + public function testStoreDoesBasicCalcs() + { + $this->pager->store('foo', 3, 25, 100); - $details = $this->pager->getDetails('foo'); + $details = $this->pager->getDetails('foo'); - $this->assertEquals($details['total'], 100); - $this->assertEquals($details['perPage'], 25); - $this->assertEquals($details['currentPage'], 3); - } + $this->assertEquals($details['total'], 100); + $this->assertEquals($details['perPage'], 25); + $this->assertEquals($details['currentPage'], 3); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testStoreAndHasMore() - { - $this->pager->store('foo', 3, 25, 100); + public function testStoreAndHasMore() + { + $this->pager->store('foo', 3, 25, 100); - $this->assertTrue($this->pager->hasMore('foo')); - } + $this->assertTrue($this->pager->hasMore('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testStoreAndHasMoreCanBeFalse() - { - $this->pager->store('foo', 3, 25, 70); + public function testStoreAndHasMoreCanBeFalse() + { + $this->pager->store('foo', 3, 25, 70); - $this->assertFalse($this->pager->hasMore('foo')); - } + $this->assertFalse($this->pager->hasMore('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testHasMoreDefaultsToFalse() - { - $this->assertFalse($this->pager->hasMore('foo')); - } + public function testHasMoreDefaultsToFalse() + { + $this->assertFalse($this->pager->hasMore('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPerPageHasDefaultValue() - { - $this->assertEquals($this->config->perPage, $this->pager->getPerPage()); - } + public function testPerPageHasDefaultValue() + { + $this->assertEquals($this->config->perPage, $this->pager->getPerPage()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testPerPageKeepsStoredValue() - { - $this->pager->store('foo', 3, 13, 70); + public function testPerPageKeepsStoredValue() + { + $this->pager->store('foo', 3, 13, 70); - $this->assertEquals(13, $this->pager->getPerPage('foo')); - } + $this->assertEquals(13, $this->pager->getPerPage('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetCurrentPageDefaultsToOne() - { - $this->assertEquals(1, $this->pager->getCurrentPage()); - } + public function testGetCurrentPageDefaultsToOne() + { + $this->assertEquals(1, $this->pager->getCurrentPage()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetCurrentPageRemembersStoredPage() - { - $this->pager->store('foo', 3, 13, 70); + public function testGetCurrentPageRemembersStoredPage() + { + $this->pager->store('foo', 3, 13, 70); - $this->assertEquals(3, $this->pager->getCurrentPage('foo')); - } + $this->assertEquals(3, $this->pager->getCurrentPage('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetCurrentPageDetectsURI() - { - $_GET['page'] = 2; + public function testGetCurrentPageDetectsURI() + { + $_GET['page'] = 2; - $this->assertEquals(2, $this->pager->getCurrentPage()); - } + $this->assertEquals(2, $this->pager->getCurrentPage()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetCurrentPageDetectsGroupedURI() - { - $_GET['page_foo'] = 2; + public function testGetCurrentPageDetectsGroupedURI() + { + $_GET['page_foo'] = 2; - $this->assertEquals(2, $this->pager->getCurrentPage('foo')); - } + $this->assertEquals(2, $this->pager->getCurrentPage('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetTotalPagesDefaultsToOne() - { - $this->assertEquals(1, $this->pager->getPageCount()); - } + public function testGetTotalPagesDefaultsToOne() + { + $this->assertEquals(1, $this->pager->getPageCount()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetTotalPagesCalcsCorrectValue() - { - $this->pager->store('foo', 3, 12, 70); + public function testGetTotalPagesCalcsCorrectValue() + { + $this->pager->store('foo', 3, 12, 70); - $this->assertEquals(6, $this->pager->getPageCount('foo')); - } + $this->assertEquals(6, $this->pager->getPageCount('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetNextURIUsesCurrentURI() - { - $_GET['page'] = 2; + public function testGetNextURIUsesCurrentURI() + { + $_GET['page'] = 2; - $this->pager->store('foo', 2, 12, 70); + $this->pager->store('foo', 2, 12, 70); - $expected = current_url(true); - $expected = (string)$expected->setQuery('page=3'); + $expected = current_url(true); + $expected = (string)$expected->setQuery('page=3'); - $this->assertEquals((string)$expected, $this->pager->getNextPageURI('foo')); - } + $this->assertEquals((string)$expected, $this->pager->getNextPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetNextURIReturnsNullOnLastPage() - { - $this->pager->store('foo', 6, 12, 70); + public function testGetNextURIReturnsNullOnLastPage() + { + $this->pager->store('foo', 6, 12, 70); - $this->assertNull($this->pager->getNextPageURI('foo')); - } + $this->assertNull($this->pager->getNextPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetNextURICorrectOnFirstPage() - { - $this->pager->store('foo', 1, 12, 70); + public function testGetNextURICorrectOnFirstPage() + { + $this->pager->store('foo', 1, 12, 70); - $expected = current_url(true); - $expected = (string)$expected->setQuery('page=2'); + $expected = current_url(true); + $expected = (string)$expected->setQuery('page=2'); - $this->assertEquals($expected, $this->pager->getNextPageURI('foo')); - } + $this->assertEquals($expected, $this->pager->getNextPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetPreviousURIUsesCurrentURI() - { - $_GET['page'] = 2; + public function testGetPreviousURIUsesCurrentURI() + { + $_GET['page'] = 2; - $this->pager->store('foo', 2, 12, 70); + $this->pager->store('foo', 2, 12, 70); - $expected = current_url(true); - $expected = (string)$expected->setQuery('page=1'); + $expected = current_url(true); + $expected = (string)$expected->setQuery('page=1'); - $this->assertEquals((string)$expected, $this->pager->getPreviousPageURI('foo')); - } + $this->assertEquals((string)$expected, $this->pager->getPreviousPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetNextURIReturnsNullOnFirstPage() - { - $this->pager->store('foo', 1, 12, 70); + public function testGetNextURIReturnsNullOnFirstPage() + { + $this->pager->store('foo', 1, 12, 70); - $this->assertNull($this->pager->getPreviousPageURI('foo')); - } + $this->assertNull($this->pager->getPreviousPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetNextURIWithQueryStringUsesCurrentURI() - { - $_GET = [ - 'page' => 3, - 'status' => 1 - ]; + public function testGetNextURIWithQueryStringUsesCurrentURI() + { + $_GET = [ + 'page' => 3, + 'status' => 1 + ]; - $expected = current_url(true); - $expected = (string)$expected->setQueryArray($_GET); + $expected = current_url(true); + $expected = (string)$expected->setQueryArray($_GET); - $this->pager->store('foo', $_GET['page']-1, 12, 70); + $this->pager->store('foo', $_GET['page']-1, 12, 70); - $this->assertEquals((string)$expected, $this->pager->getNextPageURI('foo')); - } + $this->assertEquals((string)$expected, $this->pager->getNextPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetPreviousURIWithQueryStringUsesCurrentURI() - { - $_GET = [ - 'page' => 1, - 'status' => 1 - ]; - $expected = current_url(true); - $expected = (string)$expected->setQueryArray($_GET); + public function testGetPreviousURIWithQueryStringUsesCurrentURI() + { + $_GET = [ + 'page' => 1, + 'status' => 1 + ]; + $expected = current_url(true); + $expected = (string)$expected->setQueryArray($_GET); - $this->pager->store('foo', $_GET['page']+1, 12, 70); + $this->pager->store('foo', $_GET['page']+1, 12, 70); - $this->assertEquals((string)$expected, $this->pager->getPreviousPageURI('foo')); - } + $this->assertEquals((string)$expected, $this->pager->getPreviousPageURI('foo')); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGetOnlyQueries() - { - $_GET = [ - 'page' => 2, - 'search' => 'foo', - 'order' => 'asc', - 'hello' => 'xxx', - 'category' => 'baz', - ]; - $onlyQueries = ['search', 'order']; + public function testGetOnlyQueries() + { + $_GET = [ + 'page' => 2, + 'search' => 'foo', + 'order' => 'asc', + 'hello' => 'xxx', + 'category' => 'baz', + ]; + $onlyQueries = ['search', 'order']; - $this->pager->store('default', $_GET['page'], 10, 100); + $this->pager->store('default', $_GET['page'], 10, 100); - $uri = current_url(true); + $uri = current_url(true); - $this->assertEquals( - $this->pager->only($onlyQueries)->getPreviousPageURI(), - (string)$uri->setQuery('search=foo&order=asc&page=1') - ); - $this->assertEquals( - $this->pager->only($onlyQueries)->getNextPageURI(), - (string)$uri->setQuery('search=foo&order=asc&page=3') - ); - $this->assertEquals( - $this->pager->only($onlyQueries)->getPageURI(4), - (string)$uri->setQuery('search=foo&order=asc&page=4') - ); - } + $this->assertEquals( + $this->pager->only($onlyQueries)->getPreviousPageURI(), + (string)$uri->setQuery('search=foo&order=asc&page=1') + ); + $this->assertEquals( + $this->pager->only($onlyQueries)->getNextPageURI(), + (string)$uri->setQuery('search=foo&order=asc&page=3') + ); + $this->assertEquals( + $this->pager->only($onlyQueries)->getPageURI(4), + (string)$uri->setQuery('search=foo&order=asc&page=4') + ); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Router/RouteCollectionTest.php b/tests/system/Router/RouteCollectionTest.php index b16b51e6c3e5..e4308bf8185f 100644 --- a/tests/system/Router/RouteCollectionTest.php +++ b/tests/system/Router/RouteCollectionTest.php @@ -9,104 +9,104 @@ class RouteCollectionTest extends \CIUnitTestCase { - public function setUp() - { - } + public function setUp() + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function tearDown() - { - } + public function tearDown() + { + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - protected function getCollector(array $config=[], array $files=[]) - { - $defaults = [ - 'Config' => APPPATH.'Config', - 'App' => APPPATH, - ]; - $config = array_merge($config, $defaults); + protected function getCollector(array $config=[], array $files=[]) + { + $defaults = [ + 'Config' => APPPATH.'Config', + 'App' => APPPATH, + ]; + $config = array_merge($config, $defaults); - $autoload = new \Config\Autoload(); - $autoload->psr4 = $config; + $autoload = new \Config\Autoload(); + $autoload->psr4 = $config; - $loader = new MockFileLocator($autoload); - $loader->setFiles($files); + $loader = new MockFileLocator($autoload); + $loader->setFiles($files); - return new RouteCollection($loader); - } + return new RouteCollection($loader); + } - public function testBasicAdd() - { - $routes = $this->getCollector(); + public function testBasicAdd() + { + $routes = $this->getCollector(); - $routes->add('home', '\my\controller'); + $routes->add('home', '\my\controller'); - $expects = [ - 'home' => '\my\controller', - ]; + $expects = [ + 'home' => '\my\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddPrefixesDefaultNamespaceWhenNoneExist() - { - $routes = $this->getCollector(); + public function testAddPrefixesDefaultNamespaceWhenNoneExist() + { + $routes = $this->getCollector(); - $routes->add('home', 'controller'); + $routes->add('home', 'controller'); - $expects = [ - 'home' => '\controller', - ]; + $expects = [ + 'home' => '\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddIgnoresDefaultNamespaceWhenExists() - { - $routes = $this->getCollector(); + public function testAddIgnoresDefaultNamespaceWhenExists() + { + $routes = $this->getCollector(); - $routes->add('home', 'my\controller'); + $routes->add('home', 'my\controller'); - $expects = [ - 'home' => '\my\controller', - ]; + $expects = [ + 'home' => '\my\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddWorksWithCurrentHTTPMethods() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; + public function testAddWorksWithCurrentHTTPMethods() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; - $routes = $this->getCollector(); + $routes = $this->getCollector(); - $routes->match(['get'], 'home', 'controller'); + $routes->match(['get'], 'home', 'controller'); - $expects = [ - 'home' => '\controller', - ]; + $expects = [ + 'home' => '\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- public function testAddWithLeadingSlash() { @@ -125,679 +125,679 @@ public function testAddWithLeadingSlash() //-------------------------------------------------------------------- - public function testMatchIgnoresInvalidHTTPMethods() - { - $_SERVER['REQUEST_METHOD'] = 'GET'; + public function testMatchIgnoresInvalidHTTPMethods() + { + $_SERVER['REQUEST_METHOD'] = 'GET'; - $routes = $this->getCollector(); + $routes = $this->getCollector(); - $routes->match(['put'], 'home', 'controller'); + $routes->match(['put'], 'home', 'controller'); - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals([], $routes); - } + $this->assertEquals([], $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddWorksWithArrayOFHTTPMethods() - { - $_SERVER['REQUEST_METHOD'] = 'POST'; + public function testAddWorksWithArrayOFHTTPMethods() + { + $_SERVER['REQUEST_METHOD'] = 'POST'; - $routes = $this->getCollector(); + $routes = $this->getCollector(); - $routes->add('home', 'controller', ['get', 'post']); + $routes->add('home', 'controller', ['get', 'post']); - $expects = [ - 'home' => '\controller', - ]; + $expects = [ + 'home' => '\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddReplacesDefaultPlaceholders() - { - $routes = $this->getCollector(); + public function testAddReplacesDefaultPlaceholders() + { + $routes = $this->getCollector(); - $routes->add('home/(:any)', 'controller'); + $routes->add('home/(:any)', 'controller'); - $expects = [ - 'home/(.*)' => '\controller', - ]; + $expects = [ + 'home/(.*)' => '\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddReplacesCustomPlaceholders() - { - $routes = $this->getCollector(); - $routes->addPlaceholder('smiley', ':-)'); + public function testAddReplacesCustomPlaceholders() + { + $routes = $this->getCollector(); + $routes->addPlaceholder('smiley', ':-)'); - $routes->add('home/(:smiley)', 'controller'); + $routes->add('home/(:smiley)', 'controller'); - $expects = [ - 'home/(:-))' => '\controller', - ]; + $expects = [ + 'home/(:-))' => '\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAddRecognizesCustomNamespaces() - { - $routes = $this->getCollector(); - $routes->setDefaultNamespace('\CodeIgniter'); + public function testAddRecognizesCustomNamespaces() + { + $routes = $this->getCollector(); + $routes->setDefaultNamespace('\CodeIgniter'); - $routes->add('home', 'controller'); + $routes->add('home', 'controller'); - $expects = [ - 'home' => '\CodeIgniter\controller', - ]; + $expects = [ + 'home' => '\CodeIgniter\controller', + ]; - $routes = $routes->getRoutes(); + $routes = $routes->getRoutes(); - $this->assertEquals($expects, $routes); - } + $this->assertEquals($expects, $routes); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSetDefaultControllerStoresIt() - { - $routes = $this->getCollector(); - $routes->setDefaultController('godzilla'); + public function testSetDefaultControllerStoresIt() + { + $routes = $this->getCollector(); + $routes->setDefaultController('godzilla'); - $this->assertEquals('godzilla', $routes->getDefaultController()); - } + $this->assertEquals('godzilla', $routes->getDefaultController()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testSetDefaultMethodStoresIt() - { - $routes = $this->getCollector(); - $routes->setDefaultMethod('biggerBox'); + public function testSetDefaultMethodStoresIt() + { + $routes = $this->getCollector(); + $routes->setDefaultMethod('biggerBox'); - $this->assertEquals('biggerBox', $routes->getDefaultMethod()); - } + $this->assertEquals('biggerBox', $routes->getDefaultMethod()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testTranslateURIDashesWorks() - { - $routes = $this->getCollector(); - $routes->setTranslateURIDashes(true); + public function testTranslateURIDashesWorks() + { + $routes = $this->getCollector(); + $routes->setTranslateURIDashes(true); - $this->assertTrue($routes->shouldTranslateURIDashes()); - } + $this->assertTrue($routes->shouldTranslateURIDashes()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testAutoRouteStoresIt() - { - $routes = $this->getCollector(); - $routes->setAutoRoute(true); + public function testAutoRouteStoresIt() + { + $routes = $this->getCollector(); + $routes->setAutoRoute(true); - $this->assertTrue($routes->shouldAutoRoute()); - } + $this->assertTrue($routes->shouldAutoRoute()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGroupingWorks() - { - $routes = $this->getCollector(); + public function testGroupingWorks() + { + $routes = $this->getCollector(); - $routes->group('admin', function($routes) - { - $routes->add('users/list', '\Users::list'); - }); + $routes->group('admin', function($routes) + { + $routes->add('users/list', '\Users::list'); + }); - $expected = [ - 'admin/users/list' => '\Users::list' - ]; + $expected = [ + 'admin/users/list' => '\Users::list' + ]; - $this->assertEquals($expected, $routes->getRoutes()); - } + $this->assertEquals($expected, $routes->getRoutes()); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- - public function testGroupGetsSanitized() - { - $routes = $this->getCollector(); + public function testGroupGetsSanitized() + { + $routes = $this->getCollector(); - $routes->group('