Search code examples
phpregexphpstormregex-negation

How can I find all php class files without strict_types declaration (RegExp / PhpStorm)


I'm trying to add the strict type declaration declare(strict_types=1); to all PHP class and trait files under a specific directory.

  1. How can I get a list of files without that declaration using Linux terminal?

  2. How can I add missing declarations using PhpStorm (inspection, replace in path + regexp)?

Example /src/Foobar.php without declaration:

<?php
/**
 * class file
 */
namespace Foo\Bar;

use Other\Foo\Bar;

class Foobar {
  // ..
}

Example /src/Foobar.php with declaration:

<?php
/**
 * class file
 */
declare(strict_types = 1);

namespace Foo\Bar;

use Other\Foo\Bar;

class Foobar {
  // ..
}

Comments and imports ("use") are optional within a class file.

What I've done:

  • Trying to find a PhpStorm inspection that does what I want
  • Trying RegularExpressions but didn't find any statement searching for a lack of something within a multi-row context

Solution

  • You do not need regex for this - just use built-in "quick fix" for that.

    1. Select files/folder(s) where you wish to run such stuff in Project View panel
    2. Code | Run Inspection by Name...
    3. Find Missing strict type declaration inspection there (e.g. type strict and select it from narrowed list) and run it
    4. Confirm the scope (where to run this inspection on)
    5. See the results -- you may now apply Quick Fix (many ways -- at least 3 are shown on my screen) -- can be done on per file basis as well as all in one go

    Screenshots:

    Finding inspection to run:

    enter image description here

    Applying the fix (NOTE: I've run this inspection on single file only that has your sample code as content):

    enter image description here


    Alternatively -- just enable appropriate inspection (which is disabled by default) and you will be able to add such code via usual Alt + Enter (on Windows using Default keymap; or via "light bulb" icon) directly in the code:

    Settings/Preferences | Editor | Inspections | PHP | Type Compatibility | Missing strict type declaration

    enter image description here

    Quick fix menu (Alt+Enter)

    enter image description here