Skip to content

Commit acdcb21

Browse files
committed
rector
1 parent b10658e commit acdcb21

File tree

81 files changed

+373
-421
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+373
-421
lines changed

composer.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@
6666
"stan": "@phpstan",
6767
"stan-baseline": "tools/phpstan --generate-baseline",
6868
"stan-setup": "phive install",
69+
"rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.3.1\" && mv composer.backup composer.json",
70+
"rector-check": "vendor/bin/rector process --dry-run",
71+
"rector-fix": "vendor/bin/rector process",
6972
"test": "phpunit"
7073
},
7174
"minimum-stability": "dev",

config/routes.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
use Cake\Routing\Route\DashedRoute;
44
use Cake\Routing\RouteBuilder;
55

6-
return function (RouteBuilder $routes) {
7-
$routes->plugin('DebugKit', ['path' => '/debug-kit'], function (RouteBuilder $routes) {
6+
return function (RouteBuilder $routes): void {
7+
$routes->plugin('DebugKit', ['path' => '/debug-kit'], function (RouteBuilder $routes): void {
88
$routes->setExtensions('json');
99
$routes->setRouteClass(DashedRoute::class);
1010

@@ -37,7 +37,7 @@
3737
$routes->scope(
3838
'/mail-preview',
3939
['controller' => 'MailPreview'],
40-
function (RouteBuilder $routes) {
40+
function (RouteBuilder $routes): void {
4141
$routes->connect('/', ['action' => 'index']);
4242
$routes->connect('/preview', ['action' => 'email']);
4343
$routes->connect('/preview/*', ['action' => 'email']);

rector.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
use Rector\Caching\ValueObject\Storage\FileCacheStorage;
5+
use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector;
6+
use Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector;
7+
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
8+
use Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector;
9+
use Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector;
10+
use Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector;
11+
use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector;
12+
use Rector\Config\RectorConfig;
13+
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector;
14+
use Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector;
15+
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
16+
use Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector;
17+
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
18+
use Rector\Php80\Rector\Class_\StringableForToStringRector;
19+
use Rector\Set\ValueObject\SetList;
20+
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
21+
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
22+
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictFluentReturnRector;
23+
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedCallRector;
24+
use Rector\TypeDeclaration\Rector\Function_\AddFunctionVoidReturnTypeWhereNoReturnRector;
25+
26+
$cacheDir = getenv('RECTOR_CACHE_DIR') ?: sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'rector';
27+
28+
return RectorConfig::configure()
29+
->withPaths([
30+
__DIR__ . '/config',
31+
__DIR__ . '/src',
32+
__DIR__ . '/tests',
33+
])
34+
35+
->withCache(
36+
cacheClass: FileCacheStorage::class,
37+
cacheDirectory: $cacheDir,
38+
)
39+
40+
->withPhpSets()
41+
->withAttributesSets()
42+
43+
->withSets([
44+
SetList::CODE_QUALITY,
45+
SetList::CODING_STYLE,
46+
SetList::DEAD_CODE,
47+
SetList::EARLY_RETURN,
48+
SetList::INSTANCEOF,
49+
SetList::TYPE_DECLARATION,
50+
])
51+
52+
->withSkip([
53+
__DIR__ . '/tests/test_app/templates',
54+
__DIR__ . '/tests/test_app/Plugin/TestPlugin/templates',
55+
56+
ClassPropertyAssignToConstructorPromotionRector::class,
57+
CatchExceptionNameMatchingTypeRector::class,
58+
ClosureToArrowFunctionRector::class,
59+
RemoveUselessReturnTagRector::class,
60+
ReturnTypeFromStrictFluentReturnRector::class,
61+
NewlineAfterStatementRector::class,
62+
StringClassNameToClassConstantRector::class,
63+
ReturnTypeFromStrictTypedCallRector::class,
64+
ParamTypeByMethodCallTypeRector::class,
65+
AddFunctionVoidReturnTypeWhereNoReturnRector::class,
66+
StringableForToStringRector::class,
67+
CompactToVariablesRector::class,
68+
SplitDoubleAssignRector::class,
69+
ChangeOrIfContinueToMultiContinueRector::class,
70+
ExplicitBoolCompareRector::class,
71+
NewlineBeforeNewAssignSetRector::class,
72+
SimplifyEmptyCheckOnEmptyArrayRector::class,
73+
DisallowedEmptyRuleFixerRector::class,
74+
]);

src/Cache/Engine/DebugEngine.php

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,19 +28,11 @@ class DebugEngine extends CacheEngine
2828
{
2929
/**
3030
* Proxied engine
31-
*
32-
* @var \Cake\Cache\CacheEngine
3331
*/
3432
protected CacheEngine $_engine;
3533

36-
/**
37-
* @var \Psr\Log\LoggerInterface
38-
*/
3934
protected LoggerInterface $logger;
4035

41-
/**
42-
* @var string
43-
*/
4436
protected string $name;
4537

4638
/**
@@ -132,9 +124,9 @@ protected function track(string $metric): void
132124
*/
133125
protected function log(string $operation, float $duration, ?string $key = null): void
134126
{
135-
$key = $key ? " `{$key}`" : '';
127+
$key = $key ? sprintf(' `%s`', $key) : '';
136128
$duration = number_format($duration, 5);
137-
$this->logger->log('info', ":{$this->name}: {$operation}{$key} - {$duration}ms");
129+
$this->logger->log('info', sprintf(':%s: %s%s - %sms', $this->name, $operation, $key, $duration));
138130
}
139131

140132
/**
@@ -180,7 +172,7 @@ public function get(string $key, mixed $default = null): mixed
180172
$metric = 'miss';
181173
}
182174

183-
$this->track("get {$metric}");
175+
$this->track('get ' . $metric);
184176
$this->log('get', $duration, $key);
185177

186178
return $result;
@@ -336,7 +328,7 @@ public function __toString(): string
336328
{
337329
if (isset($this->_engine)) {
338330
// phpcs:ignore SlevomatCodingStandard.Variables.UnusedVariable.UnusedVariable
339-
[$ns, $class] = namespaceSplit(get_class($this->_engine));
331+
[$ns, $class] = namespaceSplit($this->_engine::class);
340332

341333
return str_replace('Engine', '', $class);
342334
}

src/Command/BenchmarkCommand.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,6 @@ public static function getDescription(): string
4141

4242
/**
4343
* The console io
44-
*
45-
* @var \Cake\Console\ConsoleIo
4644
*/
4745
protected ConsoleIo $io;
4846

@@ -144,8 +142,8 @@ protected function _variance(array $times, bool $sample = true): float
144142
foreach ($times as $time) {
145143
$n += 1;
146144
$delta = $time - $mean;
147-
$mean = $mean + $delta / $n;
148-
$M2 = $M2 + $delta * ($time - $mean);
145+
$mean += $delta / $n;
146+
$M2 += $delta * ($time - $mean);
149147
}
150148

151149
if ($sample) {

src/Controller/ComposerController.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,10 @@ public function checkDependencies(): void
5555
$dependencies = array_filter(explode("\n", $output->fetch()));
5656
$packages = [];
5757
foreach ($dependencies as $dependency) {
58-
if (strpos($dependency, 'php_network_getaddresses') !== false) {
58+
if (str_contains($dependency, 'php_network_getaddresses')) {
5959
throw new RuntimeException('You have to be connected to the internet');
6060
}
61-
if (strpos($dependency, '<highlight>') !== false) {
61+
if (str_contains($dependency, '<highlight>')) {
6262
$packages['semverCompatible'][] = $dependency;
6363
continue;
6464
}

src/Controller/DashboardController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public function index(): void
4848
$requestsModel = $this->fetchTable('DebugKit.Requests');
4949

5050
$data = [
51-
'driver' => get_class($requestsModel->getConnection()->getDriver()),
51+
'driver' => $requestsModel->getConnection()->getDriver()::class,
5252
'rows' => $requestsModel->find()->count(),
5353
];
5454

src/Controller/MailPreviewController.php

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use Cake\Core\Plugin as CorePlugin;
2121
use Cake\Event\EventInterface;
2222
use Cake\Http\Exception\NotFoundException;
23+
use Cake\Http\ServerRequest;
2324
use Cake\Routing\Router;
2425
use Cake\Utility\Inflector;
2526
use DebugKit\Mailer\AbstractResult;
@@ -120,22 +121,22 @@ public function email(string $name, string $method): ?ResponseInterface
120121

121122
if ($partType) {
122123
$result = $this->respondWithPart($email, $partType);
123-
if ($restore) {
124+
if ($restore instanceof ServerRequest) {
124125
Router::setRequest($restore);
125126
}
126127

127128
return $result;
128129
}
129130

130-
$humanName = Inflector::humanize(Inflector::underscore($name) . "_$method");
131+
$humanName = Inflector::humanize(Inflector::underscore($name) . '_' . $method);
131132
/** @var string $part */
132133
$part = $this->request->getQuery('part');
133134
$this->set('title', $humanName);
134135
$this->set('email', $email);
135136
$this->set('plugin', $plugin);
136137
$this->set('part', $this->findPreferredPart($email, $part));
137138

138-
if ($restore) {
139+
if ($restore instanceof ServerRequest) {
139140
Router::setRequest($restore);
140141
}
141142

@@ -184,11 +185,11 @@ protected function getMailPreviews(): CollectionInterface
184185
protected function getMailPreviewClasses(): CollectionInterface
185186
{
186187
$pluginPaths = collection(CorePlugin::loaded())
187-
->reject(function ($plugin) {
188+
->reject(function ($plugin): bool {
188189
return $plugin === 'DebugKit';
189190
})
190-
->map(function ($plugin) {
191-
return [[CorePlugin::classPath($plugin) . 'Mailer/Preview/'], "$plugin."];
191+
->map(function (string $plugin): array {
192+
return [[CorePlugin::classPath($plugin) . 'Mailer/Preview/'], $plugin . '.'];
192193
});
193194

194195
$appPaths = [App::classPath('Mailer/Preview'), ''];
@@ -201,7 +202,7 @@ protected function getMailPreviewClasses(): CollectionInterface
201202
yield $plugin => $path;
202203
}
203204
})
204-
->unfold(function ($path, $plugin) {
205+
->unfold(function (string $path, string $plugin) {
205206
/** @var list<string> $files */
206207
$files = glob($path . '*Preview.php');
207208
foreach ($files as $file) {
@@ -223,13 +224,7 @@ protected function getMailPreviewClasses(): CollectionInterface
223224
*/
224225
protected function findPart(AbstractResult $email, string $partType): ?string
225226
{
226-
foreach ($email->getParts() as $part => $content) {
227-
if ($part === $partType) {
228-
return $content;
229-
}
230-
}
231-
232-
return null;
227+
return $email->getParts()[$partType] ?? null;
233228
}
234229

235230
/**
@@ -248,7 +243,7 @@ protected function findPreferredPart(AbstractResult $email, ?string $partType):
248243
}
249244

250245
if ($partType === null) {
251-
foreach ($email->getParts() as $part => $content) {
246+
foreach (array_keys($email->getParts()) as $part) {
252247
return $part;
253248
}
254249
}
@@ -268,12 +263,12 @@ protected function findPreferredPart(AbstractResult $email, ?string $partType):
268263
protected function findPreview(string $previewName, string $emailName, string $plugin = ''): PreviewResult
269264
{
270265
if ($plugin) {
271-
$plugin = "$plugin.";
266+
$plugin .= '.';
272267
}
273268

274269
$realClass = App::className($plugin . $previewName, 'Mailer/Preview');
275270
if (!$realClass) {
276-
throw new NotFoundException("Mailer preview $previewName not found");
271+
throw new NotFoundException(sprintf('Mailer preview %s not found', $previewName));
277272
}
278273
/** @var \DebugKit\Mailer\MailPreview $mailPreview */
279274
$mailPreview = new $realClass();

src/Database/Log/DebugLog.php

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -31,44 +31,32 @@ class DebugLog extends AbstractLogger
3131
{
3232
/**
3333
* Logs from the current request.
34-
*
35-
* @var array
3634
*/
3735
protected array $_queries = [];
3836

3937
/**
4038
* Decorated logger.
41-
*
42-
* @var \Psr\Log\LoggerInterface|null
4339
*/
4440
protected ?LoggerInterface $_logger = null;
4541

4642
/**
4743
* Name of the connection being logged.
48-
*
49-
* @var string
5044
*/
5145
protected string $_connectionName;
5246

5347
/**
5448
* Total time (ms) of all queries
55-
*
56-
* @var float
5749
*/
5850
protected float $_totalTime = 0;
5951

6052
/**
6153
* Set to true to capture schema reflection queries
6254
* in the SQL log panel.
63-
*
64-
* @var bool
6555
*/
6656
protected bool $_includeSchema = false;
6757

6858
/**
6959
* Whether a transaction is currently open or not.
70-
*
71-
* @var bool
7260
*/
7361
protected bool $inTransaction = false;
7462

@@ -137,7 +125,7 @@ public function log($level, string|Stringable $message, array $context = []): vo
137125
/** @var \Cake\Database\Log\LoggedQuery|object|null $query */
138126
$query = $context['query'] ?? null;
139127

140-
if ($this->_logger) {
128+
if ($this->_logger instanceof LoggerInterface) {
141129
$this->_logger->log($level, $message, $context);
142130
}
143131

@@ -206,18 +194,18 @@ protected function isSchemaQuery(LoggedQuery $query): bool
206194
$querystring = $query->jsonSerialize()['query'];
207195

208196
return // Multiple engines
209-
strpos($querystring, 'FROM information_schema') !== false ||
197+
str_contains((string)$querystring, 'FROM information_schema') ||
210198
// Postgres
211-
strpos($querystring, 'FROM pg_catalog') !== false ||
199+
str_contains((string)$querystring, 'FROM pg_catalog') ||
212200
// MySQL
213-
strpos($querystring, 'SHOW TABLE') === 0 ||
214-
strpos($querystring, 'SHOW FULL COLUMNS') === 0 ||
215-
strpos($querystring, 'SHOW INDEXES') === 0 ||
201+
str_starts_with((string)$querystring, 'SHOW TABLE') ||
202+
str_starts_with((string)$querystring, 'SHOW FULL COLUMNS') ||
203+
str_starts_with((string)$querystring, 'SHOW INDEXES') ||
216204
// Sqlite
217-
strpos($querystring, 'FROM sqlite_master') !== false ||
218-
strpos($querystring, 'PRAGMA') === 0 ||
205+
str_contains((string)$querystring, 'FROM sqlite_master') ||
206+
str_starts_with((string)$querystring, 'PRAGMA') ||
219207
// Sqlserver
220-
strpos($querystring, 'FROM INFORMATION_SCHEMA') !== false ||
221-
strpos($querystring, 'FROM sys.') !== false;
208+
str_contains((string)$querystring, 'FROM INFORMATION_SCHEMA') ||
209+
str_contains((string)$querystring, 'FROM sys.');
222210
}
223211
}

0 commit comments

Comments
 (0)