2

I've managed to enforce strict types, but now I need to declare them in every file.

phpcbf says it has 0 fixable issues upon running.

Is there a way to automatically add declare(strict_types = 1); to the top of every file?

ruleset.xml:

<?xml version="1.0"?>
<ruleset name="PrimaryStandard">
<description>Primary coding standard</description>
<rule ref="PSR2"/>
<rule ref="PSR12"/>
<rule ref="Generic.PHP.RequireStrictTypes"/>
</ruleset>

3 Answers 3

0

Yes, there is:

declare(strict_types = 1);
//you can do preparations here
$myfiles = [/*thefiles*/];
foreach ($myfiles as $file) {
    $contents = file_get_contents($file);
    if (strpos($contents) === false) {
        file_put_contents($file, addYourMacro($contents))
    }
}

You will of course need to figure out what the files are and implement addYourMacro, where you textually embed it at the right place.

Sign up to request clarification or add additional context in comments.

Comments

0

The native Generic.PHP.RequireStrictTypes sniff does not have the ability to add this declaration automatically via phpcbf. For the files found, you can edit them pretty easily in the shell via sed:

sed -i 's/<?php$/<?php\n\ndeclare(strict_types = 1);/' <file>

2 Comments

This will also add the directive to the files that already have it, right?
Yes, but you wouldn't run it on all files, just the ones that the sniff detects.
0

The fastest - and not requiring writing any code - way:

composer require --dev php-cs-fixer/shim
vendor/bin/php-cs-fixer fix --rules=declare_strict_types directoryToFix
composer remove --dev php-cs-fixer/shim

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.