Swiss knife in the pocket of every upgrade architect!
composer require rector/swiss-knife --dev- 1. Check your Code for Git Merge Conflicts
- 2. Detect Commented Code
- 3. Reach full PSR-4
- 4. Finalize classes without children
- 5. Privatize local class constants
- 6. Spots Fake Traits
- 7. Split huge Symfony config to per-package in directory
- 8. Generate Symfony Smoke Tests
- 9. Detect Duplicated Code
Do you use Git? Then merge conflict markers are the last thing you want to see in pushed code:
<<<<<<< HEAD
Add this command to CI to spot these:
vendor/bin/swiss-knife check-conflicts .You can skip paths with the --exclude option:
vendor/bin/swiss-knife check-conflicts . --exclude vendor --exclude tests/fixturesHave you ever forgotten commented code in your project?
// foreach ($matches as $match) {
// $content = str_replace($match[0], $match[2], $content);
// }No more! Add this command to CI to spot these:
vendor/bin/swiss-knife check-commented-code <directory>
vendor/bin/swiss-knife check-commented-code packages --line-limit 5 --skip-file '*Controller.php'To make PSR-4 work properly, each class must be in its own file. This command makes it easy to spot multiple classes in a single file:
vendor/bin/swiss-knife find-multi-classes srcIs your class in wrong namespace? Make it match your PSR-4 root:
vendor/bin/swiss-knife namespace-to-psr-4 src --namespace-root "App\\"This will update all files in your /src directory, to starts with App\\ and follow full PSR-4 path:
# file path: src/Repository/TalkRepository.php
-namespace Model;
+namespace App\Repository;
...Do you want to finalize all classes that don't have children?
vendor/bin/swiss-knife finalize-classes src testsDo you use mocks but not bypass final yet?
vendor/bin/swiss-knife finalize-classes src tests --skip-mockedThis will keep mocked classes non-final, so PHPUnit can extend them internally.
Do you want to skip file or two?
vendor/bin/swiss-knife finalize-classes src tests --skip-file src/SpecialProxy.phpSkip is also support with fnmatch() patterns:
vendor/bin/swiss-knife finalize-classes src tests --skip-file '*Controller.php'PHPStan can report unused private class constants, but it skips all the public ones. Do you have lots of class constants, all of them public but want to narrow scope to privates?
vendor/bin/swiss-knife privatize-constants src testThis command will:
- find all class constant usages
- scans classes and constants
- makes those constant used locally
private
That way all the constants not used outside will be made private safely.
Do you have a huge Symfony config file that is hard to navigate? Do you want to split it to per-package files?
Before - one huge config/config_dev.php with many extensions in a single file:
<?php
declare(strict_types=1);
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->extension('framework', [
'secret' => '%env(APP_SECRET)%',
'test' => true,
]);
$containerConfigurator->extension('doctrine', [
'dbal' => [
'url' => '%env(DATABASE_URL)%',
],
]);
$containerConfigurator->extension('monolog', [
'handlers' => [
'main' => [
'type' => 'stream',
'path' => '%kernel.logs_dir%/%kernel.environment%.log',
],
],
]);
};Run the command:
vendor/bin/swiss-knife split-config-per-package config/config_dev.php --output-dir config/packages/devAfter - the original config only imports the per-package files:
<?php
declare(strict_types=1);
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->import(__DIR__ . '/packages/dev/*');
};And each extension lives in its own file, e.g. config/packages/dev/doctrine.php:
<?php
declare(strict_types=1);
return static function (Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->extension('doctrine', [
'dbal' => [
'url' => '%env(DATABASE_URL)%',
],
]);
};All the extensions will be extracted to separate files in config/packages/dev directory, making them much more readable.
Cover your Symfony app with smoke tests in seconds. This command scans your composer.json, picks the matching test templates, and drops them under tests/Unit/Smoke (or your project's equivalent unit-tests directory).
vendor/bin/swiss-knife generate-symfony-smoke-testsThe command will:
- detect your unit tests directory and create a
Smokesub-directory - generate a
ServiceContainerTestthat boots the kernel and instantiates every service to catch container misconfiguration early - add a shared
AbstractContainerTestCasewith a typedgetService()helper - adjust the namespace and
Kernelclass in the templates to match your project (usesApp\Kernel,AppKernel, orKernel, whichever exists)
Existing files are never overwritten, so the command is safe to re-run.
The generated ServiceContainerTest boots the kernel and asserts every service can be instantiated:
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Smoke;
use Throwable;
final class ServiceContainerTest extends AbstractContainerTestCase
{
public function testServiceConstruction(): void
{
$serviceIds = self::$container->getServiceIds();
$checkedServiceCount = 0;
foreach ($serviceIds as $serviceId) {
if ($this->isDynamicService($serviceId)) {
continue;
}
try {
self::$container->get($serviceId);
} catch (Throwable $throwable) {
$this->fail(sprintf('Service "%s" could not be created because:%s%s', $serviceId, PHP_EOL, $throwable->getMessage()));
}
++$checkedServiceCount;
}
// @todo update this number to match your service count
$this->assertSame(100000, $checkedServiceCount);
}
private function isDynamicService(string $serviceId): bool
{
if (str_contains($serviceId, 'session')) {
return true;
}
if (str_starts_with($serviceId, 'doctrine.')) {
return true;
}
return in_array(
$serviceId,
['kernel', 'database_connection', 'event_dispatcher'],
true
);
}
}Spot copy-pasted code blocks with a token-based detector, a small clone of phpcpd. Add it to CI to fail when a large copy-pasted block is added:
vendor/bin/swiss-knife duplicated-code src
vendor/bin/swiss-knife duplicated-code src rules --min-tokens 150 --min-lines 5Options:
--min-linesminimum lines of a reported clone (default5)--min-tokensminimum tokens of a reported clone (default70)--fuzzyignore variable names when matching--skip-filefile paths or masks to skip
Exit code is 1 when clones are found, 0 otherwise.
Measure lines of code and structure size of your project - files, classes, methods, constants and more:
vendor/bin/swiss-knife measure src
vendor/bin/swiss-knife measure src tests --exclude tests/fixturesOptions:
--excludepaths to exclude--shortprint short metrics only--longestshow top 10 longest files--allow-vendorallow the/vendordirectory to be scanned--jsonoutput in JSON format
Count PHP features used in the project, grouped by the PHP version that introduced them. Handy to see how modern your code is before an upgrade:
vendor/bin/swiss-knife features srcOptions:
--jsonoutput in JSON format
That's it!
Happy coding!