diff --git a/composer.json b/composer.json index 15d82c073..c5ad5da7f 100644 --- a/composer.json +++ b/composer.json @@ -66,6 +66,9 @@ "stan": "@phpstan", "stan-baseline": "tools/phpstan --generate-baseline", "stan-setup": "phive install", + "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.3.1\" && mv composer.backup composer.json", + "rector-check": "vendor/bin/rector process --dry-run", + "rector-fix": "vendor/bin/rector process", "test": "phpunit" }, "minimum-stability": "dev", diff --git a/config/routes.php b/config/routes.php index beca12119..28a5c51d2 100644 --- a/config/routes.php +++ b/config/routes.php @@ -3,8 +3,8 @@ use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; -return function (RouteBuilder $routes) { - $routes->plugin('DebugKit', ['path' => '/debug-kit'], function (RouteBuilder $routes) { +return function (RouteBuilder $routes): void { + $routes->plugin('DebugKit', ['path' => '/debug-kit'], function (RouteBuilder $routes): void { $routes->setExtensions('json'); $routes->setRouteClass(DashedRoute::class); @@ -37,7 +37,7 @@ $routes->scope( '/mail-preview', ['controller' => 'MailPreview'], - function (RouteBuilder $routes) { + function (RouteBuilder $routes): void { $routes->connect('/', ['action' => 'index']); $routes->connect('/preview', ['action' => 'email']); $routes->connect('/preview/*', ['action' => 'email']); diff --git a/rector.php b/rector.php new file mode 100644 index 000000000..724e2a670 --- /dev/null +++ b/rector.php @@ -0,0 +1,74 @@ +withPaths([ + __DIR__ . '/config', + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + + ->withCache( + cacheClass: FileCacheStorage::class, + cacheDirectory: $cacheDir, + ) + + ->withPhpSets() + ->withAttributesSets() + + ->withSets([ + SetList::CODE_QUALITY, + SetList::CODING_STYLE, + SetList::DEAD_CODE, + SetList::EARLY_RETURN, + SetList::INSTANCEOF, + SetList::TYPE_DECLARATION, + ]) + + ->withSkip([ + __DIR__ . '/tests/test_app/templates', + __DIR__ . '/tests/test_app/Plugin/TestPlugin/templates', + + ClassPropertyAssignToConstructorPromotionRector::class, + CatchExceptionNameMatchingTypeRector::class, + ClosureToArrowFunctionRector::class, + RemoveUselessReturnTagRector::class, + ReturnTypeFromStrictFluentReturnRector::class, + NewlineAfterStatementRector::class, + StringClassNameToClassConstantRector::class, + ReturnTypeFromStrictTypedCallRector::class, + ParamTypeByMethodCallTypeRector::class, + AddFunctionVoidReturnTypeWhereNoReturnRector::class, + StringableForToStringRector::class, + CompactToVariablesRector::class, + SplitDoubleAssignRector::class, + ChangeOrIfContinueToMultiContinueRector::class, + ExplicitBoolCompareRector::class, + NewlineBeforeNewAssignSetRector::class, + SimplifyEmptyCheckOnEmptyArrayRector::class, + DisallowedEmptyRuleFixerRector::class, + ]); diff --git a/src/Cache/Engine/DebugEngine.php b/src/Cache/Engine/DebugEngine.php index 3c4e2e22e..3f108c2f2 100644 --- a/src/Cache/Engine/DebugEngine.php +++ b/src/Cache/Engine/DebugEngine.php @@ -28,19 +28,11 @@ class DebugEngine extends CacheEngine { /** * Proxied engine - * - * @var \Cake\Cache\CacheEngine */ protected CacheEngine $_engine; - /** - * @var \Psr\Log\LoggerInterface - */ protected LoggerInterface $logger; - /** - * @var string - */ protected string $name; /** @@ -132,9 +124,9 @@ protected function track(string $metric): void */ protected function log(string $operation, float $duration, ?string $key = null): void { - $key = $key ? " `{$key}`" : ''; + $key = $key ? sprintf(' `%s`', $key) : ''; $duration = number_format($duration, 5); - $this->logger->log('info', ":{$this->name}: {$operation}{$key} - {$duration}ms"); + $this->logger->log('info', sprintf(':%s: %s%s - %sms', $this->name, $operation, $key, $duration)); } /** @@ -180,7 +172,7 @@ public function get(string $key, mixed $default = null): mixed $metric = 'miss'; } - $this->track("get {$metric}"); + $this->track('get ' . $metric); $this->log('get', $duration, $key); return $result; @@ -336,7 +328,7 @@ public function __toString(): string { if (isset($this->_engine)) { // phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable - [$ns, $class] = namespaceSplit(get_class($this->_engine)); + [$ns, $class] = namespaceSplit($this->_engine::class); return str_replace('Engine', '', $class); } diff --git a/src/Command/BenchmarkCommand.php b/src/Command/BenchmarkCommand.php index ec9432b4b..af7f23220 100644 --- a/src/Command/BenchmarkCommand.php +++ b/src/Command/BenchmarkCommand.php @@ -41,8 +41,6 @@ public static function getDescription(): string /** * The console io - * - * @var \Cake\Console\ConsoleIo */ protected ConsoleIo $io; @@ -144,8 +142,8 @@ protected function _variance(array $times, bool $sample = true): float foreach ($times as $time) { $n += 1; $delta = $time - $mean; - $mean = $mean + $delta / $n; - $M2 = $M2 + $delta * ($time - $mean); + $mean += $delta / $n; + $M2 += $delta * ($time - $mean); } if ($sample) { diff --git a/src/Controller/ComposerController.php b/src/Controller/ComposerController.php index edca252cc..f657a872b 100644 --- a/src/Controller/ComposerController.php +++ b/src/Controller/ComposerController.php @@ -55,10 +55,10 @@ public function checkDependencies(): void $dependencies = array_filter(explode("\n", $output->fetch())); $packages = []; foreach ($dependencies as $dependency) { - if (strpos($dependency, 'php_network_getaddresses') !== false) { + if (str_contains($dependency, 'php_network_getaddresses')) { throw new RuntimeException('You have to be connected to the internet'); } - if (strpos($dependency, '') !== false) { + if (str_contains($dependency, '')) { $packages['semverCompatible'][] = $dependency; continue; } diff --git a/src/Controller/DashboardController.php b/src/Controller/DashboardController.php index 5d9bd0d24..ecf108cc6 100644 --- a/src/Controller/DashboardController.php +++ b/src/Controller/DashboardController.php @@ -48,7 +48,7 @@ public function index(): void $requestsModel = $this->fetchTable('DebugKit.Requests'); $data = [ - 'driver' => get_class($requestsModel->getConnection()->getDriver()), + 'driver' => $requestsModel->getConnection()->getDriver()::class, 'rows' => $requestsModel->find()->count(), ]; diff --git a/src/Controller/MailPreviewController.php b/src/Controller/MailPreviewController.php index 602eee77f..8f70ca5bd 100644 --- a/src/Controller/MailPreviewController.php +++ b/src/Controller/MailPreviewController.php @@ -20,6 +20,7 @@ use Cake\Core\Plugin as CorePlugin; use Cake\Event\EventInterface; use Cake\Http\Exception\NotFoundException; +use Cake\Http\ServerRequest; use Cake\Routing\Router; use Cake\Utility\Inflector; use DebugKit\Mailer\AbstractResult; @@ -120,14 +121,14 @@ public function email(string $name, string $method): ?ResponseInterface if ($partType) { $result = $this->respondWithPart($email, $partType); - if ($restore) { + if ($restore instanceof ServerRequest) { Router::setRequest($restore); } return $result; } - $humanName = Inflector::humanize(Inflector::underscore($name) . "_$method"); + $humanName = Inflector::humanize(Inflector::underscore($name) . '_' . $method); /** @var string $part */ $part = $this->request->getQuery('part'); $this->set('title', $humanName); @@ -135,7 +136,7 @@ public function email(string $name, string $method): ?ResponseInterface $this->set('plugin', $plugin); $this->set('part', $this->findPreferredPart($email, $part)); - if ($restore) { + if ($restore instanceof ServerRequest) { Router::setRequest($restore); } @@ -184,11 +185,11 @@ protected function getMailPreviews(): CollectionInterface protected function getMailPreviewClasses(): CollectionInterface { $pluginPaths = collection(CorePlugin::loaded()) - ->reject(function ($plugin) { + ->reject(function ($plugin): bool { return $plugin === 'DebugKit'; }) - ->map(function ($plugin) { - return [[CorePlugin::classPath($plugin) . 'Mailer/Preview/'], "$plugin."]; + ->map(function (string $plugin): array { + return [[CorePlugin::classPath($plugin) . 'Mailer/Preview/'], $plugin . '.']; }); $appPaths = [App::classPath('Mailer/Preview'), '']; @@ -201,7 +202,7 @@ protected function getMailPreviewClasses(): CollectionInterface yield $plugin => $path; } }) - ->unfold(function ($path, $plugin) { + ->unfold(function (string $path, string $plugin) { /** @var list $files */ $files = glob($path . '*Preview.php'); foreach ($files as $file) { @@ -223,13 +224,7 @@ protected function getMailPreviewClasses(): CollectionInterface */ protected function findPart(AbstractResult $email, string $partType): ?string { - foreach ($email->getParts() as $part => $content) { - if ($part === $partType) { - return $content; - } - } - - return null; + return $email->getParts()[$partType] ?? null; } /** @@ -248,7 +243,7 @@ protected function findPreferredPart(AbstractResult $email, ?string $partType): } if ($partType === null) { - foreach ($email->getParts() as $part => $content) { + foreach (array_keys($email->getParts()) as $part) { return $part; } } @@ -268,12 +263,12 @@ protected function findPreferredPart(AbstractResult $email, ?string $partType): protected function findPreview(string $previewName, string $emailName, string $plugin = ''): PreviewResult { if ($plugin) { - $plugin = "$plugin."; + $plugin .= '.'; } $realClass = App::className($plugin . $previewName, 'Mailer/Preview'); if (!$realClass) { - throw new NotFoundException("Mailer preview $previewName not found"); + throw new NotFoundException(sprintf('Mailer preview %s not found', $previewName)); } /** @var \DebugKit\Mailer\MailPreview $mailPreview */ $mailPreview = new $realClass(); diff --git a/src/Database/Log/DebugLog.php b/src/Database/Log/DebugLog.php index 979e5cede..7a56e23c8 100644 --- a/src/Database/Log/DebugLog.php +++ b/src/Database/Log/DebugLog.php @@ -31,44 +31,32 @@ class DebugLog extends AbstractLogger { /** * Logs from the current request. - * - * @var array */ protected array $_queries = []; /** * Decorated logger. - * - * @var \Psr\Log\LoggerInterface|null */ protected ?LoggerInterface $_logger = null; /** * Name of the connection being logged. - * - * @var string */ protected string $_connectionName; /** * Total time (ms) of all queries - * - * @var float */ protected float $_totalTime = 0; /** * Set to true to capture schema reflection queries * in the SQL log panel. - * - * @var bool */ protected bool $_includeSchema = false; /** * Whether a transaction is currently open or not. - * - * @var bool */ protected bool $inTransaction = false; @@ -137,7 +125,7 @@ public function log($level, string|Stringable $message, array $context = []): vo /** @var \Cake\Database\Log\LoggedQuery|object|null $query */ $query = $context['query'] ?? null; - if ($this->_logger) { + if ($this->_logger instanceof LoggerInterface) { $this->_logger->log($level, $message, $context); } @@ -206,18 +194,18 @@ protected function isSchemaQuery(LoggedQuery $query): bool $querystring = $query->jsonSerialize()['query']; return // Multiple engines - strpos($querystring, 'FROM information_schema') !== false || + str_contains((string)$querystring, 'FROM information_schema') || // Postgres - strpos($querystring, 'FROM pg_catalog') !== false || + str_contains((string)$querystring, 'FROM pg_catalog') || // MySQL - strpos($querystring, 'SHOW TABLE') === 0 || - strpos($querystring, 'SHOW FULL COLUMNS') === 0 || - strpos($querystring, 'SHOW INDEXES') === 0 || + str_starts_with((string)$querystring, 'SHOW TABLE') || + str_starts_with((string)$querystring, 'SHOW FULL COLUMNS') || + str_starts_with((string)$querystring, 'SHOW INDEXES') || // Sqlite - strpos($querystring, 'FROM sqlite_master') !== false || - strpos($querystring, 'PRAGMA') === 0 || + str_contains((string)$querystring, 'FROM sqlite_master') || + str_starts_with((string)$querystring, 'PRAGMA') || // Sqlserver - strpos($querystring, 'FROM INFORMATION_SCHEMA') !== false || - strpos($querystring, 'FROM sys.') !== false; + str_contains((string)$querystring, 'FROM INFORMATION_SCHEMA') || + str_contains((string)$querystring, 'FROM sys.'); } } diff --git a/src/DebugInclude.php b/src/DebugInclude.php index 944c5308f..949859e75 100644 --- a/src/DebugInclude.php +++ b/src/DebugInclude.php @@ -39,8 +39,6 @@ class DebugInclude /** * File Types - * - * @var array */ protected array $_fileTypes = [ 'Auth', 'Cache', 'Collection', 'Config', 'Configure', 'Console', 'Component', 'Controller', @@ -83,12 +81,8 @@ public function __construct() public function includePaths(): array { $paths = explode(PATH_SEPARATOR, (string)get_include_path()); - $paths = array_filter($paths, function ($path) { - if ($path === '.' || strlen($path) === 0) { - return false; - } - - return true; + $paths = array_filter($paths, function ($path): bool { + return $path !== '.' && strlen($path) !== 0; }); return array_values($paths); @@ -102,7 +96,7 @@ public function includePaths(): array */ public function isCakeFile(string $file): bool { - return strpos($file, CAKE) === 0; + return str_starts_with($file, CAKE); } /** @@ -113,7 +107,7 @@ public function isCakeFile(string $file): bool */ public function isAppFile(string $file): bool { - return strpos($file, APP) === 0; + return str_starts_with($file, APP); } /** @@ -125,7 +119,7 @@ public function isAppFile(string $file): bool public function getPluginName(string $file): string|bool { foreach ($this->_pluginPaths as $plugin => $path) { - if (strpos($file, $path) === 0) { + if (str_starts_with($file, $path)) { return $plugin; } } @@ -142,7 +136,7 @@ public function getPluginName(string $file): string|bool public function getComposerPackageName(string $file): string|bool { foreach ($this->_composerPaths as $package => $path) { - if (strpos($file, $path) === 0) { + if (str_starts_with($file, $path)) { return $package; } } @@ -160,24 +154,14 @@ public function getComposerPackageName(string $file): string|bool */ public function niceFileName(string $file, string $type, ?string $name = null): string { - switch ($type) { - case 'app': - return str_replace(APP, 'APP' . DIRECTORY_SEPARATOR, $file); - - case 'cake': - return str_replace(CAKE, 'CAKE' . DIRECTORY_SEPARATOR, $file); - - case 'root': - return str_replace(ROOT, 'ROOT', $file); - - case 'plugin': - return str_replace($this->_pluginPaths[$name], $name . DIRECTORY_SEPARATOR, $file); - - case 'vendor': - return str_replace($this->_composerPaths[$name], '', $file); - } - - throw new InvalidArgumentException("Type `{$type}` is not supported."); + return match ($type) { + 'app' => str_replace(APP, 'APP' . DIRECTORY_SEPARATOR, $file), + 'cake' => str_replace(CAKE, 'CAKE' . DIRECTORY_SEPARATOR, $file), + 'root' => str_replace(ROOT, 'ROOT', $file), + 'plugin' => str_replace($this->_pluginPaths[$name], $name . DIRECTORY_SEPARATOR, $file), + 'vendor' => str_replace($this->_composerPaths[$name], '', $file), + default => throw new InvalidArgumentException(sprintf('Type `%s` is not supported.', $type)), + }; } /** diff --git a/src/DebugKitPlugin.php b/src/DebugKitPlugin.php index ab2a7ee8d..d9a25ba88 100644 --- a/src/DebugKitPlugin.php +++ b/src/DebugKitPlugin.php @@ -32,9 +32,6 @@ */ class DebugKitPlugin extends BasePlugin { - /** - * @var \DebugKit\ToolbarService|null - */ protected ?ToolbarService $service = null; /** @@ -67,7 +64,7 @@ public function bootstrap(PluginApplicationInterface $app): void public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { // Only insert middleware if Toolbar Service is available (not in phpunit run) - if ($this->service) { + if ($this->service instanceof ToolbarService) { $middlewareQueue->insertAt(0, new DebugKitMiddleware($this->service)); } diff --git a/src/DebugMemory.php b/src/DebugMemory.php index 40e7a78b3..b944802da 100644 --- a/src/DebugMemory.php +++ b/src/DebugMemory.php @@ -24,8 +24,6 @@ class DebugMemory { /** * An array of recorded memory use points. - * - * @var array */ protected static array $_points = []; diff --git a/src/DebugPanel.php b/src/DebugPanel.php index 18280d9f0..ef7571ee2 100644 --- a/src/DebugPanel.php +++ b/src/DebugPanel.php @@ -29,15 +29,11 @@ class DebugPanel implements EventListenerInterface { /** * Defines which plugin this panel is from so the element can be located. - * - * @var string */ public string $plugin = 'DebugKit'; /** * The data collected about a given request. - * - * @var array */ protected array $_data = []; diff --git a/src/DebugSql.php b/src/DebugSql.php index 4b26d03ed..7d57db736 100644 --- a/src/DebugSql.php +++ b/src/DebugSql.php @@ -30,8 +30,6 @@ class DebugSql { /** * Template used for HTML output. - * - * @var string */ private static string $templateHtml = << @@ -44,8 +42,6 @@ class DebugSql /** * Template used for CLI and text output. - * - * @var string */ private static string $templateText = << $param) { - $keys[] = is_string($key) ? "/$key\b/" : '/[?]/'; + foreach (array_keys($params) as $key) { + $keys[] = is_string($key) ? sprintf('/%s\b/', $key) : '/[?]/'; } return (string)preg_replace($keys, $params, $sql, $limit); diff --git a/src/DebugTimer.php b/src/DebugTimer.php index 31ee3dd5d..7c9b32edc 100644 --- a/src/DebugTimer.php +++ b/src/DebugTimer.php @@ -25,8 +25,6 @@ class DebugTimer { /** * Internal timers array - * - * @var array */ protected static array $_timers = []; diff --git a/src/Log/Engine/DebugKitLog.php b/src/Log/Engine/DebugKitLog.php index 32416a3d3..cc2e2a2fa 100644 --- a/src/Log/Engine/DebugKitLog.php +++ b/src/Log/Engine/DebugKitLog.php @@ -24,8 +24,6 @@ class DebugKitLog extends BaseLog { /** * logs - * - * @var array */ protected array $_logs = []; @@ -62,7 +60,7 @@ public function all(): array */ public function count(): int { - return array_reduce($this->_logs, function ($sum, $v) { + return array_reduce($this->_logs, function (int|float $sum, $v): int { return $sum + count($v); }, 0); } @@ -74,6 +72,6 @@ public function count(): int */ public function noLogs(): bool { - return empty($this->_logs); + return $this->_logs === []; } } diff --git a/src/Mailer/AbstractResult.php b/src/Mailer/AbstractResult.php index b434ff151..fb09425eb 100644 --- a/src/Mailer/AbstractResult.php +++ b/src/Mailer/AbstractResult.php @@ -21,15 +21,11 @@ abstract class AbstractResult { /** * The list of headers included in the email - * - * @var array */ protected array $headers = []; /** * The rendered parts of the email (for example text and html) - * - * @var array */ protected array $parts = []; diff --git a/src/Mailer/MailPreview.php b/src/Mailer/MailPreview.php index 7294d8ebf..84c75bcd2 100644 --- a/src/Mailer/MailPreview.php +++ b/src/Mailer/MailPreview.php @@ -95,7 +95,7 @@ protected function validEmail(string $email): bool try { $method = new ReflectionMethod($this, $email); - } catch (ReflectionException $e) { + } catch (ReflectionException) { return false; } diff --git a/src/Mailer/Transport/DebugKitTransport.php b/src/Mailer/Transport/DebugKitTransport.php index 0cd510160..084bded1c 100644 --- a/src/Mailer/Transport/DebugKitTransport.php +++ b/src/Mailer/Transport/DebugKitTransport.php @@ -16,16 +16,12 @@ class DebugKitTransport extends AbstractTransport { /** * The transport object this class is decorating - * - * @var \Cake\Mailer\AbstractTransport|null */ protected ?AbstractTransport $originalTransport = null; /** * A reference to the object were emails will be pushed to * for logging. - * - * @var \ArrayObject */ protected ArrayObject $emailLog; @@ -39,7 +35,7 @@ public function __construct(array $config = [], ?AbstractTransport $originalTran { $this->emailLog = $config['debugKitLog']; - if ($originalTransport !== null) { + if ($originalTransport instanceof AbstractTransport) { $this->originalTransport = $originalTransport; return; @@ -76,7 +72,7 @@ public function send(Message $message): array $result = ['headers' => $headers, 'message' => $parts]; $this->emailLog[] = $result; - if ($this->originalTransport !== null) { + if ($this->originalTransport instanceof AbstractTransport) { return $this->originalTransport->send($message); } diff --git a/src/Middleware/DebugKitMiddleware.php b/src/Middleware/DebugKitMiddleware.php index 39f3f07a9..91189451a 100644 --- a/src/Middleware/DebugKitMiddleware.php +++ b/src/Middleware/DebugKitMiddleware.php @@ -26,9 +26,6 @@ */ class DebugKitMiddleware implements MiddlewareInterface { - /** - * @var \DebugKit\ToolbarService - */ protected ToolbarService $service; /** diff --git a/src/Model/Table/LazyTableTrait.php b/src/Model/Table/LazyTableTrait.php index b77eceb6d..eec69aa83 100644 --- a/src/Model/Table/LazyTableTrait.php +++ b/src/Model/Table/LazyTableTrait.php @@ -47,7 +47,7 @@ public function ensureTables(array $fixtures): void $existing = $schema->listTables(); } catch (PDOException $e) { // Handle errors when SQLite blows up if the schema has changed. - if (strpos($e->getMessage(), 'schema has changed') !== false) { + if (str_contains($e->getMessage(), 'schema has changed')) { $existing = $schema->listTables(); } else { throw $e; @@ -55,7 +55,7 @@ public function ensureTables(array $fixtures): void } try { - $config = require dirname(dirname(__DIR__)) . '/schema.php'; + $config = require dirname(__DIR__, 2) . '/schema.php'; $driver = $connection->getDriver(); foreach ($config as $table) { if (in_array($table['table'], $existing, true)) { @@ -80,6 +80,8 @@ public function ensureTables(array $fixtures): void throw new RuntimeException( 'Could not create a SQLite database. ' . 'Ensure that your webserver has write access to the database file and folder it is in.', + $e->getCode(), + $e, ); } throw $e; diff --git a/src/Model/Table/RequestsTable.php b/src/Model/Table/RequestsTable.php index 38fb02d62..6a716042d 100644 --- a/src/Model/Table/RequestsTable.php +++ b/src/Model/Table/RequestsTable.php @@ -87,7 +87,7 @@ public function findRecent(SelectQuery $query): SelectQuery */ protected function shouldGc(): bool { - return rand(1, 10) === 10; + return random_int(1, 10) === 10; } /** @@ -97,7 +97,7 @@ protected function shouldGc(): bool */ protected function shouldGcVacuum(): bool { - return rand(1, 10) === 10; + return random_int(1, 10) === 10; } /** diff --git a/src/Model/Table/SqlTraceTrait.php b/src/Model/Table/SqlTraceTrait.php index a9d79c712..1fb737aca 100644 --- a/src/Model/Table/SqlTraceTrait.php +++ b/src/Model/Table/SqlTraceTrait.php @@ -68,7 +68,7 @@ protected function fileStamp( int $start = 1, bool $debugOnly = true, ): SelectQuery|UpdateQuery|DeleteQuery { - if (!Configure::read('debug') && $debugOnly === true) { + if (!Configure::read('debug') && $debugOnly) { return $query; } @@ -84,7 +84,7 @@ protected function fileStamp( if ($path === '[internal]') { continue; } - if (defined('CAKE_CORE_INCLUDE_PATH') && strpos($path, CAKE_CORE_INCLUDE_PATH) !== 0) { + if (defined('CAKE_CORE_INCLUDE_PATH') && !str_starts_with((string)$path, CAKE_CORE_INCLUDE_PATH)) { break; } } diff --git a/src/Panel/CachePanel.php b/src/Panel/CachePanel.php index fef295994..8f596372c 100644 --- a/src/Panel/CachePanel.php +++ b/src/Panel/CachePanel.php @@ -24,9 +24,6 @@ */ class CachePanel extends DebugPanel { - /** - * @var \Cake\Log\Engine\ArrayLog - */ protected ArrayLog $logger; /** diff --git a/src/Panel/DeprecationsPanel.php b/src/Panel/DeprecationsPanel.php index b3013a935..65b037ff7 100644 --- a/src/Panel/DeprecationsPanel.php +++ b/src/Panel/DeprecationsPanel.php @@ -26,15 +26,11 @@ class DeprecationsPanel extends DebugPanel { /** * The list of depreated errors. - * - * @var array */ protected static array $deprecatedErrors = []; /** * instance of DebugInclude - * - * @var \DebugKit\DebugInclude */ protected DebugInclude $_debug; @@ -135,7 +131,7 @@ public function summary(): string return $carry; } // app, cake, or other groups - if (Hash::dimensions($item) == 2) { + if (Hash::dimensions($item) === 2) { return $carry + count($item); } diff --git a/src/Panel/EnvironmentPanel.php b/src/Panel/EnvironmentPanel.php index 87ae1b612..3291fe80c 100644 --- a/src/Panel/EnvironmentPanel.php +++ b/src/Panel/EnvironmentPanel.php @@ -26,8 +26,6 @@ class EnvironmentPanel extends DebugPanel { /** * instance of DebugInclude - * - * @var \DebugKit\DebugInclude */ protected DebugInclude $_debug; diff --git a/src/Panel/IncludePanel.php b/src/Panel/IncludePanel.php index 3056c5f42..640f76920 100644 --- a/src/Panel/IncludePanel.php +++ b/src/Panel/IncludePanel.php @@ -28,8 +28,6 @@ class IncludePanel extends DebugPanel { /** * instance of DebugInclude - * - * @var \DebugKit\DebugInclude */ protected DebugInclude $_debug; @@ -111,7 +109,7 @@ public function summary(): string } unset($data['paths']); - $data = array_filter($data, function ($v, $k) { + $data = array_filter($data, function ($v, $k): bool { return !empty($v); }, ARRAY_FILTER_USE_BOTH); diff --git a/src/Panel/MailPanel.php b/src/Panel/MailPanel.php index c44a4f79c..2119b9ec2 100644 --- a/src/Panel/MailPanel.php +++ b/src/Panel/MailPanel.php @@ -28,8 +28,6 @@ class MailPanel extends DebugPanel { /** * The list of emails produced during the request - * - * @var \ArrayObject|null */ protected ?ArrayObject $emailLog = null; @@ -77,7 +75,7 @@ public function initialize(): void public function data(): array { return [ - 'emails' => isset($this->emailLog) ? $this->emailLog->getArrayCopy() : [], + 'emails' => $this->emailLog instanceof ArrayObject ? $this->emailLog->getArrayCopy() : [], ]; } @@ -88,7 +86,7 @@ public function data(): array */ public function summary(): string { - if (empty($this->emailLog)) { + if (!$this->emailLog instanceof ArrayObject) { return ''; } diff --git a/src/Panel/PanelRegistry.php b/src/Panel/PanelRegistry.php index 2cac0fd71..7cceb42cd 100644 --- a/src/Panel/PanelRegistry.php +++ b/src/Panel/PanelRegistry.php @@ -86,11 +86,7 @@ protected function _throwMissingClassError(string $class, ?string $plugin): void */ protected function _create(object|string $class, string $alias, array $config): DebugPanel { - if (is_string($class)) { - $instance = new $class(); - } else { - $instance = $class; - } + $instance = is_string($class) ? new $class() : $class; $this->getEventManager()->on($instance); diff --git a/src/Panel/RequestPanel.php b/src/Panel/RequestPanel.php index ad8bc3fa4..49af9f430 100644 --- a/src/Panel/RequestPanel.php +++ b/src/Panel/RequestPanel.php @@ -43,7 +43,7 @@ public function shutdown(EventInterface $event): void try { serialize($value); } catch (Exception $e) { - $value = "Could not serialize `{$attr}`. It failed with {$e->getMessage()}"; + $value = sprintf('Could not serialize `%s`. It failed with %s', $attr, $e->getMessage()); } $attributes[$attr] = Debugger::exportVarAsNodes($value, $maxDepth); } diff --git a/src/Panel/RoutesPanel.php b/src/Panel/RoutesPanel.php index ef9ee979a..01c9aa5b6 100644 --- a/src/Panel/RoutesPanel.php +++ b/src/Panel/RoutesPanel.php @@ -15,6 +15,7 @@ namespace DebugKit\Panel; use Cake\Event\EventInterface; +use Cake\Routing\Route\Route; use Cake\Routing\Router; use DebugKit\DebugPanel; @@ -30,7 +31,7 @@ class RoutesPanel extends DebugPanel */ public function summary(): string { - $routes = array_filter(Router::routes(), function ($route) { + $routes = array_filter(Router::routes(), function (Route $route): bool { return !isset($route->defaults['plugin']) || $route->defaults['plugin'] !== 'DebugKit'; }); diff --git a/src/Panel/SqlLogPanel.php b/src/Panel/SqlLogPanel.php index 231a25005..12b8657b8 100644 --- a/src/Panel/SqlLogPanel.php +++ b/src/Panel/SqlLogPanel.php @@ -31,8 +31,6 @@ class SqlLogPanel extends DebugPanel /** * Loggers connected - * - * @var array */ protected static array $_loggers = []; @@ -103,7 +101,7 @@ public static function addConnection(string $name): void public function data(): array { return [ - 'tables' => array_map(function (Table $table) { + 'tables' => array_map(function (Table $table): string { return $table->getAlias(); }, $this->getTableLocator()->genericInstances()), 'loggers' => static::$_loggers, @@ -126,6 +124,6 @@ public function summary(): string return '0'; } - return "$count / $time ms"; + return sprintf('%d / %s ms', $count, $time); } } diff --git a/src/Panel/TimerPanel.php b/src/Panel/TimerPanel.php index 7b3dc01df..67f9a092c 100644 --- a/src/Panel/TimerPanel.php +++ b/src/Panel/TimerPanel.php @@ -15,6 +15,7 @@ namespace DebugKit\Panel; use Cake\I18n\Number; +use Closure; use DebugKit\DebugMemory; use DebugKit\DebugPanel; use DebugKit\DebugTimer; @@ -31,17 +32,17 @@ class TimerPanel extends DebugPanel */ public function implementedEvents(): array { - $before = function ($name) { + $before = function ($name): Closure { return function () use ($name): void { DebugTimer::start($name); }; }; - $after = function ($name) { + $after = function ($name): Closure { return function () use ($name): void { DebugTimer::stop($name); }; }; - $both = function ($name) use ($before, $after) { + $both = function (string $name) use ($before, $after): array { return [ ['priority' => 0, 'callable' => $before('Event: ' . $name)], ['priority' => 999, 'callable' => $after('Event: ' . $name)], @@ -80,12 +81,12 @@ public function implementedEvents(): array 'View.beforeLayout' => $both('View.beforeLayout'), 'View.afterLayout' => $both('View.afterLayout'), 'View.beforeRenderFile' => [ - ['priority' => 0, 'callable' => function ($event, $filename): void { + ['priority' => 0, 'callable' => function ($event, string $filename): void { DebugTimer::start('Render File: ' . $filename); }], ], 'View.afterRenderFile' => [ - ['priority' => 0, 'callable' => function ($event, $filename): void { + ['priority' => 0, 'callable' => function ($event, string $filename): void { DebugTimer::stop('Render File: ' . $filename); }], ], @@ -125,6 +126,6 @@ public function summary(): string $time = Number::precision(DebugTimer::requestTime(), 2) . ' s'; $memory = Number::toReadableSize(DebugMemory::getPeak()); - return "$time / $memory"; + return sprintf('%s / %s', $time, $memory); } } diff --git a/src/Panel/VariablesPanel.php b/src/Panel/VariablesPanel.php index 40f0ad242..b84a32b45 100644 --- a/src/Panel/VariablesPanel.php +++ b/src/Panel/VariablesPanel.php @@ -70,7 +70,7 @@ protected function _walkDebugInfo(callable $walker, object $item): array|string } catch (Exception $exception) { return sprintf( 'Could not retrieve debug info - %s. Error: %s in %s, line %d', - get_class($item), + $item::class, $exception->getMessage(), $exception->getFile(), $exception->getLine(), diff --git a/src/ToolbarService.php b/src/ToolbarService.php index 220013e72..a5fb2b570 100644 --- a/src/ToolbarService.php +++ b/src/ToolbarService.php @@ -42,15 +42,11 @@ class ToolbarService /** * The panel registry. - * - * @var \DebugKit\Panel\PanelRegistry */ protected PanelRegistry $registry; /** * Default configuration. - * - * @var array */ protected array $_defaultConfig = [ 'panels' => [ @@ -113,7 +109,7 @@ public function isEnabled(): bool } $enabled = (bool)Configure::read('debug') && !$this->isSuspiciouslyProduction() - && php_sapi_name() !== 'phpdbg'; + && PHP_SAPI !== 'phpdbg'; if ($enabled) { return true; @@ -159,7 +155,7 @@ protected function isSuspiciouslyProduction(): bool // So it's not an IP address. It must be a domain name. $parts = explode('.', $host); - if (count($parts) == 1) { + if (count($parts) === 1) { return false; } @@ -176,8 +172,8 @@ protected function isSuspiciouslyProduction(): bool if (!$this->getConfig('forceEnable')) { $safeList = implode(', ', $safeTlds); Log::warning( - "DebugKit is disabling itself as your host `{$host}` " . - "is not in the known safe list of top-level-domains ({$safeList}). " . + sprintf('DebugKit is disabling itself as your host `%s` ', $host) . + sprintf('is not in the known safe list of top-level-domains (%s). ', $safeList) . 'If you would like to force DebugKit on use the `DebugKit.forceEnable` Configure option.', ); } @@ -244,8 +240,8 @@ public function saveData(ServerRequest $request, ResponseInterface $response): R { $path = $request->getUri()->getPath(); $dashboardUrl = '/debug-kit'; - if (strpos($path, 'debug_kit') !== false || strpos($path, 'debug-kit') !== false) { - if (!($path === $dashboardUrl || $path === $dashboardUrl . '/')) { + if (str_contains($path, 'debug_kit') || str_contains($path, 'debug-kit')) { + if ($path !== $dashboardUrl && $path !== $dashboardUrl . '/') { // internal debug-kit request return false; } @@ -295,7 +291,7 @@ public function saveData(ServerRequest $request, ResponseInterface $response): R // Set error handler to catch warnings/errors during serialization set_error_handler(function ($errno, $errstr) use ($name): void { - throw new Exception("Serialization error in panel '{$name}': {$errstr}"); + throw new Exception(sprintf("Serialization error in panel '%s': %s", $name, $errstr)); }); $content = serialize($data); @@ -372,7 +368,7 @@ public function getToolbarUrl(): string public function injectScripts(Request $row, ResponseInterface $response): ResponseInterface { $response = $response->withHeader('X-DEBUGKIT-ID', (string)$row->id); - if (strpos($response->getHeaderLine('Content-Type'), 'html') === false) { + if (!str_contains($response->getHeaderLine('Content-Type'), 'html')) { return $response; } $body = $response->getBody(); @@ -390,7 +386,7 @@ public function injectScripts(Request $row, ResponseInterface $response): Respon // state after other middleware have been applied. $request = Router::getRequest(); $nonce = ''; - if ($request && $request->getAttribute('cspScriptNonce')) { + if ($request instanceof ServerRequest && $request->getAttribute('cspScriptNonce')) { $nonce = sprintf(' nonce="%s"', $request->getAttribute('cspScriptNonce')); } diff --git a/src/View/Helper/CredentialsHelper.php b/src/View/Helper/CredentialsHelper.php index f51f2c788..3c89cf964 100644 --- a/src/View/Helper/CredentialsHelper.php +++ b/src/View/Helper/CredentialsHelper.php @@ -31,8 +31,6 @@ class CredentialsHelper extends Helper { /** * Helpers property - * - * @var array */ public array $helpers = ['Html', 'DebugKit.Toolbar']; diff --git a/src/View/Helper/SimpleGraphHelper.php b/src/View/Helper/SimpleGraphHelper.php index 1489f828b..9184f25df 100644 --- a/src/View/Helper/SimpleGraphHelper.php +++ b/src/View/Helper/SimpleGraphHelper.php @@ -35,8 +35,6 @@ class SimpleGraphHelper extends Helper * - width => (int) * - valueType => string (value, percentage) * - style => array - * - * @var array */ protected array $_defaultSettings = [ 'max' => 100, @@ -71,9 +69,9 @@ public function bar(float|int $value, float|int $offset, array $options = []): s return sprintf( '
', - "width: {$width}px", - "margin-left: {$graphOffset}px; width: {$graphValue}px", - "Starting {$offset}ms into the request, taking {$value}ms", + sprintf('width: %spx', $width), + sprintf('margin-left: %spx; width: %spx', $graphOffset, $graphValue), + sprintf('Starting %sms into the request, taking %sms', $offset, $value), ); } } diff --git a/src/View/Helper/ToolbarHelper.php b/src/View/Helper/ToolbarHelper.php index 3fb992b37..933b8810e 100644 --- a/src/View/Helper/ToolbarHelper.php +++ b/src/View/Helper/ToolbarHelper.php @@ -34,15 +34,11 @@ class ToolbarHelper extends Helper { /** * helpers property - * - * @var array */ public array $helpers = ['Html', 'Form', 'Url']; /** * Whether or not the top level keys should be sorted. - * - * @var bool */ protected bool $sort = false; @@ -76,7 +72,7 @@ public function dumpNodes(array $nodes): string } $root = new ArrayNode($items); - return implode([ + return implode('', [ '
', $formatter->dump($root), '
', @@ -93,7 +89,7 @@ public function dumpNode(NodeInterface $node): string { $formatter = new HtmlFormatter(); - return implode([ + return implode('', [ '
', $formatter->dump($node), '
', diff --git a/tests/Fixture/PanelsFixture.php b/tests/Fixture/PanelsFixture.php index 6ccacf728..1c6696ecc 100644 --- a/tests/Fixture/PanelsFixture.php +++ b/tests/Fixture/PanelsFixture.php @@ -25,15 +25,11 @@ class PanelsFixture extends TestFixture * table property * * This is necessary to prevent userland inflections from causing issues. - * - * @var string */ public string $table = 'panels'; /** * Records - * - * @var array */ public array $records = []; } diff --git a/tests/Fixture/RequestsFixture.php b/tests/Fixture/RequestsFixture.php index 558af36e6..93e382b05 100644 --- a/tests/Fixture/RequestsFixture.php +++ b/tests/Fixture/RequestsFixture.php @@ -25,15 +25,11 @@ class RequestsFixture extends TestFixture * table property * * This is necessary to prevent userland inflections from causing issues. - * - * @var string */ public string $table = 'requests'; /** * Records - * - * @var array */ public array $records = []; } diff --git a/tests/TestCase/Cache/Engine/DebugEngineTest.php b/tests/TestCase/Cache/Engine/DebugEngineTest.php index a7550d1e1..1b50494b4 100644 --- a/tests/TestCase/Cache/Engine/DebugEngineTest.php +++ b/tests/TestCase/Cache/Engine/DebugEngineTest.php @@ -32,22 +32,16 @@ class DebugEngineTest extends TestCase */ protected $engine; - /** - * @var \Cake\Cache\Engine\ArrayEngine - */ - private $wrapped; + private ArrayEngine $wrapped; - /** - * @var \Cake\Log\Engine\ArrayLog - */ - private $logger; + private ArrayLog $logger; /** * setup * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->wrapped = new ArrayEngine(); @@ -65,7 +59,7 @@ public function setUp(): void * * @return void */ - public function testInitEngineBasedOnConfig() + public function testInitEngineBasedOnConfig(): void { $engine = new DebugEngine([ 'className' => 'File', @@ -81,7 +75,7 @@ public function testInitEngineBasedOnConfig() * * @return void */ - public function testInitErrorOnInvalidConfig() + public function testInitErrorOnInvalidConfig(): void { $this->expectException(BadMethodCallException::class); $engine = new DebugEngine([ @@ -97,7 +91,7 @@ public function testInitErrorOnInvalidConfig() * * @return void */ - public function testProxyMethodsTracksMetrics() + public function testProxyMethodsTracksMetrics(): void { $this->engine->get('key'); $this->engine->set('key', 'value'); @@ -118,7 +112,7 @@ public function testProxyMethodsTracksMetrics() * * @return void */ - public function testProxyMethodLogs() + public function testProxyMethodLogs(): void { $this->engine->get('key'); $this->engine->set('key', 'value'); @@ -141,7 +135,7 @@ public function testProxyMethodLogs() * * @return void */ - public function testGroupsProxies() + public function testGroupsProxies(): void { $engine = new DebugEngine([ 'className' => 'File', @@ -159,7 +153,7 @@ public function testGroupsProxies() * * @return void */ - public function testConfigProxies() + public function testConfigProxies(): void { $engine = new DebugEngine([ 'className' => 'File', @@ -178,7 +172,7 @@ public function testConfigProxies() * * @return void */ - public function testToString() + public function testToString(): void { $engine = new DebugEngine([ 'className' => 'File', diff --git a/tests/TestCase/Controller/ComposerControllerTest.php b/tests/TestCase/Controller/ComposerControllerTest.php index 086eda6df..4a56aa4ce 100644 --- a/tests/TestCase/Controller/ComposerControllerTest.php +++ b/tests/TestCase/Controller/ComposerControllerTest.php @@ -31,7 +31,7 @@ class ComposerControllerTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->configApplication(Application::class, []); @@ -42,7 +42,7 @@ public function setUp(): void * * @return void */ - public function testCheckDependencies() + public function testCheckDependencies(): void { $this->configRequest([ 'headers' => [ diff --git a/tests/TestCase/Controller/DashboardControllerTest.php b/tests/TestCase/Controller/DashboardControllerTest.php index 0fc12359b..08eb72f08 100644 --- a/tests/TestCase/Controller/DashboardControllerTest.php +++ b/tests/TestCase/Controller/DashboardControllerTest.php @@ -43,13 +43,13 @@ class DashboardControllerTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->configApplication(Application::class, []); } - public function testIndexNoRequests() + public function testIndexNoRequests(): void { $requests = $this->fetchTable('DebugKit.Requests'); $requests->Panels->deleteAll('1=1'); @@ -62,7 +62,7 @@ public function testIndexNoRequests() $this->assertResponseNotContains('Reset database'); } - public function testIndexWithRequests() + public function testIndexWithRequests(): void { $request = $this->makeRequest(); $this->makePanel($request); @@ -74,7 +74,7 @@ public function testIndexWithRequests() $this->assertResponseContains('Reset database'); } - public function testReset() + public function testReset(): void { $request = $this->makeRequest(); $this->makePanel($request); diff --git a/tests/TestCase/Controller/DebugKitControllerTest.php b/tests/TestCase/Controller/DebugKitControllerTest.php index 70f487c15..ed2cdefc8 100644 --- a/tests/TestCase/Controller/DebugKitControllerTest.php +++ b/tests/TestCase/Controller/DebugKitControllerTest.php @@ -24,12 +24,12 @@ use Cake\TestSuite\TestCase; use DebugKit\Controller\DebugKitController; use DebugKit\TestApp\Application; +use PHPUnit\Framework\Attributes\UsesClass; /** * DebugKit controller test. - * - * @uses \DebugKit\Controller\DebugKitController */ +#[UsesClass('\DebugKit\Controller\DebugKitController')] class DebugKitControllerTest extends TestCase { use IntegrationTestTrait; @@ -39,7 +39,7 @@ class DebugKitControllerTest extends TestCase * * @return void */ - public function testDebugDisabled() + public function testDebugDisabled(): void { Configure::write('debug', false); @@ -56,7 +56,7 @@ public function testDebugDisabled() * * @return DebugKit\Controller\DebugKitController */ - private function _buildController() + private function _buildController(): DebugKitController { $request = new ServerRequest(['url' => '/debug-kit/']); diff --git a/tests/TestCase/Controller/MailPreviewControllerTest.php b/tests/TestCase/Controller/MailPreviewControllerTest.php index ab5617f34..59cefa6d8 100644 --- a/tests/TestCase/Controller/MailPreviewControllerTest.php +++ b/tests/TestCase/Controller/MailPreviewControllerTest.php @@ -32,7 +32,7 @@ class MailPreviewControllerTest extends TestCase * * @return void */ - public function testEmailPluginPassedToView() + public function testEmailPluginPassedToView(): void { $this->get('/debug-kit/mail-preview/preview/TestMailerPreview/test_email?plugin=DebugkitTestPlugin'); @@ -44,7 +44,7 @@ public function testEmailPluginPassedToView() * * @return void */ - public function testEmailPartTextContent() + public function testEmailPartTextContent(): void { $this->get('/debug-kit/mail-preview/preview/TestMailerPreview/test_email?part=text&plugin=DebugkitTestPlugin'); @@ -58,7 +58,7 @@ public function testEmailPartTextContent() * * @return void */ - public function testOnChangeJsPluginPassedToview() + public function testOnChangeJsPluginPassedToview(): void { $this->get('/debug-kit/mail-preview/preview/TestMailerPreview/test_email?plugin=DebugkitTestPlugin'); @@ -70,7 +70,7 @@ public function testOnChangeJsPluginPassedToview() * * @return void */ - public function testSentInvalidData() + public function testSentInvalidData(): void { $this->get('/debug-kit/mail-preview/sent/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/0'); $this->assertResponseCode(404); @@ -81,7 +81,7 @@ public function testSentInvalidData() * * @return void */ - public function testSentValidData() + public function testSentValidData(): void { $panels = $this->fetchTable('DebugKit.Panels'); $request = $this->makeRequest(); @@ -97,7 +97,7 @@ public function testSentValidData() $panel->content = serialize($data); $panels->save($panel); - $this->get("/debug-kit/mail-preview/sent/{$panel->id}/0"); + $this->get(sprintf('/debug-kit/mail-preview/sent/%s/0', $panel->id)); $this->assertResponseCode(200); $this->assertResponseContains('test@example.com'); $this->assertResponseContains('fetchTable('DebugKit.Panels'); $request = $this->makeRequest(); @@ -124,7 +124,7 @@ public function testSentValidDataRenderPart() $panel->content = serialize($data); $panels->save($panel); - $this->get("/debug-kit/mail-preview/sent/{$panel->id}/0?part=html"); + $this->get(sprintf('/debug-kit/mail-preview/sent/%s/0?part=html', $panel->id)); $this->assertResponseCode(200); $this->assertResponseContains('

Hi

'); } diff --git a/tests/TestCase/Controller/PanelsControllerTest.php b/tests/TestCase/Controller/PanelsControllerTest.php index 461a26fef..eb8d4d598 100644 --- a/tests/TestCase/Controller/PanelsControllerTest.php +++ b/tests/TestCase/Controller/PanelsControllerTest.php @@ -43,7 +43,7 @@ class PanelsControllerTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->configApplication(Application::class, []); @@ -54,7 +54,7 @@ public function setUp(): void * * @return void */ - public function testIndex() + public function testIndex(): void { $this->configRequest([ 'headers' => [ @@ -63,7 +63,7 @@ public function testIndex() ]); $request = $this->makeRequest(); $this->makePanel($request); - $this->get("/debug-kit/panels/{$request->id}"); + $this->get('/debug-kit/panels/' . $request->id); $this->assertResponseOk(); $this->assertContentType('application/json'); @@ -74,12 +74,12 @@ public function testIndex() * * @return void */ - public function testView() + public function testView(): void { $request = $this->makeRequest(); $panel = $this->makePanel($request); - $this->get("/debug-kit/panels/view/{$panel->id}"); + $this->get('/debug-kit/panels/view/' . $panel->id); $this->assertResponseOk(); $this->assertResponseContains('Request'); @@ -91,7 +91,7 @@ public function testView() * * @return void */ - public function testViewNotExists() + public function testViewNotExists(): void { $this->get('/debug-kit/panels/view/aaaaaaaa-ffff-ffff-ffff-aaaaaaaaaaaa'); $this->assertResponseError(); @@ -101,7 +101,7 @@ public function testViewNotExists() /** * @return void */ - public function testLatestHistory() + public function testLatestHistory(): void { $request = $this->fetchTable('DebugKit.Requests')->find('recent')->first(); if (!$request) { diff --git a/tests/TestCase/Controller/RequestsControllerTest.php b/tests/TestCase/Controller/RequestsControllerTest.php index eb7580b5f..f4c2d950c 100644 --- a/tests/TestCase/Controller/RequestsControllerTest.php +++ b/tests/TestCase/Controller/RequestsControllerTest.php @@ -43,7 +43,7 @@ class RequestsControllerTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->configApplication(Application::class, []); @@ -54,13 +54,13 @@ public function setUp(): void * * @return void */ - public function testView() + public function testView(): void { $request = $this->makeRequest(); $this->makePanel($request); $this->configRequest(['headers' => ['Accept' => 'application/json']]); - $this->get("/debug-kit/toolbar/{$request->id}"); + $this->get('/debug-kit/toolbar/' . $request->id); $this->assertResponseOk(); $this->assertResponseContains('Request', 'Has a panel button'); @@ -72,7 +72,7 @@ public function testView() * * @return void */ - public function testViewNotExists() + public function testViewNotExists(): void { $this->configRequest(['headers' => ['Accept' => 'application/json']]); $this->get('/debug-kit/toolbar/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'); diff --git a/tests/TestCase/Controller/ToolbarControllerTest.php b/tests/TestCase/Controller/ToolbarControllerTest.php index dddac6ac2..254701b8d 100644 --- a/tests/TestCase/Controller/ToolbarControllerTest.php +++ b/tests/TestCase/Controller/ToolbarControllerTest.php @@ -32,7 +32,7 @@ class ToolbarControllerTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->configApplication(Application::class, []); @@ -43,7 +43,7 @@ public function setUp(): void * * @return void */ - public function testClearCacheNoGet() + public function testClearCacheNoGet(): void { $this->get('/debug-kit/toolbar/clear-cache?name=testing'); $this->assertResponseCode(405); @@ -54,7 +54,7 @@ public function testClearCacheNoGet() * * @return void */ - public function testClearCache() + public function testClearCache(): void { $mock = $this->getMockBuilder('Cake\Cache\CacheEngine')->getMock(); $mock->expects($this->once()) diff --git a/tests/TestCase/Database/Log/DebugLogTest.php b/tests/TestCase/Database/Log/DebugLogTest.php index d789931c3..3164132f1 100644 --- a/tests/TestCase/Database/Log/DebugLogTest.php +++ b/tests/TestCase/Database/Log/DebugLogTest.php @@ -36,7 +36,7 @@ class DebugLogTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->logger = new DebugLog(null, 'test'); @@ -47,7 +47,7 @@ public function setUp(): void * * @return void */ - public function testLog() + public function testLog(): void { $query = new LoggedQuery(); $query->setContext([ @@ -72,7 +72,7 @@ public function testLog() * * @return void */ - public function testLogElastic() + public function testLogElastic(): void { $this->assertCount(0, $this->logger->queries()); @@ -114,7 +114,7 @@ public function testLogElastic() * @return void */ #[DataProvider('schemaQueryProvider')] - public function testLogIgnoreReflection($sql) + public function testLogIgnoreReflection(string $sql): void { $query = new LoggedQuery(); $query->setContext([ @@ -135,7 +135,7 @@ public function testLogIgnoreReflection($sql) * @return void */ #[DataProvider('schemaQueryProvider')] - public function testLogIgnoreReflectionDisabled($sql) + public function testLogIgnoreReflectionDisabled(string $sql): void { $query = new LoggedQuery(); $query->setContext([ @@ -151,7 +151,7 @@ public function testLogIgnoreReflectionDisabled($sql) $this->assertCount(1, $logger->queries()); } - public static function schemaQueryProvider() + public static function schemaQueryProvider(): array { return [ // MySQL @@ -173,7 +173,7 @@ public static function schemaQueryProvider() * * @return void */ - public function testLogDecorates() + public function testLogDecorates(): void { $orig = $this->getMockBuilder(LoggerInterface::class)->getMock(); $orig->expects($this->once()) diff --git a/tests/TestCase/DebugIncludeTest.php b/tests/TestCase/DebugIncludeTest.php index 0314d061e..5dfb0d86d 100644 --- a/tests/TestCase/DebugIncludeTest.php +++ b/tests/TestCase/DebugIncludeTest.php @@ -22,7 +22,7 @@ */ class DebugIncludeTest extends TestCase { - public function testIncludePaths() + public function testIncludePaths(): void { $include = new DebugInclude(); $result = $include->includePaths(); @@ -30,7 +30,7 @@ public function testIncludePaths() $this->assertStringContainsString($result[0], get_include_path()); } - public function testIsCakeFile() + public function testIsCakeFile(): void { $include = new DebugInclude(); @@ -41,7 +41,7 @@ public function testIsCakeFile() $this->assertFalse($include->isCakeFile(TMP)); } - public function testIsAppFile() + public function testIsAppFile(): void { $include = new DebugInclude(); @@ -52,7 +52,7 @@ public function testIsAppFile() $this->assertFalse($include->isAppFile(TMP)); } - public function testGetPluginName() + public function testGetPluginName(): void { $include = new DebugInclude(); @@ -60,7 +60,7 @@ public function testGetPluginName() $this->assertFalse($include->getPluginName(TMP)); } - public function testGetComposerPackageName() + public function testGetComposerPackageName(): void { $include = new DebugInclude(); @@ -68,7 +68,7 @@ public function testGetComposerPackageName() $this->assertSame('cakephp/cakephp', $include->getComposerPackageName($path)); } - public function testNiceFileName() + public function testNiceFileName(): void { $include = new DebugInclude(); @@ -98,7 +98,7 @@ public function testNiceFileName() ); } - public function testGetFileType() + public function testGetFileType(): void { $include = new DebugInclude(); diff --git a/tests/TestCase/DebugKitPluginTest.php b/tests/TestCase/DebugKitPluginTest.php index 2b38a4212..5d48d8656 100644 --- a/tests/TestCase/DebugKitPluginTest.php +++ b/tests/TestCase/DebugKitPluginTest.php @@ -34,7 +34,7 @@ class DebugKitPluginTest extends TestCase * * @return void */ - public function testSetDeprecationHandler() + public function testSetDeprecationHandler(): void { DeprecationsPanel::clearDeprecatedErrors(); $service = new ToolbarService(new EventManager(), []); @@ -86,7 +86,7 @@ public function testSetDeprecationHandler() * * @return void */ - public function testMiddlewareNotLoadedInTests() + public function testMiddlewareNotLoadedInTests(): void { $baseApp = new Application(dirname(__DIR__) . '/config'); $baseApp->pluginBootstrap(); diff --git a/tests/TestCase/DebugMemoryTest.php b/tests/TestCase/DebugMemoryTest.php index b50f61049..391062ec6 100644 --- a/tests/TestCase/DebugMemoryTest.php +++ b/tests/TestCase/DebugMemoryTest.php @@ -27,7 +27,7 @@ class DebugMemoryTest extends TestCase * * @return void */ - public function testMemoryUsage() + public function testMemoryUsage(): void { $result = DebugMemory::getCurrent(); $this->assertIsInt($result); @@ -41,7 +41,7 @@ public function testMemoryUsage() * * @return void */ - public function testRecordNoKey() + public function testRecordNoKey(): void { DebugMemory::clear(); DebugMemory::record(); @@ -55,7 +55,7 @@ public function testRecordNoKey() * * @return void */ - public function testMemorySettingAndGetting() + public function testMemorySettingAndGetting(): void { DebugMemory::clear(); $result = DebugMemory::record('test marker'); diff --git a/tests/TestCase/DebugPanelTest.php b/tests/TestCase/DebugPanelTest.php index 61e136545..fffe7e281 100644 --- a/tests/TestCase/DebugPanelTest.php +++ b/tests/TestCase/DebugPanelTest.php @@ -28,18 +28,18 @@ class DebugPanelTest extends TestCase */ protected $panel; - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new SimplePanel(); } - public function testTitle() + public function testTitle(): void { $this->assertSame('Simple', $this->panel->title()); } - public function testElementName() + public function testElementName(): void { $this->assertSame('DebugKit.simple_panel', $this->panel->elementName()); diff --git a/tests/TestCase/DebugSqlTest.php b/tests/TestCase/DebugSqlTest.php index 79a3cd1f7..9a60b9b70 100644 --- a/tests/TestCase/DebugSqlTest.php +++ b/tests/TestCase/DebugSqlTest.php @@ -34,7 +34,7 @@ class DebugSqlTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->connection = ConnectionManager::get('test'); @@ -44,7 +44,7 @@ public function setUp(): void * Tests that a SQL string is outputted in a formatted and * highlighted fashion in a CLI environment. */ - public function testSqlCli() + public function testSqlCli(): void { $query = $this->newQuery()->select(['panels.id']); @@ -65,7 +65,7 @@ public function testSqlCli() * Tests that a SQL string is outputted as HTML in a CLI * environment. */ - public function testSqlHtmlOnCli() + public function testSqlHtmlOnCli(): void { $query = $this->newQuery()->select(['panels.id']); @@ -84,7 +84,7 @@ public function testSqlHtmlOnCli() * Tests that a SQL string is outputted as HTML in a non-CLI * environment. */ - public function testSqlHtml() + public function testSqlHtml(): void { $query = $this->newQuery()->select(['panels.id']); @@ -108,7 +108,7 @@ public function testSqlHtml() * Tests that a SQL string is outputted as plain text in a non-CLI * environment. */ - public function testSqlPlain() + public function testSqlPlain(): void { $query = $this->newQuery()->select(['panels.id']); diff --git a/tests/TestCase/DebugTimerTest.php b/tests/TestCase/DebugTimerTest.php index d38a22105..aeaa34bd6 100644 --- a/tests/TestCase/DebugTimerTest.php +++ b/tests/TestCase/DebugTimerTest.php @@ -29,7 +29,7 @@ class DebugTimerTest extends TestCase * * @return void */ - public function tearDown(): void + protected function tearDown(): void { DebugTimer::clear(); } @@ -39,7 +39,7 @@ public function tearDown(): void * * @return void */ - public function testTimers() + public function testTimers(): void { $this->assertTrue(DebugTimer::start('test1', 'this is my first test')); usleep(5000); @@ -64,7 +64,7 @@ public function testTimers() * * @return void */ - public function testAnonymousTimers() + public function testAnonymousTimers(): void { $this->assertTrue(DebugTimer::start()); usleep(2000); @@ -72,9 +72,8 @@ public function testAnonymousTimers() $timers = DebugTimer::getAll(); $this->assertCount(2, $timers); - end($timers); - $key = key($timers); - $lineNo = __LINE__ - 8; + $key = array_key_last($timers); + $lineNo = __LINE__ - 7; $file = Debugger::trimPath(__FILE__); $expected = $file . ' line ' . $lineNo; @@ -90,7 +89,7 @@ public function testAnonymousTimers() * * @return void */ - public function testNestedAnonymousTimers() + public function testNestedAnonymousTimers(): void { $this->assertTrue(DebugTimer::start()); usleep(100); @@ -119,7 +118,7 @@ public function testNestedAnonymousTimers() * * @return void */ - public function testRepeatTimers() + public function testRepeatTimers(): void { DebugTimer::start('my timer', 'This is the first call'); usleep(100); @@ -145,7 +144,7 @@ public function testRepeatTimers() * * @return void */ - public function testRequestTime() + public function testRequestTime(): void { $result1 = DebugTimer::requestTime(); usleep(50); @@ -158,7 +157,7 @@ public function testRequestTime() * * @return void */ - public function testGetTimersWithClear() + public function testGetTimersWithClear(): void { DebugTimer::start('test1', 'this is my first test'); DebugTimer::stop('test1'); @@ -173,7 +172,7 @@ public function testGetTimersWithClear() * * @return void */ - public function testGetTimers() + public function testGetTimers(): void { DebugTimer::start('test1', 'this is my first test'); DebugTimer::stop('test1'); diff --git a/tests/TestCase/Mailer/Transport/DebugKitTransportTest.php b/tests/TestCase/Mailer/Transport/DebugKitTransportTest.php index 218c7bbf5..13a087304 100644 --- a/tests/TestCase/Mailer/Transport/DebugKitTransportTest.php +++ b/tests/TestCase/Mailer/Transport/DebugKitTransportTest.php @@ -28,7 +28,7 @@ class DebugKitTransportTest extends TestCase protected $wrapped; - public function setUp(): void + protected function setUp(): void { $this->log = new ArrayObject(); $this->wrapped = new class extends AbstractTransport { @@ -50,7 +50,7 @@ public function customMethod(): string ); } - public function testPropertyProxies() + public function testPropertyProxies(): void { $this->wrapped->property = 'value'; $this->assertTrue(isset($this->transport->property)); @@ -62,12 +62,12 @@ public function testPropertyProxies() $this->assertFalse(isset($this->wrapped->property)); } - public function testMethodProxy() + public function testMethodProxy(): void { $this->assertSame('bloop', $this->transport->customMethod()); } - public function testEmailCapture() + public function testEmailCapture(): void { $message = new Message(); $message->setSubject('Testing 123') diff --git a/tests/TestCase/Middleware/DebugKitMiddlewareTest.php b/tests/TestCase/Middleware/DebugKitMiddlewareTest.php index 6a15a18f0..cb7df7f28 100644 --- a/tests/TestCase/Middleware/DebugKitMiddlewareTest.php +++ b/tests/TestCase/Middleware/DebugKitMiddlewareTest.php @@ -24,6 +24,7 @@ use Cake\Routing\Router; use Cake\TestSuite\TestCase; use DebugKit\Middleware\DebugKitMiddleware; +use Psr\Http\Message\MessageInterface; use Psr\Http\Server\RequestHandlerInterface; use ReflectionProperty; @@ -44,9 +45,6 @@ class DebugKitMiddlewareTest extends TestCase protected ?array $oldConfig = null; - /** - * @var bool - */ protected bool $restore = false; /** @@ -54,7 +52,7 @@ class DebugKitMiddlewareTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -70,7 +68,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); @@ -80,11 +78,9 @@ public function tearDown(): void protected function handler() { - $handler = $this->getMockBuilder(RequestHandlerInterface::class) + return $this->getMockBuilder(RequestHandlerInterface::class) ->onlyMethods(['handle']) ->getMock(); - - return $handler; } /** @@ -92,7 +88,7 @@ protected function handler() * * @return void */ - public function testInvokeSaveData() + public function testInvokeSaveData(): void { $request = new ServerRequest([ 'url' => '/articles', @@ -146,7 +142,7 @@ public function testInvokeSaveData() * * @return void */ - public function testInvokeInjectCspNonce() + public function testInvokeInjectCspNonce(): void { $request = new ServerRequest([ 'url' => '/articles', @@ -179,7 +175,7 @@ public function testInvokeInjectCspNonce() * * @return void */ - public function testInvokeNoModifyBinaryResponse() + public function testInvokeNoModifyBinaryResponse(): void { $request = new ServerRequest([ 'url' => '/articles', @@ -193,8 +189,8 @@ public function testInvokeNoModifyBinaryResponse() $handler = $this->handler(); $handler->expects($this->once()) ->method('handle') - ->willReturnCallback(function ($req) use ($response) { - $stream = new CallbackStream(function () { + ->willReturnCallback(function ($req) use ($response): MessageInterface { + $stream = new CallbackStream(function (): string { return 'hi!'; }); @@ -218,7 +214,7 @@ public function testInvokeNoModifyBinaryResponse() * * @return void */ - public function testInvokeNoModifyNonHtmlResponse() + public function testInvokeNoModifyNonHtmlResponse(): void { $request = new ServerRequest([ 'url' => '/articles', @@ -251,13 +247,12 @@ public function testInvokeNoModifyNonHtmlResponse() * * @return void */ - public function testConfigIsPassed() + public function testConfigIsPassed(): void { $config = ['foo' => 'bar']; Configure::write('DebugKit', $config); $layer = new DebugKitMiddleware(); $prop = new ReflectionProperty(DebugKitMiddleware::class, 'service'); - $prop->setAccessible(true); $service = $prop->getValue($layer); $this->assertSame('bar', $service->getConfig('foo')); } diff --git a/tests/TestCase/Model/Behavior/TimedBehaviorTest.php b/tests/TestCase/Model/Behavior/TimedBehaviorTest.php index 5baf4b142..fb7d5346d 100644 --- a/tests/TestCase/Model/Behavior/TimedBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/TimedBehaviorTest.php @@ -33,7 +33,7 @@ class TimedBehaviorTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->Article = $this->fetchTable('Articles'); @@ -45,7 +45,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->Article); @@ -57,7 +57,7 @@ public function tearDown(): void * * @return void */ - public function testFindTimers() + public function testFindTimers(): void { $timers = DebugTimer::getAll(); $this->assertCount(1, $timers); @@ -76,7 +76,7 @@ public function testFindTimers() * * @return void */ - public function testSaveTimers() + public function testSaveTimers(): void { $timers = DebugTimer::getAll(); $this->assertCount(1, $timers); diff --git a/tests/TestCase/Model/Table/RequestTableTest.php b/tests/TestCase/Model/Table/RequestTableTest.php index 4bead8a79..8f144b27a 100644 --- a/tests/TestCase/Model/Table/RequestTableTest.php +++ b/tests/TestCase/Model/Table/RequestTableTest.php @@ -32,7 +32,7 @@ class RequestTableTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $connection = ConnectionManager::get('test'); @@ -44,7 +44,7 @@ public function setUp(): void * * @return void */ - public function testInitializeCreatesSchema() + public function testInitializeCreatesSchema(): void { $connection = ConnectionManager::get('test'); $stmt = $connection->execute('DROP TABLE IF EXISTS panels'); @@ -66,7 +66,7 @@ public function testInitializeCreatesSchema() * * @return void */ - public function testFindRecent() + public function testFindRecent(): void { $table = $this->fetchTable('DebugKit.Requests'); $query = $table->find('recent'); @@ -79,7 +79,7 @@ public function testFindRecent() * * @return void */ - public function testGc() + public function testGc(): void { /** @var \PHPUnit\Framework\MockObject\MockObject&\DebugKit\Model\Table\RequestsTable $requestsTableMock */ $requestsTableMock = $this->getMockForModel('DebugKit.Requests', ['shouldGc']); diff --git a/tests/TestCase/Model/Table/SqlTraceTraitTest.php b/tests/TestCase/Model/Table/SqlTraceTraitTest.php index 32fcfb856..d2e746ff5 100644 --- a/tests/TestCase/Model/Table/SqlTraceTraitTest.php +++ b/tests/TestCase/Model/Table/SqlTraceTraitTest.php @@ -50,7 +50,7 @@ protected function setUp(): void $this->debug = Configure::read('App.debug', true); } - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); Configure::write('App.debug', $this->debug); @@ -59,7 +59,7 @@ public function tearDown(): void /** * Verify file name when calling find() */ - public function testFind() + public function testFind(): void { foreach ($this->tables as $table) { $table = $this->fetchTable($table); @@ -71,7 +71,7 @@ public function testFind() /** * Verify file name when calling query()/select() */ - public function testQuery() + public function testQuery(): void { foreach ($this->tables as $table) { $table = $this->fetchTable($table); @@ -83,7 +83,7 @@ public function testQuery() /** * Verify file name when calling update() */ - public function testUpdate() + public function testUpdate(): void { foreach ($this->tables as $table) { $table = $this->fetchTable($table); @@ -95,7 +95,7 @@ public function testUpdate() /** * Verify file name when calling delete() */ - public function testDelete() + public function testDelete(): void { foreach ($this->tables as $table) { $table = $this->fetchTable($table); diff --git a/tests/TestCase/Panel/CachePanelTest.php b/tests/TestCase/Panel/CachePanelTest.php index 34b1aea70..3b3b5b420 100644 --- a/tests/TestCase/Panel/CachePanelTest.php +++ b/tests/TestCase/Panel/CachePanelTest.php @@ -33,7 +33,7 @@ class CachePanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new CachePanel(); @@ -45,7 +45,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); Cache::drop('debug_kit_test'); @@ -57,7 +57,7 @@ public function tearDown(): void * * @return void */ - public function testInitialize() + public function testInitialize(): void { $this->panel->initialize(); @@ -71,7 +71,7 @@ public function testInitialize() * * @return void */ - public function testInitializeNoProxyIncompleteConfig() + public function testInitializeNoProxyIncompleteConfig(): void { $data = ['duration' => '+2 seconds']; Cache::setConfig('incomplete', $data); @@ -86,7 +86,7 @@ public function testInitializeNoProxyIncompleteConfig() * * @return void */ - public function testInitializeIncompleteData() + public function testInitializeIncompleteData(): void { Cache::setConfig('incomplete', ['duration' => '+2 seconds']); $this->panel->initialize(); @@ -100,7 +100,7 @@ public function testInitializeIncompleteData() * * @return void */ - public function testInitializeTwiceNoDoubleProxy() + public function testInitializeTwiceNoDoubleProxy(): void { $this->panel->initialize(); $result = Cache::pool('debug_kit_test'); @@ -111,7 +111,7 @@ public function testInitializeTwiceNoDoubleProxy() $this->assertSame($result2, $result); } - public function testInitializePreserveGlobalConfig() + public function testInitializePreserveGlobalConfig(): void { $this->panel->initialize(); $result = Cache::getConfig('debug_kit_test'); diff --git a/tests/TestCase/Panel/DeprecationsPanelTest.php b/tests/TestCase/Panel/DeprecationsPanelTest.php index 4b4a5fd5d..6dfc2b44b 100644 --- a/tests/TestCase/Panel/DeprecationsPanelTest.php +++ b/tests/TestCase/Panel/DeprecationsPanelTest.php @@ -35,7 +35,7 @@ class DeprecationsPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); DeprecationsPanel::clearDeprecatedErrors(); @@ -43,7 +43,7 @@ public function setUp(): void $this->loadPlugins(['DebugKit']); $this->panel = new DeprecationsPanel(); - set_error_handler(function ($code, $message, $file, $line, $context = null) { + set_error_handler(function ($code, $message, $file, $line, $context = null): void { DeprecationsPanel::addDeprecatedError(compact('code', 'message', 'file', 'line', 'context')); }); try { @@ -56,7 +56,7 @@ public function setUp(): void } #[WithoutErrorHandler] - public function testShutdown() + public function testShutdown(): void { $event = new Event('Panel.shutdown'); $this->panel->shutdown($event); @@ -75,7 +75,7 @@ public function testShutdown() $this->assertArrayHasKey('line', $error); } - public function testSummary() + public function testSummary(): void { $this->assertSame('1', $this->panel->summary()); } diff --git a/tests/TestCase/Panel/EnvironmentPanelTest.php b/tests/TestCase/Panel/EnvironmentPanelTest.php index 3e6a10fbc..3073f63fe 100644 --- a/tests/TestCase/Panel/EnvironmentPanelTest.php +++ b/tests/TestCase/Panel/EnvironmentPanelTest.php @@ -34,7 +34,7 @@ class EnvironmentPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new EnvironmentPanel(); @@ -45,7 +45,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->panel); @@ -56,7 +56,7 @@ public function tearDown(): void * * @return void */ - public function testShutdown() + public function testShutdown(): void { $controller = new stdClass(); $event = new Event('Controller.shutdown', $controller); diff --git a/tests/TestCase/Panel/IncludePanelTest.php b/tests/TestCase/Panel/IncludePanelTest.php index 776abb62b..6163e8e30 100644 --- a/tests/TestCase/Panel/IncludePanelTest.php +++ b/tests/TestCase/Panel/IncludePanelTest.php @@ -34,10 +34,10 @@ class IncludePanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); - $this->deprecated(function () { + $this->deprecated(function (): void { $this->panel = new IncludePanel(); }); } @@ -48,7 +48,7 @@ public function setUp(): void * @return void */ #[WithoutErrorHandler] - public function testShutdown() + public function testShutdown(): void { $this->panel->shutdown(new Event('Controller.shutdown')); @@ -66,7 +66,7 @@ public function testShutdown() * @return void */ #[WithoutErrorHandler] - public function testSummary() + public function testSummary(): void { $total = $this->panel->summary(); $this->assertEquals(5, $total); diff --git a/tests/TestCase/Panel/LogPanelTest.php b/tests/TestCase/Panel/LogPanelTest.php index 3df4fe034..0afa2ba3b 100644 --- a/tests/TestCase/Panel/LogPanelTest.php +++ b/tests/TestCase/Panel/LogPanelTest.php @@ -34,7 +34,7 @@ class LogPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new LogPanel(); @@ -45,7 +45,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); Log::drop('debug_kit_log_panel'); @@ -56,7 +56,7 @@ public function tearDown(): void * * @return void */ - public function testInitialize() + public function testInitialize(): void { $this->panel->initialize(); @@ -70,7 +70,7 @@ public function testInitialize() * * @return void */ - public function testData() + public function testData(): void { $this->panel->initialize(); Log::write('error', 'Test'); @@ -90,7 +90,7 @@ public function testData() * * @return void */ - public function testSummary() + public function testSummary(): void { $this->panel->initialize(); diff --git a/tests/TestCase/Panel/PackagesPanelTest.php b/tests/TestCase/Panel/PackagesPanelTest.php index ceaaee237..98f49474a 100644 --- a/tests/TestCase/Panel/PackagesPanelTest.php +++ b/tests/TestCase/Panel/PackagesPanelTest.php @@ -34,7 +34,7 @@ class PackagesPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new PackagesPanel(); @@ -45,7 +45,7 @@ public function setUp(): void * * @return array */ - public static function packagesProvider() + public static function packagesProvider(): array { return [ 'requirements' => ['packages'], @@ -59,7 +59,7 @@ public static function packagesProvider() * @return void */ #[DataProvider('packagesProvider')] - public function testData($package) + public function testData(string $package): void { $data = $this->panel->data(); $this->assertArrayHasKey($package, $data); diff --git a/tests/TestCase/Panel/RequestPanelTest.php b/tests/TestCase/Panel/RequestPanelTest.php index 1382b49cf..50e5dc566 100644 --- a/tests/TestCase/Panel/RequestPanelTest.php +++ b/tests/TestCase/Panel/RequestPanelTest.php @@ -35,7 +35,7 @@ class RequestPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new RequestPanel(); @@ -46,7 +46,7 @@ public function setUp(): void * * @return void */ - public function testShutdownSkipAttributes() + public function testShutdownSkipAttributes(): void { $request = new ServerRequest([ 'url' => '/', @@ -55,7 +55,7 @@ public function testShutdownSkipAttributes() ]); $request = $request ->withAttribute('ok', 'string') - ->withAttribute('closure', function () { + ->withAttribute('closure', function (): void { }); $controller = new Controller($request); diff --git a/tests/TestCase/Panel/RoutesPanelTest.php b/tests/TestCase/Panel/RoutesPanelTest.php index 96cab2cdf..c0821dcb8 100644 --- a/tests/TestCase/Panel/RoutesPanelTest.php +++ b/tests/TestCase/Panel/RoutesPanelTest.php @@ -33,7 +33,7 @@ class RoutesPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -54,7 +54,7 @@ public function setUp(): void * * @return void */ - public function testSummary() + public function testSummary(): void { $this->panel->initialize(); $this->assertSame('4', $this->panel->summary()); diff --git a/tests/TestCase/Panel/SessionPanelTest.php b/tests/TestCase/Panel/SessionPanelTest.php index 8341f4a17..f43d81145 100644 --- a/tests/TestCase/Panel/SessionPanelTest.php +++ b/tests/TestCase/Panel/SessionPanelTest.php @@ -37,7 +37,7 @@ class SessionPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new SessionPanel(); @@ -49,7 +49,7 @@ public function setUp(): void * @return void */ #[WithoutErrorHandler] - public function testShutdownSkipAttributes() + public function testShutdownSkipAttributes(): void { $session = new Session(); $session->write('test', 123); @@ -59,7 +59,7 @@ public function testShutdownSkipAttributes() $controller = new Controller($request); $event = new Event('Controller.shutdown', $controller); - $this->deprecated(function () use ($event) { + $this->deprecated(function () use ($event): void { $this->panel->shutdown($event); }); diff --git a/tests/TestCase/Panel/SqlLogPanelTest.php b/tests/TestCase/Panel/SqlLogPanelTest.php index a9b0d6ab4..4ca4a855a 100644 --- a/tests/TestCase/Panel/SqlLogPanelTest.php +++ b/tests/TestCase/Panel/SqlLogPanelTest.php @@ -40,14 +40,14 @@ class SqlLogPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new SqlLogPanel(); $this->logger = ConnectionManager::get('test')->getDriver()->getLogger(); } - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); @@ -61,7 +61,7 @@ public function tearDown(): void * * @return void */ - public function testInitializeTwiceNoDoubleProxy() + public function testInitializeTwiceNoDoubleProxy(): void { $this->panel->initialize(); $db = ConnectionManager::get('test'); @@ -78,7 +78,7 @@ public function testInitializeTwiceNoDoubleProxy() * * @return void */ - public function testInitializePassesIncludeSchema() + public function testInitializePassesIncludeSchema(): void { Configure::write('DebugKit.includeSchemaReflection', true); $this->panel->initialize(); @@ -87,7 +87,6 @@ public function testInitializePassesIncludeSchema() $this->assertInstanceOf('DebugKit\Database\Log\DebugLog', $logger); $property = new ReflectionProperty($logger, '_includeSchema'); - $property->setAccessible(true); $this->assertTrue($property->getValue($logger)); } @@ -96,7 +95,7 @@ public function testInitializePassesIncludeSchema() * * @return void */ - public function testData() + public function testData(): void { $this->panel->initialize(); @@ -113,7 +112,7 @@ public function testData() * * @return void */ - public function testSummary() + public function testSummary(): void { $this->panel->initialize(); @@ -130,7 +129,7 @@ public function testSummary() * * @return void */ - public function testWithSimpleConnection() + public function testWithSimpleConnection(): void { ConnectionManager::setConfig('simple', [ 'className' => 'DebugKit\TestApp\Stub\SimpleConnectionStub', diff --git a/tests/TestCase/Panel/VariablesPanelTest.php b/tests/TestCase/Panel/VariablesPanelTest.php index 62cf4529c..417268c22 100644 --- a/tests/TestCase/Panel/VariablesPanelTest.php +++ b/tests/TestCase/Panel/VariablesPanelTest.php @@ -37,7 +37,7 @@ class VariablesPanelTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->panel = new VariablesPanel(); @@ -48,7 +48,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->panel); @@ -59,7 +59,7 @@ public function tearDown(): void * * @return void */ - public function testShutdown() + public function testShutdown(): void { $requests = $this->getTableLocator()->get('Requests'); $query = $requests->find('all'); diff --git a/tests/TestCase/ToolbarServiceTest.php b/tests/TestCase/ToolbarServiceTest.php index 789d30f08..93b6c1e14 100644 --- a/tests/TestCase/ToolbarServiceTest.php +++ b/tests/TestCase/ToolbarServiceTest.php @@ -45,9 +45,6 @@ class ToolbarServiceTest extends TestCase 'plugin.DebugKit.Panels', ]; - /** - * @var bool - */ protected bool $restore = false; /** @@ -60,7 +57,7 @@ class ToolbarServiceTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->events = new EventManager(); @@ -76,7 +73,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); putenv('HTTP_HOST='); @@ -88,7 +85,7 @@ public function tearDown(): void * * @return void */ - public function testLoadPanels() + public function testLoadPanels(): void { $bar = new ToolbarService($this->events, []); $bar->loadPanels(); @@ -103,7 +100,7 @@ public function testLoadPanels() * * @return void */ - public function testDisablePanels() + public function testDisablePanels(): void { $bar = new ToolbarService($this->events, ['panels' => [ 'DebugKit.SqlLog' => false, @@ -122,7 +119,7 @@ public function testDisablePanels() * * @return void */ - public function testInitializePanels() + public function testInitializePanels(): void { Log::drop('debug_kit_log_panel'); $bar = new ToolbarService($this->events, []); @@ -139,7 +136,7 @@ public function testInitializePanels() * * @return void */ - public function testSaveDataIgnoreDebugKit() + public function testSaveDataIgnoreDebugKit(): void { $request = new Request([ 'url' => '/debug_kit/panel/abc123', @@ -160,7 +157,7 @@ public function testSaveDataIgnoreDebugKit() * * @return void */ - public function testSaveDataIgnoreDebugKitDashedUrl() + public function testSaveDataIgnoreDebugKitDashedUrl(): void { $request = new Request([ 'url' => '/debug-kit/panel/abc123', @@ -194,7 +191,7 @@ public function testSaveDataIgnoreDebugKitDashedUrl() * * @return void */ - public function testSaveDataIgnorePaths() + public function testSaveDataIgnorePaths(): void { $request = new Request([ 'url' => '/foo.jpg', @@ -228,7 +225,7 @@ public function testSaveDataIgnorePaths() * * @return void */ - public function testSaveData() + public function testSaveData(): void { $request = new Request([ 'url' => '/articles', @@ -272,7 +269,7 @@ public function testSaveData() * * @return void */ - public function testSaveDataMissingConnection() + public function testSaveDataMissingConnection(): void { $restore = ConnectionManager::getConfig('test_debug_kit'); ConnectionManager::drop('test_debug_kit'); @@ -300,7 +297,7 @@ public function testSaveDataMissingConnection() * * @return void */ - public function testInjectScriptsLastBodyTag() + public function testInjectScriptsLastBodyTag(): void { $request = new Request([ 'url' => '/articles', @@ -335,7 +332,7 @@ public function testInjectScriptsLastBodyTag() * * @return void */ - public function testInjectScriptsFileBodies() + public function testInjectScriptsFileBodies(): void { $response = new Response([ 'statusCode' => 200, @@ -357,7 +354,7 @@ public function testInjectScriptsFileBodies() * * @return void */ - public function testInjectScriptsStreamBodies() + public function testInjectScriptsStreamBodies(): void { $response = new Response([ 'statusCode' => 200, @@ -378,7 +375,7 @@ public function testInjectScriptsStreamBodies() * * @return void */ - public function testInjectScriptsNoModifyResponse() + public function testInjectScriptsNoModifyResponse(): void { $request = new Request([ 'url' => '/articles/view/123', @@ -406,7 +403,7 @@ public function testInjectScriptsNoModifyResponse() * * @return void */ - public function testIsEnabled() + public function testIsEnabled(): void { Configure::write('debug', true); $bar = new ToolbarService($this->events, []); @@ -425,10 +422,10 @@ public function testIsEnabled() * @return void */ #[DataProvider('domainsProvider')] - public function testIsEnabledProductionEnv(string $domain, bool $isEnabled) + public function testIsEnabledProductionEnv(string $domain, bool $isEnabled): void { Configure::write('debug', true); - putenv("HTTP_HOST=$domain"); + putenv('HTTP_HOST=' . $domain); $bar = new ToolbarService($this->events, []); $this->assertSame($isEnabled, $bar->isEnabled()); @@ -467,12 +464,12 @@ public static function domainsProvider(): array * * @return void */ - public function testIsEnabledProductionEnvCustomTld() + public function testIsEnabledProductionEnvCustomTld(): void { $domain = 'myapp.foobar'; Configure::write('debug', true); - putenv("HTTP_HOST=$domain"); + putenv('HTTP_HOST=' . $domain); $bar = new ToolbarService($this->events, []); $this->assertFalse($bar->isEnabled()); @@ -485,7 +482,7 @@ public function testIsEnabledProductionEnvCustomTld() * * @return void */ - public function testIsEnabledForceEnable() + public function testIsEnabledForceEnable(): void { Configure::write('debug', false); $bar = new ToolbarService($this->events, ['forceEnable' => true]); @@ -497,11 +494,11 @@ public function testIsEnabledForceEnable() * * @return void */ - public function testIsEnabledForceEnableCallable() + public function testIsEnabledForceEnableCallable(): void { Configure::write('debug', false); $bar = new ToolbarService($this->events, [ - 'forceEnable' => function () { + 'forceEnable' => function (): bool { return true; }, ]); @@ -513,7 +510,7 @@ public function testIsEnabledForceEnableCallable() * * @return void */ - public function testSaveDataSerializationError() + public function testSaveDataSerializationError(): void { $request = new Request([ 'url' => '/articles', @@ -534,7 +531,7 @@ public function testSaveDataSerializationError() 'className' => SimplePanel::class, ]); // Mock the data() method to return something problematic - $panel->setData(['closure' => fn() => 'test']); + $panel->setData(['closure' => fn(): string => 'test']); $row = $bar->saveData($request, $response); $this->assertNotEmpty($row, 'Should save data even with serialization errors'); diff --git a/tests/TestCase/View/Helper/CredentialsHelperTest.php b/tests/TestCase/View/Helper/CredentialsHelperTest.php index 904c97ddb..8762b254a 100644 --- a/tests/TestCase/View/Helper/CredentialsHelperTest.php +++ b/tests/TestCase/View/Helper/CredentialsHelperTest.php @@ -41,7 +41,7 @@ class CredentialsHelperTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -56,18 +56,17 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->Helper); } /** - * @dataProvider credentialsProvider * @return void */ #[DataProvider('credentialsProvider')] - public function testFilter($in, $out) + public function testFilter(string|array|null $in, string|array|null $out): void { $this->assertSame($out, $this->Helper->filter($in)); } @@ -77,7 +76,7 @@ public function testFilter($in, $out) * * @return array input, expected output */ - public static function credentialsProvider() + public static function credentialsProvider(): array { return [ [null, null], diff --git a/tests/TestCase/View/Helper/SimpleGraphHelperTest.php b/tests/TestCase/View/Helper/SimpleGraphHelperTest.php index 275c7bf10..de216c40b 100644 --- a/tests/TestCase/View/Helper/SimpleGraphHelperTest.php +++ b/tests/TestCase/View/Helper/SimpleGraphHelperTest.php @@ -41,7 +41,7 @@ class SimpleGraphHelperTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); Router::createRouteBuilder('/')->connect('/{controller}/{action}'); @@ -58,7 +58,7 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->Graph); @@ -69,7 +69,7 @@ public function tearDown(): void * * @return void */ - public function testBar() + public function testBar(): void { $output = $this->Graph->bar(10, 0); $expected = [ @@ -94,7 +94,7 @@ public function testBar() * * @return void */ - public function testBarOffset() + public function testBarOffset(): void { $output = $this->Graph->bar(10, 10); $expected = [ @@ -119,7 +119,7 @@ public function testBarOffset() * * @return void */ - public function testBarWithFloat() + public function testBarWithFloat(): void { $output = $this->Graph->bar(10.5, 10.5); $expected = [ diff --git a/tests/TestCase/View/Helper/ToolbarHelperTest.php b/tests/TestCase/View/Helper/ToolbarHelperTest.php index 3f86bf0fc..bffd82e66 100644 --- a/tests/TestCase/View/Helper/ToolbarHelperTest.php +++ b/tests/TestCase/View/Helper/ToolbarHelperTest.php @@ -15,6 +15,7 @@ */ namespace DebugKit\Test\TestCase\View\Helper; +use Cake\Error\Debug\NodeInterface; use Cake\Error\Debugger; use Cake\Http\ServerRequest as Request; use Cake\Routing\Router; @@ -44,7 +45,7 @@ class ToolbarHelperTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); Router::createRouteBuilder('/')->connect('/{controller}/{action}'); @@ -61,17 +62,17 @@ public function setUp(): void * * @return void */ - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); unset($this->Toolbar); } - public function testDumpNodesSorted() + public function testDumpNodesSorted(): void { $path = '//*[@class="cake-debug-array-item"]/*[@class="cake-debug-string"]'; $data = ['z' => 1, 'a' => 99, 'm' => 123]; - $nodes = array_map(function ($v) { + $nodes = array_map(function (int $v): NodeInterface { return Debugger::exportVarAsNodes($v); }, $data); $result = $this->Toolbar->dumpNodes($nodes); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index e43e2036c..9a2e5b2b0 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -22,7 +22,7 @@ use DebugKit\DebugKitPlugin; use function Cake\Core\env; -require_once 'vendor/autoload.php'; +require_once dirname(__DIR__) . '/vendor/autoload.php'; // Path constants to a few helpful things. if (!defined('DS')) { diff --git a/tests/test_app/Application.php b/tests/test_app/Application.php index d7f67d29c..255c93d39 100644 --- a/tests/test_app/Application.php +++ b/tests/test_app/Application.php @@ -41,7 +41,6 @@ public function bootstrap(): void } /** - * @param \Cake\Routing\RouteBuilder $routes * @return void */ public function routes(RouteBuilder $routes): void diff --git a/tests/test_app/Controller/DebugKitTestController.php b/tests/test_app/Controller/DebugKitTestController.php index b71ad63b2..954e8cff7 100644 --- a/tests/test_app/Controller/DebugKitTestController.php +++ b/tests/test_app/Controller/DebugKitTestController.php @@ -54,7 +54,7 @@ class DebugKitTestController extends Controller * * @return string */ - public function request_action_return() + public function request_action_return(): string { $this->autoRender = false; @@ -64,7 +64,7 @@ public function request_action_return() /** * Render Request Action */ - public function request_action_render() + public function request_action_render(): void { $this->set('test', 'I have been rendered.'); } diff --git a/tests/test_app/Form/TestForm.php b/tests/test_app/Form/TestForm.php index d7c006303..c66018697 100644 --- a/tests/test_app/Form/TestForm.php +++ b/tests/test_app/Form/TestForm.php @@ -36,7 +36,7 @@ public function validationDefault(Validator $validator): Validator return $validator ->requirePresence('accept') ->add('accept', 'accept', [ - 'rule' => function ($value) { + 'rule' => function ($value): string { return 'always fail validation'; }, ]); diff --git a/tests/test_app/Panel/TestPanel.php b/tests/test_app/Panel/TestPanel.php index eb4f76152..e1386ce24 100644 --- a/tests/test_app/Panel/TestPanel.php +++ b/tests/test_app/Panel/TestPanel.php @@ -31,10 +31,8 @@ class TestPanel extends DebugPanel { /** * Startup - * - * @param Controller $controller */ - public function startup(Controller $controller) + public function startup(Controller $controller): void { $controller->testPanel = true; }