From 1b0e1c332ad6edd187013f6d6469025f70ffea0e Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Wed, 18 Nov 2026 18:12:04 +0800 Subject: [PATCH 1/4] chore: analyse the PHP samples of the user guide with PHPStan --- .github/workflows/test-phpstan.yml | 9 ++ admin/docs-phpstan-baseline.php | 176 +++++++++++++++++++++++++++++ admin/lint-docs-samples.php | 142 +++++++++++++++++++++-- contributing/documentation.md | 9 +- 4 files changed, 327 insertions(+), 9 deletions(-) create mode 100644 admin/docs-phpstan-baseline.php diff --git a/.github/workflows/test-phpstan.yml b/.github/workflows/test-phpstan.yml index d16ab6d98a27..61df5f0a2f59 100644 --- a/.github/workflows/test-phpstan.yml +++ b/.github/workflows/test-phpstan.yml @@ -15,6 +15,9 @@ on: - composer.json - phpstan.dist.neon - phpstan-baseline.php + - 'docs/**' + - 'admin/lint-docs-samples.php' + - 'admin/docs-phpstan-baseline.php' - '.github/workflows/test-phpstan.yml' push: @@ -29,6 +32,9 @@ on: - composer.json - phpstan.dist.neon - phpstan-baseline.php + - 'docs/**' + - 'admin/lint-docs-samples.php' + - 'admin/docs-phpstan-baseline.php' - '.github/workflows/test-phpstan.yml' concurrency: @@ -89,3 +95,6 @@ jobs: - name: Run static analysis run: composer phpstan:check + + - name: Run static analysis on the user guide samples + run: php admin/lint-docs-samples.php --phpstan diff --git a/admin/docs-phpstan-baseline.php b/admin/docs-phpstan-baseline.php new file mode 100644 index 000000000000..14d7f1678c70 --- /dev/null +++ b/admin/docs-phpstan-baseline.php @@ -0,0 +1,176 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +/** + * PHPStan exceptions for the PHP samples of the user guide. + * + * An entry is a page relative to the project root, for all of its samples, or `page:line`, for the sample + * whose opening ```php fence is on that line. + * + * - `excludePaths`: samples that are skipped, for errors that PHPStan does not allow to be ignored. + * - `ignoreErrors`: an error identifier, optionally narrowed by a `message` pattern, ignored in the samples of the + * listed `paths` or, without them, in all samples. + * + * @return array{ + * excludePaths: list, + * ignoreErrors: list}> + * } + */ +return [ + 'excludePaths' => [ + 'docs/cli/cli_signals.md:201', + 'docs/cli/cli_signals.md:413', + 'docs/cli/cli_signals.md:608', + 'docs/cli/cli_signals.md:654', + 'docs/cli/cli_signals.md:700', + 'docs/concepts/services.md:135', + 'docs/dbmgmt/migration.md:78', + 'docs/extending/core_classes.md:64', + 'docs/guides/api/controller.md:21', + 'docs/guides/first-app/static_pages.md:55', + 'docs/incoming/filters.md:18', + 'docs/incoming/filters.md:59', + 'docs/installation/upgrade_412.md:37', + 'docs/libraries/encryption.md:182', + 'docs/models/entities.md:659', + 'docs/models/model.md:73', + 'docs/models/model.md:562', + 'docs/testing/fabricator.md:9', + ], + 'ignoreErrors' => [ + // Samples are fragments: they leave out code, and the classes and functions that they refer to. + ['identifier' => 'class.notFound'], + ['identifier' => 'codeigniter.configArgumentInstanceof'], + ['identifier' => 'codeigniter.configArgumentType'], + ['identifier' => 'codeigniter.modelArgumentType'], + ['identifier' => 'codeigniter.unknownServiceMethod'], + ['identifier' => 'expr.resultUnused'], + ['identifier' => 'function.notFound'], + ['identifier' => 'method.unused'], + ['identifier' => 'variable.undefined'], + + // A class that a sample declares, and that several samples declare differently, is resolved to one of them. + [ + 'identifier' => 'method.notFound', + 'message' => '#^Call to an undefined method (App\\\\|Tests\\\\|SampleCommand::|MyRules::|MyTestClass::)#', + ], + [ + 'identifier' => 'property.notFound', + 'message' => '#^Access to an undefined property (App\\\\|Config\\\\|SampleCommand::)#', + ], + + // A value that PHP coerces, a function or class that the sample does not define, or the Session of CodeIgniter 3. + [ + 'identifier' => 'argument.type', + 'paths' => [ + 'docs/cli/cli_commands.md:78', + 'docs/cli/cli_library.md:240', + 'docs/extending/events.md:25', + 'docs/extending/events.md:50', + 'docs/extending/events.md:89', + 'docs/outgoing/api_responses.md:510', + 'docs/outgoing/api_transformers.md:118', + 'docs/outgoing/api_transformers.md:415', + 'docs/testing/controllers.md:285', + ], + ], + [ + 'identifier' => 'method.nonObject', + 'paths' => [ + 'docs/outgoing/api_transformers.md:235', + 'docs/outgoing/api_transformers.md:309', + 'docs/outgoing/api_transformers.md:684', + 'docs/outgoing/view_cells.md:324', + 'docs/outgoing/view_cells.md:347', + ], + ], + [ + 'identifier' => 'property.notFound', + 'paths' => ['docs/installation/upgrade_sessions.md:39'], + ], + + // Samples that write the array of CodeIgniter 3 or of a configuration in the way that the page describes. + [ + 'identifier' => 'variable.implicitArray', + 'paths' => [ + 'docs/general/configuration.md:245', + 'docs/incoming/routing.md:621', + 'docs/installation/upgrade_localization.md:45', + ], + ], + + // Samples that show alternatives one after the other, or code that a sample does not complete. + [ + 'identifier' => 'catch.neverThrown', + 'paths' => ['docs/cli/cli_commands.md:144', 'docs/general/logging.md:125'], + ], + [ + 'identifier' => 'deadCode.unreachable', + 'paths' => [ + 'docs/installation/upgrade_localization.md:61', + 'docs/outgoing/localization.md:271', + 'docs/outgoing/localization.md:310', + 'docs/outgoing/localization.md:377', + 'docs/outgoing/response.md:31', + 'docs/outgoing/view_parser.md:273', + ], + ], + [ + 'identifier' => 'if.alwaysFalse', + 'paths' => ['docs/cli/cli_signals.md:527'], + ], + [ + 'identifier' => 'outOfClass.self', + 'paths' => ['docs/testing/overview.md:293'], + ], + [ + 'identifier' => 'property.onlyWritten', + 'paths' => ['docs/installation/deployment.md:78'], + ], + + // Samples that use a class that the samples declare differently, or a name that they do not define. + [ + 'identifier' => 'new.noConstructor', + 'paths' => [ + 'docs/concepts/services.md:150', + 'docs/concepts/services.md:204', + 'docs/extending/core_classes.md:81', + 'docs/testing/fabricator.md:50', + ], + ], + [ + 'identifier' => 'parameterByRef.type', + 'paths' => ['docs/libraries/validation.md:1041'], + ], + [ + 'identifier' => 'return.type', + 'paths' => [ + 'docs/concepts/services.md:150', + 'docs/concepts/services.md:204', + 'docs/extending/core_classes.md:81', + ], + ], + [ + 'identifier' => 'property.defaultValue', + 'paths' => ['docs/outgoing/view_parser.md:518', 'docs/testing/database.md:73'], + ], + [ + 'identifier' => 'property.nonObject', + 'paths' => ['docs/testing/fabricator.md:87'], + ], + [ + 'identifier' => 'property.protected', + 'paths' => ['docs/libraries/time.md:417'], + ], + ], +]; diff --git a/admin/lint-docs-samples.php b/admin/lint-docs-samples.php index 0b9d6a695403..b186a61b619c 100644 --- a/admin/lint-docs-samples.php +++ b/admin/lint-docs-samples.php @@ -20,7 +20,12 @@ * rewritten in place. Otherwise, nothing is changed, and the script exits * with 1 when a sample needs fixing. * - * Usage: php admin/lint-docs-samples.php [--fix] [--docs=] + * With --phpstan, the samples are analysed by PHPStan instead, using the + * configuration at the project root unless --phpstan-config is given, and + * each error is reported against its page and line. The samples that are + * excluded, and the errors that are ignored, are listed in admin/docs-phpstan-baseline.php. + * + * Usage: php admin/lint-docs-samples.php [--fix | --phpstan [--phpstan-config=]] [--docs=] */ /** @@ -103,13 +108,105 @@ function find_samples(array $lines): array function remove_directory(string $directory): void { foreach (glob($directory . '/*') ?: [] as $file) { - unlink($file); + is_dir($file) ? remove_directory($file) : unlink($file); } rmdir($directory); } -$options = getopt('', ['fix', 'docs::']); +/** + * @param list $found + * @param array $files + */ +function analyse_with_phpstan(string $root, string $work, array $found, array $files, ?string $config): int +{ + foreach (['phpstan.neon', 'phpstan.neon.dist', 'phpstan.dist.neon'] as $name) { + if ($config === null && is_file($root . '/' . $name)) { + $config = $root . '/' . $name; + } + } + + $pageSamples = []; + $fenceSamples = []; + + foreach ($found as $id => $sample) { + $page = substr($sample['page'], strlen($root) + 1); + + $pageSamples[$page][] = $files[$id]; + $fenceSamples[$page . ':' . $sample['start']] = $files[$id]; + } + + $unmatched = []; + + $expand = static function (array $entries) use ($pageSamples, $fenceSamples, &$unmatched): array { + $resolved = []; + + foreach ($entries as $entry) { + $samples = isset($fenceSamples[$entry]) ? [$fenceSamples[$entry]] : ($pageSamples[$entry] ?? []); + + if ($samples === []) { + $unmatched[] = $entry; + } + + array_push($resolved, ...$samples); + } + + return $resolved; + }; + + /** @var array{excludePaths: list, ignoreErrors: list}>} $exceptions */ + $exceptions = require __DIR__ . '/docs-phpstan-baseline.php'; + $ignoreErrors = []; + + foreach ($exceptions['ignoreErrors'] as $ignore) { + if (! isset($ignore['paths'])) { + $ignoreErrors[] = $ignore; + + continue; + } + + if (($ignore['paths'] = $expand($ignore['paths'])) !== []) { + $ignoreErrors[] = $ignore; + } + } + + file_put_contents($work . '/phpstan.neon', sprintf( + "includes:\n - %s\n\nparameters: %s\n", + $config, + json_encode([ + 'excludePaths' => ['analyse' => $expand($exceptions['excludePaths'])], + 'ignoreErrors' => $ignoreErrors, + ], JSON_UNESCAPED_SLASHES), + )); + + exec(sprintf( + 'cd %s && %s %s analyse --configuration=%s --ansi --no-progress --memory-limit=1G %s 2>&1', + escapeshellarg($root), + escapeshellarg(PHP_BINARY), + escapeshellarg($root . '/vendor/bin/phpstan'), + escapeshellarg($work . '/phpstan.neon'), + escapeshellarg($work), + ), $output, $status); + + $pages = []; + + foreach ($found as $id => $sample) { + $page = substr($sample['page'], strlen($root) + 1); + + $pages[$files[$id]] = $sample['page']; + $pages[substr($files[$id], strlen($work) + 1)] = $page; + } + + echo strtr(implode("\n", $output), $pages), "\n"; + + foreach (array_unique($unmatched) as $entry) { + printf("\n%s is listed in admin/docs-phpstan-baseline.php, but it matches no PHP sample.\n", $entry); + } + + return $status !== 0 ? $status : ($unmatched === [] ? 0 : 1); +} + +$options = getopt('', ['fix', 'phpstan', 'phpstan-config:', 'docs::']); $fix = isset($options['fix']); $root = dirname(__DIR__); $docs = rtrim(is_string($options['docs'] ?? null) ? $options['docs'] : $root . '/docs', '/'); @@ -125,12 +222,43 @@ function remove_directory(string $directory): void } } -$work = sys_get_temp_dir() . '/docs-samples-' . getmypid(); -mkdir($work); +$phpstan = isset($options['phpstan']); +$work = $phpstan ? $root . '/build/docs-samples' : sys_get_temp_dir() . '/docs-samples-' . getmypid(); + +if (is_dir($work)) { + remove_directory($work); +} + +mkdir($work, 0777, true); foreach ($found as $id => $sample) { - $files[$id] = sprintf('%s/%05d.php', $work, $id); - file_put_contents($files[$id], $sample['code']); + if (! $phpstan) { + $files[$id] = sprintf('%s/%05d.php', $work, $id); + file_put_contents($files[$id], $sample['code']); + + continue; + } + + // Padding after the opening tag keeps the lines of the sample on the lines of its page. + $files[$id] = sprintf('%s/%s@%d.php', $work, substr($sample['page'], strlen($root) + 1), $sample['start']); + $padded = preg_replace('/^<\?php\n/', '` on the line above its fence. +A PHP sample that starts with `` on the line above its fence. + +These are also analysed by PHPStan, with the configuration at the root of the project, +when you run `php admin/lint-docs-samples.php --phpstan`. Each error is reported against its page and line. +A sample that PHPStan cannot analyse, or an error that a sample cannot avoid, is listed in +**admin/docs-phpstan-baseline.php**, by page or by the line of the opening fence of the sample. ### CLI Command From 53ea1874fb41debeb9922a7128e541fbff3b4388 Mon Sep 17 00:00:00 2001 From: "John Paul E. Balandan, CPA" Date: Wed, 18 Nov 2026 18:12:18 +0800 Subject: [PATCH 2/4] docs: fix the PHP samples reported by PHPStan --- docs/cli/cli_controllers.md | 2 +- docs/cli/cli_generators.md | 3 ++ docs/concepts/factories.md | 12 ++++-- docs/concepts/services.md | 12 +++--- docs/database/configuration.md | 26 ++++++++++-- docs/database/query_builder.md | 24 +++++------ docs/database/results.md | 16 +++---- docs/extending/basecontroller.md | 2 +- docs/extending/core_classes.md | 2 +- docs/general/configuration.md | 12 ++++-- docs/general/errors.md | 5 ++- docs/general/helpers.md | 10 ++++- docs/general/logging.md | 12 ++++-- docs/general/managing_apps.md | 2 +- docs/general/modules.md | 12 +++++- docs/guides/api/controller.md | 26 +++++++----- docs/guides/api/database-setup.md | 2 +- docs/guides/first-app/create_news_items.md | 7 +++- docs/guides/first-app/news_section.md | 14 +++---- docs/guides/first-app/static_pages.md | 8 ++-- docs/helpers/test_helper.md | 2 +- docs/incoming/auto_routing_improved.md | 12 +++--- docs/incoming/controller_attributes.md | 27 ++++++------ docs/incoming/controllers.md | 28 ++++++------- docs/incoming/filters.md | 41 +++++++++++++++++- docs/incoming/incomingrequest.md | 4 +- docs/incoming/routing.md | 4 +- docs/installation/deployment.md | 2 +- docs/installation/upgrade_412.md | 4 +- docs/installation/upgrade_415.md | 5 ++- docs/installation/upgrade_460.md | 3 ++ docs/installation/upgrade_configuration.md | 4 +- docs/installation/upgrade_controllers.md | 2 +- docs/installation/upgrade_file_upload.md | 8 ++-- docs/installation/upgrade_models.md | 4 +- docs/installation/upgrade_security.md | 8 +++- docs/installation/upgrade_validations.md | 2 +- docs/installation/worker_mode.md | 7 +++- docs/libraries/caching.md | 22 ++++++++-- docs/libraries/cookies.md | 14 ------- docs/libraries/cors.md | 11 +++++ docs/libraries/email.md | 10 +++-- docs/libraries/encryption.md | 5 ++- docs/libraries/file_collections.md | 2 +- docs/libraries/honeypot.md | 8 +++- docs/libraries/pagination.md | 21 +++++++--- docs/libraries/security.md | 35 ++++++++++++---- docs/libraries/throttler.md | 18 +++++--- docs/libraries/time.md | 6 +-- docs/libraries/uploaded_files.md | 4 +- docs/libraries/validation.md | 49 ++++++++++++++++------ docs/models/entities.md | 6 +-- docs/models/model.md | 33 +++++++++++---- docs/outgoing/api_responses.md | 22 +++++++--- docs/outgoing/api_transformers.md | 29 +++++++++++-- docs/outgoing/localization.md | 8 +++- docs/outgoing/view_cells.md | 38 +++++++++++------ docs/outgoing/view_layouts.md | 2 +- docs/outgoing/view_parser.md | 2 +- docs/outgoing/views.md | 14 ++++--- docs/testing/controllers.md | 6 +-- docs/testing/debugging.md | 7 +++- docs/testing/fabricator.md | 28 ++++++++++--- docs/testing/overview.md | 10 ++--- 64 files changed, 545 insertions(+), 241 deletions(-) diff --git a/docs/cli/cli_controllers.md b/docs/cli/cli_controllers.md index 8a17e4d1209a..aea4d7312f8f 100644 --- a/docs/cli/cli_controllers.md +++ b/docs/cli/cli_controllers.md @@ -20,7 +20,7 @@ use CodeIgniter\Controller; class Tools extends Controller { - public function message($to = 'World') + public function message(string $to = 'World'): string { return "Hello {$to}!" . PHP_EOL; } diff --git a/docs/cli/cli_generators.md b/docs/cli/cli_generators.md index a5883283baa8..6ae0ea802fdd 100644 --- a/docs/cli/cli_generators.md +++ b/docs/cli/cli_generators.md @@ -321,6 +321,9 @@ use CodeIgniter\Config\BaseConfig; class Generators extends BaseConfig { + /** + * @var array|string> + */ public array $views = [ // .. 'make:awesome-command' => 'App\Commands\Generators\Views\awesomecommand.tpl.php', diff --git a/docs/concepts/factories.md b/docs/concepts/factories.md index 474eceba3ffd..a9e49ece9258 100644 --- a/docs/concepts/factories.md +++ b/docs/concepts/factories.md @@ -58,7 +58,7 @@ use CodeIgniter\Config\Factories; class SomeOtherClass { - public function someFunction() + public function someFunction(): void { $users = Factories::models('UserModel'); @@ -214,7 +214,10 @@ use CodeIgniter\Filters\FilterInterface; class Factory extends BaseFactory { - public $filters = [ + /** + * @var array + */ + public array $filters = [ 'instanceOf' => FilterInterface::class, ]; } @@ -239,7 +242,10 @@ use CodeIgniter\Config\Factory as BaseFactory; class Factory extends BaseFactory { - public $library = [ + /** + * @var array + */ + public array $library = [ 'path' => 'Libraries', ]; } diff --git a/docs/concepts/services.md b/docs/concepts/services.md index ac00a9d76cad..22cc3e24967f 100644 --- a/docs/concepts/services.md +++ b/docs/concepts/services.md @@ -171,7 +171,7 @@ class Services extends BaseService { // ... - public static function routes() + public static function routes(): \CodeIgniter\Router\RouteCollection { return new MyRouteCollection(static::locator(), config('Modules')); } @@ -196,9 +196,9 @@ class Services extends BaseService { // ... - public static function renderer($viewPath = APPPATH . 'views/') + public static function renderer(string $viewPath = APPPATH . 'views/'): View { - return new View($viewPath); + return new View(config('View'), $viewPath); } } ``` @@ -229,7 +229,7 @@ class Services extends BaseService { // ... - public static function routes($getShared = true) + public static function routes(bool $getShared = true): \CodeIgniter\Router\RouteCollection { if ($getShared) { return static::getSharedInstance('routes'); @@ -261,9 +261,9 @@ use CodeIgniter\Config\BaseService; class Services extends BaseService { - public static function postManager() + public static function postManager(): \Blog\Libraries\PostManager { - // ... + return new \Blog\Libraries\PostManager(); } } ``` diff --git a/docs/database/configuration.md b/docs/database/configuration.md index 4c7ba25ac331..c33fa4f28512 100644 --- a/docs/database/configuration.md +++ b/docs/database/configuration.md @@ -22,6 +22,9 @@ class Database extends Config { // ... + /** + * @var array + */ public array $default = [ 'DSN' => '', 'hostname' => 'localhost', @@ -112,6 +115,9 @@ class Database extends Config { // ... + /** + * @var array + */ public array $default = [ // ... 'failover' => [ @@ -172,6 +178,9 @@ class Database extends Config { // ... + /** + * @var array + */ public array $test = [ 'DSN' => '', 'hostname' => 'localhost', @@ -234,9 +243,20 @@ use CodeIgniter\Database\Config; class Database extends Config { // ... - public $development = [/* ... */]; - public $test = [/* ... */]; - public $production = [/* ... */]; + /** + * @var array + */ + public array $development = [/* ... */]; + + /** + * @var array + */ + public array $test = [/* ... */]; + + /** + * @var array + */ + public array $production = [/* ... */]; public function __construct() { diff --git a/docs/database/query_builder.md b/docs/database/query_builder.md index eb9ffa4a08a7..9bd7a62389f9 100644 --- a/docs/database/query_builder.md +++ b/docs/database/query_builder.md @@ -1281,9 +1281,9 @@ namespace App\Libraries; class MyClass { - public $title = 'My Title'; - public $content = 'My Content'; - public $date = 'My Date'; + public string $title = 'My Title'; + public string $content = 'My Content'; + public string $date = 'My Date'; } ``` @@ -1468,9 +1468,9 @@ namespace App\Libraries; class MyClass { - public $email = 'ahmadinejad@example.com'; - public $name = 'Ahmadinejad'; - public $country = 'Iran'; + public string $email = 'ahmadinejad@example.com'; + public string $name = 'Ahmadinejad'; + public string $country = 'Iran'; } ``` @@ -1794,9 +1794,9 @@ namespace App\Libraries; class MyClass { - public $title = 'My Title'; - public $content = 'My Content'; - public $date = 'My Date'; + public string $title = 'My Title'; + public string $content = 'My Content'; + public string $date = 'My Date'; } ``` @@ -1842,9 +1842,9 @@ namespace App\Libraries; class MyClass { - public $title = 'My Title'; - public $content = 'My Content'; - public $date = 'My Date'; + public string $title = 'My Title'; + public string $content = 'My Content'; + public string $date = 'My Date'; } ``` diff --git a/docs/database/results.md b/docs/database/results.md index 16d58cd944b8..c12a31d0da6f 100644 --- a/docs/database/results.md +++ b/docs/database/results.md @@ -228,29 +228,31 @@ namespace App\Entities; class User { - public $id; - public $email; - public $username; + public int $id; + public string $email; + public string $username; - protected $lastLogin; + protected DateTime $lastLogin; - public function lastLogin($format) + public function lastLogin(string $format): string { return $this->lastLogin->format($format); } - public function __set($name, $value) + public function __set(string $name, mixed $value): void { if ($name === 'lastLogin') { $this->lastLogin = DateTime::createFromFormat('!U', $value); } } - public function __get($name) + public function __get(string $name): mixed { if (isset($this->{$name})) { return $this->{$name}; } + + return null; } } ``` diff --git a/docs/extending/basecontroller.md b/docs/extending/basecontroller.md index c476471d23fb..3ff12c822580 100644 --- a/docs/extending/basecontroller.md +++ b/docs/extending/basecontroller.md @@ -51,7 +51,7 @@ abstract class BaseController extends Controller // ... /** - * @var \CodeIgniter\Session\Session; + * @var \CodeIgniter\Session\Session */ protected $session; diff --git a/docs/extending/core_classes.md b/docs/extending/core_classes.md index d04088253ad0..7133482ef091 100644 --- a/docs/extending/core_classes.md +++ b/docs/extending/core_classes.md @@ -88,7 +88,7 @@ use CodeIgniter\Config\BaseService; class Services extends BaseService { - public static function routes(bool $getShared = true) + public static function routes(bool $getShared = true): \CodeIgniter\Router\RouteCollection { if ($getShared) { return static::getSharedInstance('routes'); diff --git a/docs/general/configuration.md b/docs/general/configuration.md index 66a1948abe94..5db2cf23e3c3 100644 --- a/docs/general/configuration.md +++ b/docs/general/configuration.md @@ -89,8 +89,8 @@ use CodeIgniter\Config\BaseConfig; class CustomClass extends BaseConfig { - public $siteName = 'My Great Site'; - public $siteEmail = 'webmaster@example.com'; + public string $siteName = 'My Great Site'; + public string $siteEmail = 'webmaster@example.com'; // ... } ``` @@ -302,6 +302,9 @@ namespace CodeIgniter\Shield\Config; class Registrar { + /** + * @return array> + */ public static function Pager(): array { return [ @@ -326,7 +329,7 @@ A configuration file can also specify any number of registrars explicitly. This namespace Config; -// ... +use CodeIgniter\Config\BaseConfig; class MyConfig extends BaseConfig { @@ -370,6 +373,9 @@ namespace App\Models; class RegionalSales { + /** + * @return array + */ public static function MySalesConfig(): array { return [ diff --git a/docs/general/errors.md b/docs/general/errors.md index 0293db232230..519ebdbe496a 100644 --- a/docs/general/errors.md +++ b/docs/general/errors.md @@ -115,6 +115,9 @@ use CodeIgniter\Config\BaseConfig; class Exceptions extends BaseConfig { // ... + /** + * @var list + */ public array $ignoreCodes = [404]; // ... } @@ -170,7 +173,7 @@ class Logger extends BaseConfig { // ... // This must contain the log level (5 for LogLevel::WARNING) corresponding to $deprecationLogLevel. - public $threshold = (ENVIRONMENT === 'production') ? 4 : 9; + public int $threshold = (ENVIRONMENT === 'production') ? 4 : 9; // ... } ``` diff --git a/docs/general/helpers.md b/docs/general/helpers.md index 23aa2d6631a9..49b794d8d9d6 100644 --- a/docs/general/helpers.md +++ b/docs/general/helpers.md @@ -164,7 +164,10 @@ For example, to extend the native **Array Helper** you'll create a file named ** $haystack + */ +function any_in_array(mixed $needle, array $haystack): bool { $needle = is_array($needle) ? $needle : [$needle]; @@ -178,7 +181,10 @@ function any_in_array($needle, $haystack) } // random_element() is included in Array Helper, so it overrides the native function -function random_element($array) +/** + * @param list $array + */ +function random_element(array $array): mixed { shuffle($array); diff --git a/docs/general/logging.md b/docs/general/logging.md index f7b152f89ce6..cbe956aa66cd 100644 --- a/docs/general/logging.md +++ b/docs/general/logging.md @@ -42,7 +42,7 @@ use CodeIgniter\Config\BaseConfig; class Logger extends BaseConfig { - public $threshold = 5; + public int $threshold = 5; // ... } @@ -62,7 +62,10 @@ use CodeIgniter\Config\BaseConfig; class Logger extends BaseConfig { // Log only debug and info type messages - public $threshold = [5, 8]; + /** + * @var list + */ + public array $threshold = [5, 8]; // ... } @@ -87,7 +90,10 @@ use CodeIgniter\Config\BaseConfig; class Logger extends BaseConfig { - public $handlers = [ + /** + * @var array> + */ + public array $handlers = [ // File Handler 'CodeIgniter\Log\Handlers\FileHandler' => [ 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'], diff --git a/docs/general/managing_apps.md b/docs/general/managing_apps.md index 442fa576508a..0f343c59c1fb 100644 --- a/docs/general/managing_apps.md +++ b/docs/general/managing_apps.md @@ -89,7 +89,7 @@ class Paths { // ... - public $systemDirectory = __DIR__ . '/../../../vendor/codeigniter4/framework/system'; + public string $systemDirectory = __DIR__ . '/../../../vendor/codeigniter4/framework/system'; // ... } diff --git a/docs/general/modules.md b/docs/general/modules.md index e692e10c9873..a19588c06438 100644 --- a/docs/general/modules.md +++ b/docs/general/modules.md @@ -136,7 +136,10 @@ class Modules extends BaseModules { // ... - public $composerPackages = [ + /** + * @var array{only?: list, exclude?: list} + */ + public array $composerPackages = [ 'only' => [ // List up all packages to auto-discover 'codeigniter4/shield', @@ -160,7 +163,10 @@ class Modules extends BaseModules { // ... - public $composerPackages = [ + /** + * @var array{only?: list, exclude?: list} + */ + public array $composerPackages = [ 'exclude' => [ // List up packages to exclude. 'pestphp/pest', @@ -222,6 +228,8 @@ When working with modules, it can be a problem if the routes in the application { /** * Registers the Shield filters. + * + * @return array> */ public static function Filters(): array { diff --git a/docs/guides/api/controller.md b/docs/guides/api/controller.md index b4e8e027a6e6..cd48127040a5 100644 --- a/docs/guides/api/controller.md +++ b/docs/guides/api/controller.md @@ -4,7 +4,7 @@ In this chapter, we build the API endpoints to expose your `books` table through ## What is RESTful? -RESTful APIs use standard HTTP verbs (`GET`, `POST`, `PUT`, `DELETE`) to perform actions on resources identified by URIs. This approach makes APIs predictable and easy to use. There can be much debate on some of the finer points of what makes a REST API, but following these basics can get it close enough for many uses. By using auto-routing and the `Api\ResponseTrait`, CodeIgniter makes it simple to create RESTful endpoints. +RESTful APIs use standard HTTP verbs (`GET`, `POST`, `PUT`, `DELETE`) to perform actions on resources identified by URIs. This approach makes APIs predictable and easy to use. There can be much debate on some of the finer points of what makes a REST API, but following these basics can get it close enough for many uses. By using auto-routing and the `API\ResponseTrait`, CodeIgniter makes it simple to create RESTful endpoints. ## Generate the controller @@ -25,6 +25,7 @@ namespace App\Controllers\Api; use App\Controllers\BaseController; use CodeIgniter\API\ResponseTrait; +use CodeIgniter\HTTP\ResponseInterface; class Books extends BaseController { @@ -36,7 +37,7 @@ class Books extends BaseController * and * GET /api/books/{id} */ - public function getIndex(?int $id = null) + public function getIndex(?int $id = null): ResponseInterface { } @@ -45,7 +46,7 @@ class Books extends BaseController * * PUT /api/books/{id} */ - public function putIndex(int $id) + public function putIndex(int $id): ResponseInterface { } @@ -54,7 +55,7 @@ class Books extends BaseController * * POST /api/books */ - public function postIndex() + public function postIndex(): ResponseInterface { } @@ -63,7 +64,7 @@ class Books extends BaseController * * DELETE /api/books/{id} */ - public function deleteIndex(int $id) + public function deleteIndex(int $id): ResponseInterface { } } @@ -106,9 +107,14 @@ class BookTransformer extends BaseTransformer ]; } + /** + * @param array $book + * + * @return array|null + */ protected function includeAuthor(array $book): ?array { - if (empty($book['author_id']) || empty($book['author_name'])) { + if (! isset($book['author_id'], $book['author_name'])) { return null; } @@ -176,7 +182,7 @@ use CodeIgniter\Model; class BookModel extends Model { - public function withAuthorInfo() + public function withAuthorInfo(): static { return $this ->select('books.*, authors.name as author_name') @@ -249,7 +255,7 @@ namespace App\Controllers\Api; use App\Controllers\BaseController; use App\Transformers\BookTransformer; -use CodeIgniter\Api\ResponseTrait; +use CodeIgniter\API\ResponseTrait; use CodeIgniter\HTTP\ResponseInterface; class Books extends BaseController @@ -305,7 +311,7 @@ class Books extends BaseController $model = model('BookModel'); - if (! $model->find($id)) { + if ($model->find($id) === null) { return $this->failNotFound('Book not found'); } @@ -352,7 +358,7 @@ class Books extends BaseController { $model = model('BookModel'); - if (! $model->find($id)) { + if ($model->find($id) === null) { return $this->failNotFound('Book not found'); } diff --git a/docs/guides/api/database-setup.md b/docs/guides/api/database-setup.md index 86e0adf05660..1c2bb5155eb7 100644 --- a/docs/guides/api/database-setup.md +++ b/docs/guides/api/database-setup.md @@ -252,4 +252,4 @@ class BookModel extends Model This tells CodeIgniter which table to use and which fields can be mass-assigned. -In the next section, we'll use your new models to power a RESTful API controller. You'll build the `/api/books` endpoint and see how CodeIgniter's `Api\ResponseTrait` makes CRUD operations easy. +In the next section, we'll use your new models to power a RESTful API controller. You'll build the `/api/books` endpoint and see how CodeIgniter's `API\ResponseTrait` makes CRUD operations easy. diff --git a/docs/guides/first-app/create_news_items.md b/docs/guides/first-app/create_news_items.md index a2d4fe267ca5..56dee8844863 100644 --- a/docs/guides/first-app/create_news_items.md +++ b/docs/guides/first-app/create_news_items.md @@ -19,6 +19,9 @@ class Filters extends BaseConfig { // ... + /** + * @var array> + */ public array $methods = [ 'POST' => ['csrf'], ]; @@ -118,7 +121,7 @@ class News extends BaseController { // ... - public function new() + public function new(): string { helper('form'); @@ -155,7 +158,7 @@ class News extends BaseController { // ... - public function create() + public function create(): string { helper('form'); diff --git a/docs/guides/first-app/news_section.md b/docs/guides/first-app/news_section.md index a427fb318555..aa229b23c84f 100644 --- a/docs/guides/first-app/news_section.md +++ b/docs/guides/first-app/news_section.md @@ -131,18 +131,18 @@ use App\Models\NewsModel; class News extends BaseController { - public function index() + public function index(): void { $model = model(NewsModel::class); - $data['news_list'] = $model->getNews(); + $data = ['news_list' => $model->getNews()]; } - public function show(?string $slug = null) + public function show(?string $slug = null): void { $model = model(NewsModel::class); - $data['news'] = $model->getNews($slug); + $data = ['news' => $model->getNews($slug)]; } } ``` @@ -168,7 +168,7 @@ use App\Models\NewsModel; class News extends BaseController { - public function index() + public function index(): string { $model = model(NewsModel::class); @@ -238,11 +238,11 @@ class News extends BaseController { // ... - public function show(?string $slug = null) + public function show(?string $slug = null): string { $model = model(NewsModel::class); - $data['news'] = $model->getNews($slug); + $data = ['news' => $model->getNews($slug)]; if ($data['news'] === null) { throw new PageNotFoundException('Cannot find the news item: ' . $slug); diff --git a/docs/guides/first-app/static_pages.md b/docs/guides/first-app/static_pages.md index a2628e804e3d..bec64374863b 100644 --- a/docs/guides/first-app/static_pages.md +++ b/docs/guides/first-app/static_pages.md @@ -59,12 +59,12 @@ namespace App\Controllers; class Pages extends BaseController { - public function index() + public function index(): string { return view('welcome_message'); } - public function view(string $page = 'home') + public function view(string $page = 'home'): string { // ... } @@ -134,14 +134,14 @@ class Pages extends BaseController { // ... - public function view(string $page = 'home') + public function view(string $page = 'home'): string { if (! is_file(APPPATH . 'Views/pages/' . $page . '.php')) { // Whoops, we don't have a page for that! throw new PageNotFoundException($page); } - $data['title'] = ucfirst($page); // Capitalize the first letter + $data = ['title' => ucfirst($page)]; // Capitalize the first letter return view('templates/header', $data) . view('pages/' . $page) diff --git a/docs/helpers/test_helper.md b/docs/helpers/test_helper.md index 238a66c2a181..c1e4e294322a 100644 --- a/docs/helpers/test_helper.md +++ b/docs/helpers/test_helper.md @@ -38,7 +38,7 @@ use CodeIgniter\Test\CIUnitTestCase; final class MyTestClass extends CIUnitTestCase { - public function testUserAccess() + public function testUserAccess(): void { $user = fake('App\Models\UserModel'); diff --git a/docs/incoming/auto_routing_improved.md b/docs/incoming/auto_routing_improved.md index f3bc41acf561..66cf871a7650 100644 --- a/docs/incoming/auto_routing_improved.md +++ b/docs/incoming/auto_routing_improved.md @@ -93,7 +93,7 @@ namespace App\Controllers; class HelloWorld extends BaseController { - public function getIndex() + public function getIndex(): string { return 'Hello World!'; } @@ -215,12 +215,12 @@ namespace App\Controllers; class HelloWorld extends BaseController { - public function getIndex() + public function getIndex(): string { return 'Hello World!'; } - public function getComment() + public function getComment(): string { return 'I am not flat!'; } @@ -254,7 +254,7 @@ namespace App\Controllers; class Products extends BaseController { - public function getShoes($type, $id) + public function getShoes(string $type, string $id): string { return $type . $id; } @@ -288,7 +288,7 @@ namespace App\Controllers; class Product extends BaseController { - public function getIndex($id = null, $action = '') + public function getIndex(?string $id = null, string $action = ''): void { // ... } @@ -321,7 +321,7 @@ use App\Controllers\BaseController; class Home extends BaseController { - public function getIndex($id = null) + public function getIndex(?string $id = null): void { // ... } diff --git a/docs/incoming/controller_attributes.md b/docs/incoming/controller_attributes.md index aecc5ed8ce9f..b21ce3c2c711 100644 --- a/docs/incoming/controller_attributes.md +++ b/docs/incoming/controller_attributes.md @@ -16,7 +16,7 @@ use CodeIgniter\Router\Attributes\Filter; #[Filter(by: 'auth')] class AdminController extends BaseController { - public function index() + public function index(): string { return view('welcome_message'); } @@ -38,7 +38,7 @@ use CodeIgniter\Router\Attributes\Filter; class AdminController extends BaseController { #[Filter(by: 'permission', having: ['users.manage'])] - public function users() + public function users(): void { // Will have 'group' filter with ['admin', 'superadmin'] // and 'permission' filter with ['users.manage'] @@ -69,20 +69,20 @@ class HomeController extends BaseController { // Apply the filter by it's alias name #[Filter(by: 'csrf')] - public function index() + public function index(): void { } // Apply a filter with arguments #[Filter(by: 'throttle', having: ['60', '1'])] - public function api() + public function api(): void { } // Multiple filters can be applied by repeating the attribute #[Filter(by: 'auth')] #[Filter(by: 'csrf')] - public function admin() + public function admin(): void { } } @@ -111,19 +111,19 @@ class HomeController extends BaseController { // Restrict access by hostname #[Restrict(hostname: 'localhost')] - public function index() + public function index(): void { } // Multiple allowed hosts #[Restrict(hostname: ['localhost', '127.0.0.1', 'dev.example.com'])] - public function devOnly() + public function devOnly(): void { } // Restrict to subdomain, e.g. admin.example.com #[Restrict(subdomain: 'admin')] - public function deleteItem($id) + public function deleteItem(int $id): void { } } @@ -144,14 +144,14 @@ class HomeController extends BaseController { // Cache this method's response for 2 hours #[Cache(for: 2 * HOUR)] - public function index() + public function index(): string { return view('welcome_message'); } // Custom cache key #[Cache(for: 10 * MINUTE, key: 'custom_cache_key')] - public function custom() + public function custom(): string { return 'This response is cached with a custom key for 10 minutes.'; } @@ -225,6 +225,7 @@ namespace App\Controllers; use App\Attributes\AddHeader; use CodeIgniter\Controller; +use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Router\Attributes\Cache; class Api extends Controller @@ -233,7 +234,7 @@ class Api extends Controller * Add a single custom header */ #[AddHeader('X-API-Version', '2.0')] - public function userInfo() + public function userInfo(): ResponseInterface { return $this->response->setJSON([ 'name' => 'John Doe', @@ -248,7 +249,7 @@ class Api extends Controller #[AddHeader('X-API-Version', '2.0')] #[AddHeader('X-Rate-Limit', '100')] #[AddHeader('X-Content-Source', 'cache')] - public function statistics() + public function statistics(): ResponseInterface { return $this->response->setJSON([ 'users' => 1500, @@ -263,7 +264,7 @@ class Api extends Controller */ #[AddHeader('X-Powered-By', 'My Custom API')] #[Cache(for: 3600)] - public function dashboard() + public function dashboard(): ResponseInterface { return $this->response->setJSON([ 'status' => 'operational', diff --git a/docs/incoming/controllers.md b/docs/incoming/controllers.md index ee358d9e8c4d..c856afce941f 100644 --- a/docs/incoming/controllers.md +++ b/docs/incoming/controllers.md @@ -119,7 +119,7 @@ namespace App\Controllers; class StoreController extends BaseController { - public function product(int $id) + public function product(int $id): string { $data = [ 'id' => $id, @@ -137,7 +137,7 @@ class StoreController extends BaseController ]); } - // ... + return view('store/success'); } } ``` @@ -165,7 +165,7 @@ namespace App\Controllers; class UserController extends BaseController { - public function updateUser(int $userID) + public function updateUser(int $userID): string { if (! $this->validate([ 'email' => "required|is_unique[users.email,id,{$userID}]", @@ -182,7 +182,7 @@ class UserController extends BaseController // Get the validated data. $validData = $this->validator->getValidated(); - // ... + return view('users/success'); } } ``` @@ -202,7 +202,7 @@ namespace App\Controllers; class UserController extends BaseController { - public function updateUser(int $userID) + public function updateUser(int $userID): string { if (! $this->validate('userRules')) { // The validation failed. @@ -216,7 +216,7 @@ class UserController extends BaseController // Get the validated data. $validData = $this->validator->getValidated(); - // ... + return view('users/success'); } } ``` @@ -237,7 +237,7 @@ namespace App\Controllers; class Helloworld extends BaseController { - protected function utility() + protected function utility(): void { // some code } @@ -302,7 +302,7 @@ namespace App\Controllers; class Helloworld extends BaseController { - public function index() + public function index(): string { return 'Hello World!'; } @@ -402,12 +402,12 @@ namespace App\Controllers; class Helloworld extends BaseController { - public function index() + public function index(): string { return 'Hello World!'; } - public function comment() + public function comment(): string { return 'I am not flat!'; } @@ -441,7 +441,7 @@ namespace App\Controllers; class Products extends BaseController { - public function shoes($sandals, $id) + public function shoes(string $sandals, string $id): string { return $sandals . $id; } @@ -519,7 +519,7 @@ namespace App\Controllers; class Products extends BaseController { - public function _remap() + public function _remap(): void { // Some code here... } @@ -538,7 +538,7 @@ namespace App\Controllers; class Products extends BaseController { - public function _remap($method) + public function _remap(string $method): mixed { if ($method === 'some_method') { return $this->{$method}(); @@ -562,7 +562,7 @@ use CodeIgniter\Exceptions\PageNotFoundException; class Products extends BaseController { - public function _remap($method, ...$params) + public function _remap(string $method, string ...$params): mixed { $method = 'process_' . $method; diff --git a/docs/incoming/filters.md b/docs/incoming/filters.md index a96cd1638d4c..e366f9831cce 100644 --- a/docs/incoming/filters.md +++ b/docs/incoming/filters.md @@ -114,6 +114,9 @@ use CodeIgniter\Filters\CSRF; class Filters extends BaseConfig { + /** + * @var array> + */ public array $aliases = [ 'csrf' => CSRF::class, ]; @@ -139,6 +142,9 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { + /** + * @var array> + */ public array $aliases = [ 'api-prep' => [ Negotiate::class, @@ -175,6 +181,9 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { // ... + /** + * @var array{before: list, after: list} + */ public array $required = [ 'before' => [ 'forcehttps', // Force Global Secure Requests @@ -210,6 +219,12 @@ class Filters extends BaseConfig { // ... + /** + * @var array{ + * before: array|string}>|list, + * after: array|string}>|list + * } + */ public array $globals = [ 'before' => [ 'csrf', @@ -238,6 +253,12 @@ class Filters extends BaseConfig { // ... + /** + * @var array{ + * before: array|string}>|list, + * after: array|string}>|list + * } + */ public array $globals = [ 'before' => [ 'csrf' => ['except' => 'api/*'], @@ -267,6 +288,12 @@ class Filters extends BaseConfig { // ... + /** + * @var array{ + * before: array|string}>|list, + * after: array|string}>|list + * } + */ public array $globals = [ 'before' => [ 'csrf' => ['except' => ['foo/*', 'bar/*']], @@ -296,6 +323,9 @@ class Filters extends BaseConfig { // ... + /** + * @var array> + */ public array $methods = [ 'POST' => ['invalidchars', 'csrf'], 'GET' => ['csrf'], @@ -328,6 +358,9 @@ class Filters extends BaseConfig { // ... + /** + * @var array>> + */ public array $filters = [ 'foo' => ['before' => ['admin/*'], 'after' => ['users/*']], 'bar' => ['before' => ['api/*', 'admin/*']], @@ -357,7 +390,10 @@ class Filters extends BaseConfig { // ... - public $filters = [ + /** + * @var array>> + */ + public array $filters = [ 'group:admin,superadmin' => ['before' => ['admin/*']], 'permission:users.manage' => ['before' => ['admin/users/*']], ]; @@ -489,6 +525,9 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { + /** + * @var array> + */ public array $aliases = [ // ... 'secureheaders' => SecureHeaders::class, diff --git a/docs/incoming/incomingrequest.md b/docs/incoming/incomingrequest.md index ccae7d1db668..c8375ea498cc 100644 --- a/docs/incoming/incomingrequest.md +++ b/docs/incoming/incomingrequest.md @@ -15,7 +15,7 @@ use CodeIgniter\Controller; class UserController extends Controller { - public function index() + public function index(): void { if ($this->request->isAJAX()) { // ... @@ -43,7 +43,7 @@ use CodeIgniter\HTTP\RequestInterface; class SomeClass { - protected $request; + protected RequestInterface $request; public function __construct(RequestInterface $request) { diff --git a/docs/incoming/routing.md b/docs/incoming/routing.md index 9c464ab704c0..ac6717e72641 100644 --- a/docs/incoming/routing.md +++ b/docs/incoming/routing.md @@ -246,7 +246,7 @@ namespace App\Controllers; class Catalog extends BaseController { - public function productLookup($seg1 = false, $seg2 = false, $seg3 = false) + public function productLookup(false|string $seg1 = false, false|string $seg2 = false, false|string $seg3 = false): void { echo $seg1; // Will be 123 in all examples echo $seg2; // false in first, 456 in second and third example @@ -264,7 +264,7 @@ namespace App\Controllers; class Catalog extends BaseController { - public function productLookup(...$params) + public function productLookup(string ...$params): void { echo $params[0] ?? null; // Will be 123 in all examples echo $params[1] ?? null; // null in first, 456 in second and third example diff --git a/docs/installation/deployment.md b/docs/installation/deployment.md index ba91ec36a118..0c692a9f1a47 100644 --- a/docs/installation/deployment.md +++ b/docs/installation/deployment.md @@ -83,7 +83,7 @@ Make sure you use the appstarter installation. If using manual installation, you class preload { /** - * @var array Paths to preload. + * @var list> Paths to preload. */ private array $paths = [ [ diff --git a/docs/installation/upgrade_412.md b/docs/installation/upgrade_412.md index a02678e7b8ca..dd02da17b741 100644 --- a/docs/installation/upgrade_412.md +++ b/docs/installation/upgrade_412.md @@ -41,7 +41,7 @@ use CodeIgniter\Test\DatabaseTestCase; class MyDatabaseTest extends DatabaseTestCase { - public function testBadRow() + public function testBadRow(): void { // ... } @@ -60,7 +60,7 @@ class MyDatabaseTest extends CIUnitTestCase { use DatabaseTestTrait; - public function testBadRow() + public function testBadRow(): void { // ... } diff --git a/docs/installation/upgrade_415.md b/docs/installation/upgrade_415.md index 38e6bedb4e33..3ea8059299df 100644 --- a/docs/installation/upgrade_415.md +++ b/docs/installation/upgrade_415.md @@ -46,7 +46,10 @@ class Filters extends BaseConfig { // ... - public $methods = [ + /** + * @var array> + */ + public array $methods = [ 'GET' => ['csrf'], 'POST' => ['csrf'], ]; diff --git a/docs/installation/upgrade_460.md b/docs/installation/upgrade_460.md index 418b0bff7c76..c823e774550e 100644 --- a/docs/installation/upgrade_460.md +++ b/docs/installation/upgrade_460.md @@ -182,6 +182,9 @@ class Registrar // Does something. } + /** + * @return array> + */ public static function Pager(): array { return [ diff --git a/docs/installation/upgrade_configuration.md b/docs/installation/upgrade_configuration.md index a92ffcc3e4cb..7b3591a7812f 100644 --- a/docs/installation/upgrade_configuration.md +++ b/docs/installation/upgrade_configuration.md @@ -48,7 +48,7 @@ use CodeIgniter\Config\BaseConfig; class Site extends BaseConfig { - public $siteName = 'My Great Site'; - public $siteEmail = 'webmaster@example.com'; + public string $siteName = 'My Great Site'; + public string $siteEmail = 'webmaster@example.com'; } ``` diff --git a/docs/installation/upgrade_controllers.md b/docs/installation/upgrade_controllers.md index 4891a78d0aef..6f95beff5629 100644 --- a/docs/installation/upgrade_controllers.md +++ b/docs/installation/upgrade_controllers.md @@ -57,7 +57,7 @@ namespace App\Controllers; class Helloworld extends BaseController { - public function index($name) + public function index(string $name): string { return 'Hello ' . esc($name) . '!'; } diff --git a/docs/installation/upgrade_file_upload.md b/docs/installation/upgrade_file_upload.md index 556d4d6a2054..cc6c5e89e3ff 100644 --- a/docs/installation/upgrade_file_upload.md +++ b/docs/installation/upgrade_file_upload.md @@ -68,12 +68,12 @@ namespace App\Controllers; class Upload extends BaseController { - public function index() + public function index(): string { return view('upload_form', ['error' => ' ']); } - public function do_upload() + public function do_upload(): string { $this->validateData([], [ 'userfile' => [ @@ -87,7 +87,9 @@ class Upload extends BaseController $file = $this->request->getFile('userfile'); - if (! $path = $file->store()) { + $path = $file->store(); + + if ($path === '') { return view('upload_form', ['error' => 'upload failed']); } $data = ['upload_file_path' => $path]; diff --git a/docs/installation/upgrade_models.md b/docs/installation/upgrade_models.md index d0085cc0199c..db20a8385cd3 100644 --- a/docs/installation/upgrade_models.md +++ b/docs/installation/upgrade_models.md @@ -67,7 +67,7 @@ class NewsModel extends Model // Sets the table name. protected $table = 'news'; - public function setNews($title, $slug, $text) + public function setNews(string $title, string $slug, string $text): mixed { $data = [ 'title' => $title, @@ -100,7 +100,7 @@ class NewsModel extends Model // Sets the field names to allow to insert/update. protected $allowedFields = ['title', 'slug', 'text']; - public function setNews($title, $slug, $text) + public function setNews(string $title, string $slug, string $text): mixed { $data = [ 'title' => $title, diff --git a/docs/installation/upgrade_security.md b/docs/installation/upgrade_security.md index 2fb433496272..63cd520839f3 100644 --- a/docs/installation/upgrade_security.md +++ b/docs/installation/upgrade_security.md @@ -27,7 +27,13 @@ { // ... - public $globals = [ + /** + * @var array{ + * before?: array|string}>|list, + * after?: array|string}>|list + * } + */ + public array $globals = [ 'before' => [ // 'honeypot', 'csrf', diff --git a/docs/installation/upgrade_validations.md b/docs/installation/upgrade_validations.md index 53ef3775f09f..320ec519f65b 100644 --- a/docs/installation/upgrade_validations.md +++ b/docs/installation/upgrade_validations.md @@ -148,7 +148,7 @@ use CodeIgniter\Controller; class Form extends Controller { - public function index() + public function index(): string { helper('form'); diff --git a/docs/installation/worker_mode.md b/docs/installation/worker_mode.md index 06d99b4efa38..b00fca047ca7 100644 --- a/docs/installation/worker_mode.md +++ b/docs/installation/worker_mode.md @@ -182,8 +182,13 @@ To clean up such listeners between requests, add the event name to `$resetEventL namespace Config; -class WorkerMode extends \CodeIgniter\Config\WorkerMode +class WorkerMode { + // ... + + /** + * @var list + */ public array $resetEventListeners = ['my_event']; } ``` diff --git a/docs/libraries/caching.md b/docs/libraries/caching.md index d89313718864..b37342ccc89a 100644 --- a/docs/libraries/caching.md +++ b/docs/libraries/caching.md @@ -9,7 +9,9 @@ The following example shows a common usage pattern within your controllers. ```php '; $foo = 'foobarbaz!'; @@ -367,7 +369,10 @@ class Cache extends BaseConfig { // ... - public $memcached = [ + /** + * @var array{host?: string, port?: int, weight?: int, raw?: bool} + */ + public array $memcached = [ 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 1, @@ -403,7 +408,18 @@ class Cache extends BaseConfig { // ... - public $redis = [ + /** + * @var array{ + * host?: string, + * password?: string|null, + * port?: int, + * timeout?: int, + * async?: bool, + * persistent?: bool, + * database?: int + * } + */ + public array $redis = [ 'host' => '127.0.0.1', 'password' => null, 'port' => 6379, diff --git a/docs/libraries/cookies.md b/docs/libraries/cookies.md index 164db2c9f1de..bfaf2ce9c14c 100644 --- a/docs/libraries/cookies.md +++ b/docs/libraries/cookies.md @@ -457,20 +457,6 @@ delete_cookie('login_token'); More often than not, you do not need to concern yourself with manually sending cookies. CodeIgniter will do this for you. However, if you really need to manually send cookies, you can use the `dispatch` method. Just like when sending other headers, you need to make sure the headers are not yet sent by checking the value of `headers_sent()`. -```php -dispatch(); // After dispatch, the collection is now empty. -``` - ## Cookie Personalization Sane defaults are already in place inside the `Cookie` class to ensure the smooth creation of cookie objects. However, you may wish to define your own settings by changing the following settings in the `Config\Cookie` class in the **app/Config/Cookie.php** file. diff --git a/docs/libraries/cors.md b/docs/libraries/cors.md index 73a17f9af65b..e216d3befc3a 100644 --- a/docs/libraries/cors.md +++ b/docs/libraries/cors.md @@ -135,6 +135,17 @@ class Cors extends BaseConfig { // ... + /** + * @var array{ + * allowedOrigins: list, + * allowedOriginsPatterns: list, + * supportsCredentials: bool, + * allowedHeaders: list, + * exposedHeaders: list, + * allowedMethods: list, + * maxAge: int, + * } + */ public array $api = [ 'allowedOrigins' => ['https://app.example.com'], 'allowedOriginsPatterns' => [], diff --git a/docs/libraries/email.md b/docs/libraries/email.md index 22a3de2cadb1..477c208c4ee6 100644 --- a/docs/libraries/email.md +++ b/docs/libraries/email.md @@ -48,10 +48,12 @@ Preferences are set by passing an array of preference values to the email initia ```php 'sendmail', + 'mailPath' => '/usr/sbin/sendmail', + 'charset' => 'iso-8859-1', + 'wordWrap' => true, +]; $email->initialize($config); ``` diff --git a/docs/libraries/encryption.md b/docs/libraries/encryption.md index f1e65b558c0b..dd22aaead5c3 100644 --- a/docs/libraries/encryption.md +++ b/docs/libraries/encryption.md @@ -147,7 +147,7 @@ use CodeIgniter\Config\BaseConfig; class Encryption extends BaseConfig { - public $key = 'YOUR KEY'; + public string $key = 'YOUR KEY'; // ... } @@ -238,6 +238,9 @@ class Encryption extends BaseConfig { public string $key = 'hex2bin:your_new_encryption_key_in_hex'; + /** + * @var list|string + */ public array|string $previousKeys = [ 'hex2bin:your_old_encryption_key_in_hex', 'hex2bin:another_old_key_if_needed', diff --git a/docs/libraries/file_collections.md b/docs/libraries/file_collections.md index b4554b7c45b4..e97f3f01e31a 100644 --- a/docs/libraries/file_collections.md +++ b/docs/libraries/file_collections.md @@ -39,7 +39,7 @@ echo 'I have ' . count($files) . ' files!'; foreach ($files as $file) { echo 'Moving ' . $file->getBasename() . ', ' . $file->getSizeByUnit('mb'); - $file->move(WRITABLE . $file->getRandomName()); + $file->move(WRITEPATH . $file->getRandomName()); } ``` diff --git a/docs/libraries/honeypot.md b/docs/libraries/honeypot.md index c39f7115edaf..8f34022fad79 100644 --- a/docs/libraries/honeypot.md +++ b/docs/libraries/honeypot.md @@ -17,7 +17,13 @@ class Filters extends BaseConfig { // ... - public $globals = [ + /** + * @var array{ + * before: array|string}>|list, + * after: array|string}>|list + * } + */ + public array $globals = [ 'before' => [ 'honeypot', // 'csrf', diff --git a/docs/libraries/pagination.md b/docs/libraries/pagination.md index 7b35c461dd7b..6aa7a5e72b45 100644 --- a/docs/libraries/pagination.md +++ b/docs/libraries/pagination.md @@ -27,7 +27,7 @@ use App\Models\UserModel; class UserController extends BaseController { - public function index() + public function index(): string { $model = model(UserModel::class); @@ -76,7 +76,7 @@ class UserModel extends Model { // ... - public function banned() + public function banned(): static { $this->builder()->where('ban', 1); @@ -114,6 +114,9 @@ class NewsModel extends Model // ... + /** + * @return array + */ public function getPagination(?int $perPage = null): array { $this->builder() @@ -169,7 +172,7 @@ use App\Models\UserModel; class UserController extends BaseController { - public function index() + public function index(): void { $userModel = model(UserModel::class); $pageModel = model(PageModel::class); @@ -228,7 +231,7 @@ namespace App\Controllers; class UserController extends BaseController { - public function index() + public function index(): string { // ... @@ -320,7 +323,10 @@ use CodeIgniter\Config\BaseConfig; class Pager extends BaseConfig { - public $templates = [ + /** + * @var array + */ + public array $templates = [ 'default_full' => 'CodeIgniter\Pager\Views\default_full', 'default_simple' => 'CodeIgniter\Pager\Views\default_simple', ]; @@ -354,7 +360,10 @@ use CodeIgniter\Config\BaseConfig; class Pager extends BaseConfig { - public $templates = [ + /** + * @var array + */ + public array $templates = [ 'default_full' => 'CodeIgniter\Pager\Views\default_full', 'default_simple' => 'CodeIgniter\Pager\Views\default_simple', 'front_full' => 'App\Views\Pagers\foundation_full', diff --git a/docs/libraries/security.md b/docs/libraries/security.md index d447854b71bb..218219bc246f 100644 --- a/docs/libraries/security.md +++ b/docs/libraries/security.md @@ -75,7 +75,7 @@ use CodeIgniter\Config\BaseConfig; class Security extends BaseConfig { - public $csrfProtection = 'session'; + public string $csrfProtection = 'session'; // ... } @@ -98,7 +98,7 @@ use CodeIgniter\Config\BaseConfig; class Security extends BaseConfig { - public $tokenRandomize = true; + public bool $tokenRandomize = true; // ... } @@ -119,7 +119,7 @@ use CodeIgniter\Config\BaseConfig; class Security extends BaseConfig { - public $regenerate = true; + public bool $regenerate = true; // ... } @@ -182,7 +182,13 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $globals = [ + /** + * @var array{ + * before?: array|string}>|list, + * after?: array|string}>|list + * } + */ + public array $globals = [ 'before' => [ // 'honeypot', 'csrf', @@ -204,7 +210,13 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $globals = [ + /** + * @var array{ + * before?: array|string}>|list, + * after?: array|string}>|list + * } + */ + public array $globals = [ 'before' => [ 'csrf' => ['except' => ['api/record/save']], ], @@ -225,7 +237,13 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $globals = [ + /** + * @var array{ + * before?: array|string}>|list, + * after?: array|string}>|list + * } + */ + public array $globals = [ 'before' => [ 'csrf' => ['except' => ['api/record/[0-9]+']], ], @@ -246,7 +264,10 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $methods = [ + /** + * @var array> + */ + public array $methods = [ 'GET' => ['csrf'], 'POST' => ['csrf'], ]; diff --git a/docs/libraries/throttler.md b/docs/libraries/throttler.md index 6328b105c463..e08331270c83 100644 --- a/docs/libraries/throttler.md +++ b/docs/libraries/throttler.md @@ -47,7 +47,7 @@ class Throttle implements FilterInterface * * @param list|null $arguments * - * @return ResponseInterface|void + * @return ResponseInterface|null */ public function before(RequestInterface $request, $arguments = null) { @@ -58,6 +58,8 @@ class Throttle implements FilterInterface if ($throttler->check(md5($request->getIPAddress()), 60, MINUTE) === false) { return service('response')->setStatusCode(429); } + + return null; } /** @@ -65,11 +67,11 @@ class Throttle implements FilterInterface * * @param list|null $arguments * - * @return void + * @return ResponseInterface|null */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { - // ... + return null; } } ``` @@ -90,7 +92,10 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $aliases = [ + /** + * @var array> + */ + public array $aliases = [ // ... 'throttle' => Throttle::class, ]; @@ -110,7 +115,10 @@ use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { - public $methods = [ + /** + * @var array> + */ + public array $methods = [ 'POST' => ['throttle'], ]; diff --git a/docs/libraries/time.md b/docs/libraries/time.md index 84e074f9d108..84435333450a 100644 --- a/docs/libraries/time.md +++ b/docs/libraries/time.md @@ -189,7 +189,7 @@ While not an instantiator, this method is the opposite of the `createFromInstanc use CodeIgniter\I18n\Time; -$datetime = Time::toDateTime(); +$datetime = Time::now()->toDateTime(); ``` ## Displaying the Value @@ -423,7 +423,7 @@ $tz = Time::now()->getTimezone(); $tz = Time::now()->timezone; echo $tz->getName(); -echo $tz->getOffset(); +echo $tz->getOffset(Time::now()); ``` #### getTimezoneName() @@ -666,7 +666,7 @@ use CodeIgniter\I18n\Time; $time = Time::parse('March 10, 2017', 'America/Chicago'); $diff = $time->difference(Time::now()); -$diff = $time->difference(new DateTime('July 4, 1975', 'America/Chicago')); +$diff = $time->difference(new \DateTime('July 4, 1975', new \DateTimeZone('America/Chicago'))); $diff = $time->difference('July 4, 1975 13:32:05', 'America/Chicago'); ``` diff --git a/docs/libraries/uploaded_files.md b/docs/libraries/uploaded_files.md index 92270a53141b..4c37a74a2e39 100644 --- a/docs/libraries/uploaded_files.md +++ b/docs/libraries/uploaded_files.md @@ -87,12 +87,12 @@ class Upload extends BaseController { protected $helpers = ['form']; - public function index() + public function index(): string { return view('upload_form', ['errors' => []]); } - public function upload() + public function upload(): string { $validationRule = [ 'userfile' => [ diff --git a/docs/libraries/validation.md b/docs/libraries/validation.md index c9028245c8d0..ecea81c2279f 100644 --- a/docs/libraries/validation.md +++ b/docs/libraries/validation.md @@ -100,7 +100,7 @@ class Form extends BaseController { protected $helpers = ['form']; - public function index() + public function index(): string { if (! $this->request->is('post')) { return view('signup'); @@ -245,17 +245,19 @@ If you want to use traditional rules, you need to change the rule classes in **a namespace Config; +use CodeIgniter\Config\BaseConfig; use CodeIgniter\Validation\CreditCardRules; use CodeIgniter\Validation\FileRules; use CodeIgniter\Validation\FormatRules; use CodeIgniter\Validation\Rules; -// ... - class Validation extends BaseConfig { // ... + /** + * @var list + */ public array $ruleSets = [ CreditCardRules::class, FileRules::class, @@ -558,12 +560,15 @@ To store your validation rules, simply create a new public property in the `Conf namespace Config; -// ... +use CodeIgniter\Config\BaseConfig; class Validation extends BaseConfig { // ... + /** + * @var array|string> + */ public array $signup = [ 'username' => 'required|max_length[30]', 'password' => 'required|max_length[255]', @@ -592,12 +597,15 @@ You can also store custom error messages in this configuration file by naming th namespace Config; -// ... +use CodeIgniter\Config\BaseConfig; class Validation extends BaseConfig { // ... + /** + * @var array|string> + */ public array $signup = [ 'username' => 'required|max_length[30]', 'password' => 'required|max_length[255]', @@ -605,6 +613,9 @@ class Validation extends BaseConfig 'email' => 'required|max_length[254]|valid_email', ]; + /** + * @var array> + */ public array $signup_errors = [ 'username' => [ 'required' => 'You must choose a username.', @@ -625,12 +636,15 @@ Or pass all settings in an array: namespace Config; -// ... +use CodeIgniter\Config\BaseConfig; class Validation extends BaseConfig { // ... + /** + * @var array|string> + */ public array $signup = [ 'username' => [ 'rules' => 'required|max_length[30]', @@ -901,7 +915,7 @@ When you call `$validation->listErrors()` or `$validation->showError()`, it load The first step is to create custom views. These can be placed anywhere that the `view()` method can locate them, which means the standard View directory or any namespaced View folder will work. For example, you could create a new view at **app/Views/\_errors_list.php**: ```php - +