Skip to content
Draft

rector #1062

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 3 additions & 3 deletions config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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']);
Expand Down
74 changes: 74 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);

use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector;
use Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector;
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
use Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector;
use Rector\CodingStyle\Rector\Catch_\CatchExceptionNameMatchingTypeRector;
use Rector\CodingStyle\Rector\ClassMethod\NewlineBeforeNewAssignSetRector;
use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector;
use Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector;
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
use Rector\Php74\Rector\Closure\ClosureToArrowFunctionRector;
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
use Rector\Php80\Rector\Class_\StringableForToStringRector;
use Rector\Set\ValueObject\SetList;
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictFluentReturnRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictTypedCallRector;
use Rector\TypeDeclaration\Rector\Function_\AddFunctionVoidReturnTypeWhereNoReturnRector;

$cacheDir = getenv('RECTOR_CACHE_DIR') ?: sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'rector';

return RectorConfig::configure()
->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,
]);
16 changes: 4 additions & 12 deletions src/Cache/Engine/DebugEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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));
}

/**
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down
6 changes: 2 additions & 4 deletions src/Command/BenchmarkCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ public static function getDescription(): string

/**
* The console io
*
* @var \Cake\Console\ConsoleIo
*/
protected ConsoleIo $io;

Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/Controller/ComposerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, '<highlight>') !== false) {
if (str_contains($dependency, '<highlight>')) {
$packages['semverCompatible'][] = $dependency;
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
];

Expand Down
29 changes: 12 additions & 17 deletions src/Controller/MailPreviewController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -120,22 +121,22 @@ 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);
$this->set('email', $email);
$this->set('plugin', $plugin);
$this->set('part', $this->findPreferredPart($email, $part));

if ($restore) {
if ($restore instanceof ServerRequest) {
Router::setRequest($restore);
}

Expand Down Expand Up @@ -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'), ''];
Expand All @@ -201,7 +202,7 @@ protected function getMailPreviewClasses(): CollectionInterface
yield $plugin => $path;
}
})
->unfold(function ($path, $plugin) {
->unfold(function (string $path, string $plugin) {
/** @var list<string> $files */
$files = glob($path . '*Preview.php');
foreach ($files as $file) {
Expand All @@ -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;
}

/**
Expand All @@ -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;
}
}
Expand All @@ -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();
Expand Down
32 changes: 10 additions & 22 deletions src/Database/Log/DebugLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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.');
}
}
Loading
Loading