Automating the backslash prefixing for native PHP function calls
After reading the blog post Why does a backslash prefix improve PHP function call performance by Jeroen Deviaene I was looking for a way to automate it for the codebase of the Lean Package Validator, to shave off some miliseconds for it's CLI. The PHP Coding Standards Fixer has a rule named native_function_invocation which does the very exact task.
Configuring the PHP Coding Standards Fixer
.php-cs-fixer.php
<?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$finder = Finder::create()
->in([__DIR__, __DIR__ . DIRECTORY_SEPARATOR . 'tests']);
$rules = [
'psr_autoloading' => false,
'@PSR2' => true,
'phpdoc_order' => true,
'ordered_imports' => true,
'native_function_invocation' => [
'include' => ['@internal'],
'exclude' => ['file_put_contents']
]
];
$cacheDir = \getenv('HOME') ? \getenv('HOME') : __DIR__;
$config = new Config();
return $config->setRules($rules)
->setFinder($finder)
->setCacheFile($cacheDir . '/.php-cs-fixer.cache');
To make this rule executeable I needed to add the --allow-risky=yes option to the PHP Coding Standards Fixer calls in the two dedicated Composer scripts shown next.
composer.json
"scripts": {
"lpv:test": "phpunit",
"lpv:test-with-coverage": "export XDEBUG_MODE=coverage && phpunit --coverage-html coverage-reports",
"lpv:cs-fix": "php-cs-fixer --allow-risky=yes fix . -vv || true",
"lpv:cs-lint": "php-cs-fixer fix --diff --stop-on-violation --verbose --dry-run --allow-risky=yes",
"lpv:configure-commit-template": "git config --add commit.template .gitmessage",
"lpv:application-version-guard": "php bin/application-version --verify-tag-match=bin",
"lpv:application-phar-version-guard": "php bin/application-version --verify-tag-match=phar",
"lpv:static-analyse": "phpstan analyse --configuration phpstan.neon.dist",
"lpv:validate-gitattributes": "bin/lean-package-validator validate"
},
After running the lpv:cs-fix Composer script the first time the tests of the system under test started failing due to file_put_contents being prefixed with a backslash when using phpmock\MockBuilder's setName method, so I had to exclude it as shown in the PHP Coding Standards Fixer configuration above.
No comments:
Post a Comment