skip to Main Content

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>

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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$/<?phpnndeclare(strict_types = 1);/' <file>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search