Skip to content

Instantly share code, notes, and snippets.

@RobinBastiaan
Forked from Pen-y-Fan/Info for PHPStorm.md
Created November 24, 2022 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobinBastiaan/deea4c114406ccf6844d73376d4f7709 to your computer and use it in GitHub Desktop.
Save RobinBastiaan/deea4c114406ccf6844d73376d4f7709 to your computer and use it in GitHub Desktop.
PHPStorm Tips, Tricks and setup

PHPStorm

PhpStorm Tips, ticks and standard setup

  1. Tips and Tracks for PHPStorm (PHPStorm Tips and Tricks.md)
  2. Standard setup for PHP projects (Standard.md)

PHPStorm

DPC2017: PhpStorm Tips Tricks - Gary Hockin

Project navigation / project panel (1:00) Alt + 1

Will toggle the navigation panel

Open a recent file (1:45) Ctrl+E

Recent files list

Navigate to File (1:54) Ctrl + Shift + N

Open a file by its file name

Search Everywhere (2:04) Shift Shift

Double shift will open search Everywhere, which will search all files, methods, classes etc.

Version Control (2:50) Alt + 9

Open the version control panel

Hide all Windows (2:59) Ctrl + Shift + F12

Toggle all open panels, just leaving the code windows, press again to restore them.

Navigate to Test (3:27) Ctrl + Shift + T

When in the code Ctrl + Shift + T will move to the corresponding unit test. The same keys will toggle back.

Close open windows (4:03) Esc Esc Esc

Keep pressing Escape to close all open windows and return to the core window.

Inspections (4:25)

Hover over the inspections in the right gutter to see what PHPStorm thinks is wrong, colour coded for severity. Red is a warning, orange is info.

Navigate to Next Highlighted Error (4:40) F2

Jump to the next highlighted error

Show Intention Actions (5:20) Alt + Enter

When on an error a quick fix light bulb will display. Alt + enter will open the menu for the possible actions. E.g. Add method, Update PHPDoc Comment.

Navigate back or Navigate Forward (6:37) Ctrl + Alt + Left/Right

Move to the previous position in the core window. Will toggle between files too.

Refactoring (7:09) Shift + Ctrl + Alt + T

Will open the Refactor This menu. Press the number corresponding the the required refactor. Note the direct shortcut is also listed for future use.

Move Caret to Next Word with Selection (7:43) Ctrl + Shift + Right

If the method is camel case, then the caret can jump to the next word.

Refactor code to its own method (8:56) Ctrl + Shift + Alt + T 7 (Or Ctrl + Alt + M)

Highlight a block of code, then Ctrl + Alt + M will open the Extract Method window. The code block can be given a method name and automatically moved to its own method, the original code will call the new method.

Navigate to Declaration (Ctrl + B)

Jumps to the method declaration.

Live templates (9:55)

Create your own code snippets or use the built in one, start typing the code name and press tab for it to complete.

Open Settings (Ctrl + Alt + S)

Start typing live templates to quickly search for the location (Editor > Live Templates), there are live templates for many languages, expand PHP to see the key words. Built in include:

  • eco ('echo' statement)
  • fore (foreach(iterable_expr as $value) {...})
  • forek (foreach(iterable_expr as $key => $value) {...})
  • inc ('include' statement)
  • inco ('include_once' statement)
  • prif (private function)
  • prisf (private static function)
  • prof (protected function)
  • prosf (protected static function)
  • pubf (public function)
  • pubsf (public static function)
  • rqr ('require' statement)
  • rqro ('require_once' statement)
  • thr (throw new)

Example type fore to create a foreach loop, the first variable should be a plural, the second variable will automatically be changed to the singular. Press Tab to navigate to the next item. (Choose Lookup Item Replace via ->| (Tab))

Create your own (11:11)

Example for vdd for Var Dump and Die.

Postfix completion (12:42) Ctrl + Alt + S

Search for Postfix.

Built in include:

  • ! (Negates expression)
  • echo (echo $expr) Calls echo for expression
  • else (if (!$expr)) Checks boolean expression to be 'false'.
  • fe (foreach($expr as $it)) Iterates over object (array).
  • if (if (expr(1))) checks boolean expression to be 'true'.
  • isset (if (isset($a))) Checks if expression is set and not null using isset() function
  • nn (if ($expr !== null)) Checks expression not to be null
  • not (!$expr) Negates expression
  • notnull (if ($expr !== null)) Checks expression not to be null
  • null (if ($expr === null)) Checks expression to be null
  • par (expr) Surrounds the expression with parens ().
  • return (return $expr) Returns value from containing method
  • throw (throw new Exception) Throw the expression.
  • var ($name = expr) Introduces new variable from expression
  • var_dump (var_dump($expr)) Calls var_dump for expression

Type in the expression then dot keyword for the code block to be generated

Example: $name.isset Tab will convert to:

if (isset($name)) {

}

You can't add your own Postfix completions, at the moment.

Expand / Contact Selection (12:40) Ctrl + W / Ctrl + shift + W

Click in a code block, press Ctrl + w to select the item clicked, press ctrl + w again to expand the selection, e.g. to an if statement, press ctrl + w again to expand again, e.g. to the code block.

Contact the selection back to the original cursor location.

Split Screen Horizontally or Vertically (13:26) Ctrl + Shift + A

Type in Split and enter to select Split Horizontally. Ctrl + F4 to close the file (and window). Alt + Tab to switch file

Setup Xdebug (14:03) Ctrl + Shift + A

Search for Xdebug, it is available under Preferences

Editor Lens (15:10)

Hover over the inspections in the right gutter to see what PHPStorm thinks is wrong, a mini window called the editor lens will show the code without having to navigate to that section in the file.

Scratch Files (15:17) Ctrl + Alt + Shift + Insert

Choose the required language and a new scratch file will open, you can enter code snippets too.

Run code (16:08) Ctrl + Shift + F10

The code will run in the Run terminal (Alt + 4 to toggle) or Right Click and select run

Save All (16:28) Ctrl + S

Saves all the documents, including scratch files.

Hector the Inspector (16:59)

Displayed in the bottom right of the screen. Highlighting Level can be changed for PHP and HTML, Power Save Mode can be used, to save battery.

Parameter type hints (18:25)

When a method/function is called the type hints for the parameter name is displayed. Turn off under Editor > General > Appearance > Show parameter name hints.

PHP 7 support (19:34)

PHPStorm has support for PHP 7 including strict declaration

Declare Strict (20:43) Ctrl + Alt + S

Search for missing declaration

Editor > Inspections under PHP > Type compatibility > Missing strict types declaration

The syntax highlighting will show a missing strict type declaration, F2 to goto the error, Alt + Enter to select the quick fix and Enter again will automatically add:

declare(strict_types=1);

The severity can also be changed from Warning (yellow) to Error (red).

Type hinting and return types will ne highlighted, if there are any errors.

Run Inspection by Name (22:21) Ctrl + Alt + Shift + I

Will pull up the inspections, type declaration and select Missing strict types declaration, then against the Project, including tests. The inspection will highlight all files, they can be checked one by one or click Add strict types declaration to apply it to the whole project.

Can be used for an inspections, for example to convert old array syntax to short array syntax.

Version Control (24:29) Alt + 9

Version control (git).

Local History (25:21)

VCS > Local History > Show History

Independent version control built into PHPStorm.

Test RESTful Web Service (26:07)

Make API calls (similar to Postman) from within PHPStorm

Example: HTTP Method: GET Host/Port: http://api.joind.in Path: /v2.1/events Ctrl + Enter to submit

External Tools (27:05) Ctrl + Alt + S

Search for external tools, it is under Tools > External Tools.

Gary demonstrates PHPCS.

Program is the location of the phpcs file (or bat file) Working directory is $ProjectFileDir$

PHPMD can also be configured.

Commands can be bound to their own keyboard shortcut.

Terminal (28:40) Ctrl + Tab T

Multiple terminals can be opened, e.g. to run php artisan serve

Front End (HTML) (29:56)

Install the JetBrains extension in your browser

Google JetBrains IDE Support for chrome

Changes made in HTML are live viewed in Chrome.

Emmet (31:40)

Example: div>lorem10*3TAB will create three div tags with Lorem Ipsum text.

Multiple Cursor Support (32:12)

Hold down Alt, while clicking the space to use a cursor will add an additional cursor, keep holding Alt and clicking for multiple. Start typing and the text will be entered at all selected locations.

Esc key will exit multiple cursor mode.

There is also Column Selection Mode Alt + Shift + Insert to toggle. the cursor keys can be moved up and down to expand multiple cursors.

Step Debugging (34:19)

See the recoding on the YouTube channel.

Database Browser (36:41) Ctrl + Tab D

Opens the database browser.

Browse the database tables, write SQL statements in the console.

Once the database browser is configured completion is available in the code editor.

Language Injection (38:24)

If writing in one language, but code completion is needed for another use Alt + Enter and select Inject language or reference. Useful inside a string or heredoc.

It is also possible to use a PHPDoc to declare the language using the same Alt + Enter quick hint.

Open Project

File > Open, select the project folder and Open, then choose This Window or New Window

Opening a new project in this window, the original project will have the code styles.

Reformat Code (41:50) Ctrl + Alt + L

Reformat the code to the set coding standard.

Productivity Guide (43:30)

Help menu > Productivity Guide.

This is also Help > New Support Request

the Productivity guide shows PHPStorm features which have been used and how often.

Standard setup for PHP projects

The focus in setting up PHP Projects in PHPStorm, in particular a Laravel project.

Composer with php codeSniffer, PHPUnit, and easy coding standard. Also some simplify projects to allow the output to be displayed in PHPStorm.

Below are some other options, including psalm, Rector and PHP Mess Detector.

Composer

Example snippet of a composer.json

{
    "require-dev": {
        "phpstan/phpstan": "^0.12",
        "phpunit/phpunit": "^8.5.0",
        "squizlabs/php_codesniffer": "^3.5.3",
        "symplify/easy-coding-standard": "^7.1",
        "symplify/phpstan-extensions": "^7.1",
        "nunomaduro/larastan": "^0.5.0",
        "phpstan/phpstan-phpunit": "^0.12.2",
    },
    "scripts": {
        "checkcode": "phpcs src tests --standard=PSR12",
        "fixcode": "phpcbf src tests --standard=PSR12",
        "test": "phpunit",
        "tests": "phpunit",
        "check-cs": "ecs check src tests --ansi",
        "fix-cs": "ecs check src tests --fix --ansi",
        "phpstan": "phpstan analyse src tests --ansi --error-format symplify",
    }
}

.editorconfig

Example .editorconfig file, normally found in the root of a project.

root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

Xdebug

Xdebug is used to debug PHP script, however due to how it analyses the script it makes PHP very slow, debugging should only enable it when debugging is required.

Add the following to the php.ini:

[xdebug]
zend_extension=xdebug
xdebug.remote_enable=1
xdebug.remote_port=9000

Note: PhpStorm will automatically enable xdebug, when the following is configure and debugging is enable, there is no need to leave xdebug enabled in php.ini. To temporarily disable xdebug comment out and the line. Using Laragon: Menu > PHP > Quick settings > xdebug, click to toggle on and off. This will be the same as manually adding a ; to the php.ini file:

[xdebug]
;zend_extension=xdebug
...

Configuring Xdebug in PhpStorm

TL;DR (parts copied from above PhpStorm Tutorials, full version below)

  1. In the Settings/Preferences dialog Ctrl+Alt+S, select Languages & Frameworks | PHP.

  2. Check the Xdebug installation associated with the selected PHP interpreter:

    a. On the PHP page, choose the relevant PHP installation from the CLI Interpreter list and click the Browse button next to the field.

    b. The CLI Interpreters dialog that opens shows the following:

    i. The version of the selected PHP installation. (e.g. D:\laragon\bin\php\php-7.4.4-Win32-vc15-x64\php.exe)

    ii. The name and version of the debugging engine associated with the selected PHP installation (Xdebug). (e.g. D:\laragon\bin\php\php-7.4.4-Win32-vc15-x64\ext\php_xdebug.dll)

    iii Once set click OK.

  3. Define the Xdebug behaviour. Click Debug under the PHP node (Languages & Frameworks | PHP | Debug.). On the Debug page that opens, specify the following settings in the Xdebug area:

  • Check the Pre-configuration has been complete (Xdebug ins installed, Install browser toolbar, Enable listening for PHP Debug connections and Start debug session)
  • Under the XDebug heading, Choose the Debug Port field (default is 9000). This must be exactly the same port number as specified in the php.ini file: xdebug.remote_port =9000
  • To accept any incoming connections, select the Can accept external connections checkbox. (Default)
  • Select the Force break at the first line when no path mapping is specified checkbox to have the debugger stop as soon as it reaches and opens a file that is not mapped to any file in the project on the Servers page. (Default)
  • Click OK

Using debug mode

Set a breakpoint in the file to be inspected.

Open public/index.php, wait for the file to open, then in to top right there will be a floating bar with a list of browsers. Click Chrome (Alt+F2 + Choose Chrome)

Chrome browser will launch and open the projects webpage. If the Debug icon isn't already green, click the Debug icon for Xdebug helper extension. From the drop down list click Debug option, the icon will then display green.

Navigate the project's website, to the page which uses the file that has the breakpoint set. As soon as the page is hit PhpStorm will open (it may be behind the browser).

In PhpStorm, accept the connection (this warning normally only displays the first hit and accepted once).

Debug information will display in the console, including the option to inspect variables and evaluate.

More details: How to Debug

For the full version of the above see Configuring Xdebug in PhpStorm and Browser Debugging Extensions, click the link for Xdebug for Chrome and install Xdebug Helper.

Youtube: Step Into Debugging with PhpStorm by Gary Hockin, 58 min video on Debugging.

How to Debug using Xdebug and PHPStorm from a Remote Server

Strict mode

PHPStorm has an inspection to set strict mode.

TL&DR;

Strict types declaration setting can be found under Type compatibility in the Inspections pane of the Preferences window.

Or double shift search for Missing Strict types declaration tick the inspection.

To run the inspection against the whole project (code base): CTRL + ALT + SHIFT + I or double shift search for run inspection by name. Search for missing strict type declaration, Enter for whole project. The inspection will run, click on each file and click Add strict types declaration

Project specific Standards

Laravel

Add the Laravel code standard for PHP code sniffer, static analysis for PHPStan and PHPStorm helper.

composer require --dev emielmolenaar/phpcs-laravel
composer require --dev nunomaduro/larastan
composer require --dev barryvdh/laravel-ide-helper

Example script to run phpcs using the phpcs-laravel standard:

phpcs --standard=phpcs-laravel

Automatic phpDoc generation for Laravel Facades (ide helper setup)

  • phpDoc generation for Laravel Facades
  • phpDocs for models
  • PhpStorm Meta file

After updating composer, add the service provider to the providers array in config/app.php

Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

To generate helper files, run the following:

php artisan ide-helper:generate
php artisan ide-helper:models --write
php artisan ide-helper:meta

It is a good idea to add the generated files to .gitignore

echo /.phpstorm.meta.php >> .gitignore
echo /_ide_helper.php >> .gitignore
echo /_ide_helper_models.php >> .gitignore

PHPStan Setup

PHP Static Analysis Tool - discover bugs in your code without running it!

Installation of PHPStan using Composer

composer require phpstan/phpstan --dev

Example phpstan.neon file

PHPStan needs a phpstan.neon file an example can be found here

Example phpstan.neon

includes:
    - vendor/nunomaduro/larastan/extension.neon
    - vendor/symplify/phpstan-extensions/config/config.neon
    - vendor/phpstan/phpstan-phpunit/extension.neon

parameters:
    paths:
        - app
        - tests

    # The level 8 is the highest level
    level: 8

    checkGenericClassInNonGenericObjectType: false

    # Larstan recommendation:
    checkMissingIterableValueType: false

    # to allow installing with various phpstan versions without reporting old errors here
    reportUnmatchedIgnoredErrors: false

    ignoreErrors:
        # Larstan recommendation:
        - '#Unsafe usage of new static#'

        # Ignore errors in Laravel's Middleware classes
        -
            message: '#Method App\\Http\\Middleware\\RedirectIfAuthenticated\:\:handle\(\) has no return typehint specified#'
            path: app\Http\Middleware\RedirectIfAuthenticated.php
        -
            message: '#Method App\\Http\\Middleware\\Authenticate\:\:redirectTo\(\) should return string\|null but return statement is missing#'
            path: app\Http\Middleware\Authenticate.php

    # buggy

    # mixed

    # cache buggy

    # tests

    # iterable

The above includes placeholders (buggy/mixed etc) for ignored files or rules. See the documentation for how to add.

Another phpstan.neon example from Larastan:

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:

    paths:
        - app

    # The level 8 is the highest level
    level: 5

    ignoreErrors:
        - '#Unsafe usage of new static#'

    excludes_analyse:
        - ./*/*/FileToBeExcluded.php

    checkMissingIterableValueType: false

Alternative phpstan script with level set to max

phpstan analyse src tests --level max --error-format checkstyle

PHPStorm Setup of PHPStan

PHPStan can be used as an External Tool

Go to Preferences > Tools > External Tools and click + to add a new tool.

  • Name: PHPStan (Can be any value)
  • Description: PHPStan (Can be any value)
  • Program: $ProjectFileDir$/vendor/bin/phpstan.bat (Path to phpstan.bat executable; On Windows path separators must be a \)
  • Parameters: check $FilePathRelativeToProjectRoot$ (append --fix to auto-fix)
  • Working directory: $ProjectFileDir$

Press Cmd/Ctrl + Shift + A (Find Action), search for phpstan, and then hit Enter. It will run phpstan for all files in the project.

You can also create a keyboard shortcut in Preferences > Keymap to run phpstan.

PHPStan can be used as a watcher

I have also tried setting up PHPStan as a watcher as follows:

  • File type: PHP
  • Scope: All Places
  • Program: $ProjectFileDir$/vendor/bin/phpstan
  • Arguments: analyse
  • Working directory: $ProjectFileDir$
  • Show console: On error

It runs PHPStan on every save, but only opens the console when PHPStan detects an error. Not as good as integrated analysis, but a good compromise, until Jetbrains can integrate it.

Easy Coding Standard (ECS)

Easiest way to start using PHP CS Fixer and PHP_CodeSniffer with 0-knowledge

Installation of ECS using Composer

composer require symplify/easy-coding-standard --dev

Example ecs.yaml file

parameters:
    sets:
        - 'psr12'
        - 'php71'
        - 'symplify'
        - 'common'
        - 'clean-code'

    line_ending: "\n"

    # 4 spaces
    indentation: "    "

    skip:
        Symplify\CodingStandard\Sniffs\Architecture\DuplicatedClassShortNameSniff: null
        # Allow snake_case for tests
        PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff:
            - tests/**
        # Ignore what is not owned - Laravel's TestCase class does not start with 'Abstract'
        Symplify\CodingStandard\Sniffs\Naming\AbstractClassNameSniff:
           - tests/TestCase.php
        # Ignore what is not owned - Laravel's traits do not end with 'Trait'
        Symplify\CodingStandard\Sniffs\Naming\TraitNameSniff:
            - tests/**
        # Ignore what is not owned - CommentedOutCodeSniff
        Symplify\CodingStandard\Sniffs\Debug\CommentedOutCodeSniff.Found:
            - app/Console/Kernel.php
        # Ignore what is not owned - @return \Illuminate\Contracts\Validation\Validator
        SlevomatCodingStandard\Sniffs\Namespaces\ReferenceUsedNamesOnlySniff.ReferenceViaFullyQualifiedName:
          - app/Http/Controllers/Auth/RegisterController.php

services:
    Symplify\CodingStandard\Sniffs\CleanCode\CognitiveComplexitySniff:
        max_cognitive_complexity: 8

Working example from KnpLabs/DoctrineBehaviors

Example ecs.yaml

parameters:
    sets:
        - 'psr12'
        - 'php70'
        - 'php71'
        - 'symplify'
        - 'common'
        - 'clean-code'

    skip:
        PhpCsFixer\Fixer\Operator\UnaryOperatorSpacesFixer: null
        Symplify\CodingStandard\Sniffs\ControlStructure\SprintfOverContactSniff: null
        Symplify\CodingStandard\Sniffs\CleanCode\ForbiddenStaticFunctionSniff: null
        Symplify\CodingStandard\Sniffs\CleanCode\CognitiveComplexitySniff: null
        Symplify\CodingStandard\Sniffs\CleanCode\ForbiddenReferenceSniff: null
        Symplify\CodingStandard\Sniffs\Architecture\ExplicitExceptionSniff: null
        Symplify\CodingStandard\Sniffs\Architecture\DuplicatedClassShortNameSniff: null

        # mixed types
        SlevomatCodingStandard\Sniffs\TypeHints\PropertyTypeHintSniff: null

        # buggy
        Symplify\CodingStandard\Fixer\ControlStructure\PregDelimiterFixer: null

        PhpCsFixer\Fixer\PhpUnit\PhpUnitStrictFixer:
            - "tests/ORM/TimestampableTest.php"

        # weird naming
        Symplify\CodingStandard\Fixer\Naming\PropertyNameMatchingTypeFixer:
            - "src/Model/Geocodable/GeocodablePropertiesTrait.php"
            # & bug
            - "*Repository.php"

        SlevomatCodingStandard\Sniffs\Classes\UnusedPrivateElementsSniff:
            - "tests/Fixtures/Entity/SluggableWithoutRegenerateEntity.php"

services:
    Symplify\CodingStandard\Sniffs\CleanCode\CognitiveComplexitySniff:
        max_cognitive_complexity: 8

    PhpCsFixer\Fixer\ClassNotation\FinalClassFixer: ~

    # see single LICENSE.txt file in the root directory
    PhpCsFixer\Fixer\Comment\HeaderCommentFixer:
        header: ''

    PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer:
        annotations:
            - 'author'
            - 'package'
            - 'license'
            - 'link'
            - 'abstract'

    # every property should have @var annotation
    # SlevomatCodingStandard\Sniffs\TypeHints\PropertyTypeHintSniff: ~

Example from phpdocumentor\reflection-common\easy-coding-standard.neon

includes:
    - temp/ecs/config/clean-code.neon
    - temp/ecs/config/psr2.neon
    - temp/ecs/config/common.neon

parameters:
    exclude_checkers:
        # from temp/ecs/config/common.neon
        - PhpCsFixer\Fixer\ClassNotation\OrderedClassElementsFixer
        - PhpCsFixer\Fixer\PhpUnit\PhpUnitStrictFixer
        - PhpCsFixer\Fixer\ControlStructure\YodaStyleFixer
        # from temp/ecs/config/spaces.neon
        - PhpCsFixer\Fixer\Operator\NotOperatorWithSuccessorSpaceFixer

    skip:
        PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff:
            - tests/**

PHPStorm setup for Easy Coding Standard (ECS)

EasyCodingStandard can be used as an External Tool

Go to Preferences > Tools > External Tools and click + to add a new tool.

  • Name: ecs (Can be any value)
  • Description: easyCodingStandard (Can be any value)
  • Program: $ProjectFileDir$/vendor/bin/ecs (Path to ecs executable; On Windows path separators must be a \)
  • Parameters: check $FilePathRelativeToProjectRoot$ (append --fix to auto-fix)
  • Working directory: $ProjectFileDir$

Press Cmd/Ctrl + Shift + A (Find Action), search for ecs, and then hit Enter. It will run ecs for the current file.

To run ecs on a directory, right click on a folder in the project browser go to external tools and select ecs.

You can also create a keyboard shortcut in Preferences > Keymap to run ecs.

PHP CodeSniffer

PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.

Installation of PHP CodeSniffer using Composer

composer require squizlabs/php_codesniffer --dev

Example phpcs.xml.dist

Example from phpdocumentor\type-resolver

Example phpcs.xml.dist

<?xml version="1.0"?>
<ruleset name="phpDocumentor">
 <description>The coding standard for phpDocumentor.</description>

    <file>src</file>
    <file>tests/unit</file>
    <exclude-pattern>*/tests/unit/Types/ContextFactoryTest.php</exclude-pattern>
    <arg value="p"/>
    <rule ref="PSR2">
        <include-pattern>*\.php</include-pattern>
    </rule>

    <rule ref="Doctrine">
        <exclude name="SlevomatCodingStandard.TypeHints.UselessConstantTypeHint.UselessDocComment" />
    </rule>

    <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps">
        <exclude-pattern>*/src/*_.php</exclude-pattern>
    </rule>

    <rule ref="SlevomatCodingStandard.Classes.SuperfluousAbstractClassNaming.SuperfluousPrefix">
        <exclude-pattern>*/src/*/Abstract*.php</exclude-pattern>
    </rule>

    <rule ref="Generic.Formatting.SpaceAfterNot">
        <properties>
            <property name="spacing" value="0" />
        </properties>
    </rule>
</ruleset>

PHPUnit

The PHP Unit Testing framework.

Installation of PHPUnit using Composer

composer require phpunit/phpunit --dev

Example phpunit.xml or phpunit.xml.dist

Example phpunit.xml.dist from Laravel Package Boilerplate, very useful for coverage reports!

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         verbose="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">src/</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="tap" target="build/report.tap"/>
        <log type="junit" target="build/report.junit.xml"/>
        <log type="coverage-html" target="build/coverage" lowUpperBound="35" highLowerBound="70"/>
        <log type="coverage-text" target="build/coverage.txt"/>
        <log type="coverage-clover" target="build/logs/clover.xml"/>
    </logging>
</phpunit>
  • Add /build/ to .gitignore
echo /build/ >>  .gitignore

Example phpunit.xml from livewire\livewire

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
        </whitelist>
    </filter>
</phpunit>

phpunit.xml from KnpLabs/DoctrineBehaviors (minimalist)

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
     colors="true"
     bootstrap="tests/bootstrap.php"
>

    <testsuites>
        <testsuite name="Knp Doctrine2 Behaviors">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

PHP Mess Detector

Installation of PHP Mess Detector

Follow the link from phpmd.org to download the latest version and save the phpmd.phar file in an accessible location.

Example phpmd.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ruleset
    name="ProxyManager rules"
    xmlns="http://pmd.sf.net/ruleset/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
    xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
>
    <rule ref="rulesets/codesize.xml"/>
    <rule ref="rulesets/unusedcode.xml"/>
    <rule ref="rulesets/design.xml">
        <!-- eval is needed to generate runtime classes -->
        <exclude name="EvalExpression"/>
    </rule>
    <rule ref="rulesets/naming.xml">
        <exclude name="LongVariable"/>
    </rule>
    <rule ref="rulesets/naming.xml/LongVariable">
        <properties>
            <property name="minimum">40</property>
        </properties>
    </rule>
</ruleset>

Mess detection rules from nesbot\Carbon

Example phpmd.xml

<?xml version="1.0"?>
<ruleset name="Mess detection rules for Carbon"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
                     http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="
                     http://pmd.sf.net/ruleset_xml_schema.xsd">
    <description>
        Mess detection rules for Carbon
    </description>
    <rule ref="rulesets/codesize.xml">
        <exclude name="CyclomaticComplexity" />
        <exclude name="NPathComplexity" />
        <exclude name="ExcessiveMethodLength" />
        <exclude name="ExcessiveClassLength" />
        <exclude name="ExcessivePublicCount" />
        <exclude name="TooManyMethods" />
        <exclude name="TooManyPublicMethods" />
        <exclude name="ExcessiveClassComplexity" />
    </rule>
    <rule ref="rulesets/cleancode.xml">
        <exclude name="BooleanArgumentFlag" />
        <exclude name="StaticAccess" />
        <exclude name="IfStatementAssignment" />
    </rule>
    <rule ref="rulesets/controversial.xml" />
    <rule ref="rulesets/design.xml">
        <exclude name="EvalExpression" />
        <exclude name="CouplingBetweenObjects" />
        <exclude name="CountInLoopExpression" />
    </rule>
    <rule ref="rulesets/design.xml/CouplingBetweenObjects">
        <properties>
            <property name="maximum" value="20" />
        </properties>
    </rule>
    <rule ref="rulesets/naming.xml/ShortVariable">
        <properties>
            <property name="exceptions" value="ci,id,to,tz" />
        </properties>
    </rule>
    <rule ref="rulesets/unusedcode.xml" />
</ruleset>

PHPStorm setup for PHP Mess Detector

Configure a local PHP Mess Detector script

1) Download and install the PHP Mess Detector scripts.

To check the PHP Mess Detector installation, switch to the installation directory and run the following command:

phpmd --version

If the tool is available, you will get a message in the following format:

PHPMD version <version>

To have code checked against your own custom coding standard, create it. Store the rules and the ruleset.xml file that points to them in the rulesets root directory.

2) Register the local PHP Mess Detector script in PhpStorm:

a. In the Settings/Preferences dialog Ctrl+Alt+S, navigate to Languages & Frameworks | PHP | Quality Tools.

b. On the Quality Tools page that opens, expand the Mess Detector area and click the Browse button next to the Configuration list.

c. In the PHP Mess Detector dialog that opens, specify the location of the phpmd.bat or phpmd PHP Mess Detector executable in the PHP Mess Detector path field. Type the path manually or click the Browse button and select the relevant folder in the dialog that opens.

To check that the specified path to phpmd.bat or phpmd ensures interaction between PhpStorm and PHP Mess Detector, that is, the tool can be launched from PhpStorm and PhpStorm will receive problem reports from it, click the Validate button. This validation is equal to running the phpmd --version command. If validation passes successfully, PhpStorm displays the information on the detected PHP Mess Detector version.

Configure a PHP Mess Detector script associated with a PHP interpreter

  1. In the Settings/Preferences dialog Ctrl+Alt+S, navigate to Languages & Frameworks | PHP | Quality Tools.

  2. On the Quality Tools page that opens, expand the Mess Detector area and click the ... (Browse button) next to the Configuration list. The PHP Mess Detector dialog opens showing the list of all the configured PHP Mess Detector scripts in the left-hand pane, one of them is of the type Local and others are named after the PHP interpreters with which the scripts are associated. Click the Add button on the toolbar.

  3. In the PHP Mess Detector by Remote Interpreter dialog that opens, choose the remote PHP interpreter to use the associated script from. If the list does not contain a relevant interpreter, click the Browse button and configure a remote interpreter in the CLI Interpreters dialog as described in Configuring Remote PHP Interpreters.

When you click OK, PhpStorm brings you back to the PHP Mess Detector dialog where the new PHP Mess Detector configuration is added to the list and the right-hand pane shows the chosen remote PHP interpreter, the path to the PHP Mess Detector associated with it, and the advanced PHP Mess Detector options.

psalm

A static analysis tool for finding errors in PHP applications https://psalm.dev

Install psalm

Install via Composer:

composer require --dev vimeo/psalm

Add a config:

./vendor/bin/psalm --init

Then run Psalm:

./vendor/bin/psalm

Example psalm.xml

<?xml version="1.0"?>
<psalm
    autoloader="psalm-autoload.php"
    stopOnFirstError="false"
    useDocblockTypes="true"
>
    <projectFiles>
        <directory name="app" />
        <directory name="tests" />
    </projectFiles>
    <issueHandlers>
        <RedundantConditionGivenDocblockType errorLevel="info" />
        <UnresolvableInclude errorLevel="info" />
        <DuplicateClass errorLevel="info" />
        <InvalidOperand errorLevel="info" />
        <UndefinedConstant errorLevel="info" />
        <MissingReturnType errorLevel="info" />
        <InvalidReturnType errorLevel="info" />
    </issueHandlers>
</psalm>

Rector

Instant Upgrades and Instant Refactoring of any PHP 5.3+ code https://getrector.org

Installation of Rector using Composer

composer require rector/rector --dev

Example rector.yaml

parameters:
    sets:
        - 'code-quality'
        - 'php71'
        - 'php72'
        - 'php73'

    php_version_features: '7.2' # your version is 7.3

    paths:
        - 'src'
        - 'tests'

Example rector-ci.yaml

parameters:
    paths:
        - "src"
        - "tests"

    sets:
        - 'dead-code'
        - 'code-quality'
        - 'coding-style'
        - 'nette-utils-code-quality'

    exclude_rectors:
        - 'Rector\DeadCode\Rector\Class_\RemoveUnusedDoctrineEntityMethodAndPropertyRector'
        - 'Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector'

    exclude_paths:
        - 'src/Model/Translatable/TranslatableMethodsTrait.php'

Phan

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness. https://github.com/phan/phan/wiki

composer require phan/phan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment