PhpStorm 2020.3: PHP 8, Attributes, PHPStan and Psalm, Xdebug 3, Tailwind CSS and Co-development





We are glad to present the final major release of PhpStorm this year! Below the cut is a detailed analysis of all the changes and new features.







PHP 8



PHP 8.0 released. Many thanks to all contributors and release managers!



PhpStorm 2020.3 supports all the latest language changes. Let's take a look at what's available and how to use it in the IDE.



Language version in the status bar



Now the status bar always displays the current PHP version of the project. You can also switch the version from there.







If the radio button is not active, it means that the PHP version limit is set in composer.json.



Named arguments



In PHP 8, arguments to functions and methods can be passed by specifying a parameter name. Calls are now automatically documented and optional parameters are optional in the full sense of the word.



Using the Add name identifiers quick-fix, you can add names to arguments:







Typos or erroneous names of arguments are highlighted:







If the passed value matches the default parameter value, you can safely remove it:







Instead of the options array, you can use named arguments to pass a set of parameters, just passing only the necessary ones. Arguments passed in this way are type-safe, unlike array elements.







Attributes



Attributes are a new, structured way of specifying metadata in PHP instead of PHPDoc comments.



To create an attribute, you must declare a class and add a marker #[Attribute]



. Here PhpStorm will help you with highlighting, code completion, search for usages, refactorings and more.







PHP itself only checks the validity of attributes when called ReflectionAttribute::newInstance()



. And if you do not access the attributes through Reflection, then they are completely ignored so as not to load unnecessary classes and not create objects.



But PhpStorm will validate everything in the editor without running the Reflection API. The following rules are checked:



  • The specified class can indeed be an attribute.





  • This attribute applies only in the permitted locations: class, property, method, parameter, function, or class constant.





  • The attribute is repeated only if it is declared with a flag Attribute::IS_REPEATABLE



    .







Here are the attributes in action with Symfony:










PHP 8 Storm Attributes



Several attributes are available in PhpStorm 2020.3 out of the box in the namespace \JetBrains\PhpStorm\



.



You can immediately use them in your codebase without connecting anything.



But if you additionally use other static analysis tools and do not want to receive Class not found errors , then it may be worth adding the JetBrains / phpstorm-attributes attribute package as a dependency to composer.json



.





# [Deprecated]



Use this attribute as a PHPDoc @deprecated tag to mark methods, classes, or class constants that will be removed in the future.



The advantage here is that you can specify a replacement for the deprecated code and it will be easier for the user to update.



Let's take a look at a real-world example. In the recently released Symfony 5.2, the method is \Symfony\Component\DependencyInjection\Alias::setPrivate()



deprecated . If you add an attribute there #[Deprecated]



, you can simplify the migration.



#[Deprecated(
   reason: 'since Symfony 5.2, use setPublic() instead',
   replacement: '%class%->setPublic(!%parameter0%)'
)]

      
      













# [ArrayShape]



This attribute is useful for working with simple data structures or object-like arrays when a class cannot be declared for some reason.



The syntax is like this:

#[ArrayShape([
// β€˜key’ => ’type’,
   β€˜key1’ => β€˜int’,
   β€˜key2’ => β€˜string’,
   β€˜key3’ => β€˜Foo’,
   β€˜key3’ => App\PHP 8\Foo::class,
])]
function functionName(...): array

      
      







The type can be specified as a string or as a class reference in the form of an FQN string or constant ::class



.







The array that defines the "shape" can be put into a constant and reused:



const  MY_ARRAY_SHAPE = [];
#[ArrayShape(MY_ARRAY_SHAPE)]

      
      











In PhpStorm we have already annotated #[ArrayShape]



some standard PHP functions with an attribute , for example parse_url()



.



Luckily, the single-line attribute syntax is backward compatible. That is, if written #[ArrayShape]



in one line in a PHP 7 project, the PHP interpreter will interpret this line as a comment.



Unlike PHP interpreter, PhpStorm will parse attributes anyway! So even if your project is running PHP 7.4 or lower, you will still benefit from the addition #[ArrayShape]



.





# [Immutable]



Immutable objects cannot be modified after initialization or creation. Their use makes the state of the program more predictable and easier to debug.



An attribute #[Immutable]



can be used to mark an entire class or specific properties to indicate that they cannot be changed.



PhpStorm will check the use of such objects and properties and highlight the modification attempts.







Changing a property by default is allowed in the constructor, but can also be allowed in private / protected methods. This is done using the constants CONSTRUCTOR_WRITE_SCOPE



, PRIVATE_WRITE_SCOPE



, PROTECTED_WRITE_SCOPE



passed to the constructor #[Immutable]



.









# [Pure]



This attribute marks pure functions, that is, those that do not produce any side effects. Such functions can be safely removed if the result of their execution is not subsequently used.







If the function is marked as clean, but there is an attempt to change something outside of the external scope in its body, then PhpStorm will highlight the unsafe code.







All standard pure PHP functions are already marked with this attribute in PhpStorm.





# [ExpectedValues]



Using this attribute, you can specify which values ​​the function takes as parameters and which can be returned.



This is practically the same thing that does expectedArguments()



in .phpstorm.meta.php



. The only difference is that the meta version is rather auxiliary, and the attribute rigidly indicates that there are no other possible values.



For example, consider the count function:

count ( array|Countable $array_or_countable [, int $mode = COUNT_NORMAL ] ) : int
      
      





Its second argument is an integer, but in fact it is not an arbitrary integer, but one of the constants COUNT_NORMAL



or COUNT_RECURSIVE



.



Here's how the attribute #[ExpectedValues]



will improve the situation:







That is, auto-completion has appeared, and if something else is passed, the error is highlighted.



How to specify possible values ​​or bit masks
:

  • : #[ExpectedValues(values: [1,2,3])]





  • : #[ExpectedValues(values: [β€˜red’, β€˜black’, β€˜green’])]





  • : #[ExpectedValues(values: [COUNT_NORMAL, COUNT_RECURSIVE])]





  • : #[ExpectedValues(values: [Code::OK, Code::ERROR])]









:

  • #[ExpectedValues(values: [1,2,3])]



    , .

  • #[ExpectedValues(flags: [1, 2, 3])]



    , , 1 | 3



    .

  • #[ExpectedValues(valuesFromClass: MyClass::class)]



    , `MyClass



    `.

  • #[ExpectedValues(flagsFromClass: ExpectedValues::class)]



    , `MyClass`.







Another example # [ExpectedValues]



Let's take a helper response()



from Laravel. It takes the HTTP status code as the second parameter.



There are two problems

  • No autocompletion with possible codes

  • No validation of value in editor









Let's fix this by adding the attribute #[ExpectedValues(valuesFromClass: Response::class)]













# [NoReturn]



Some functions can stop the script execution. Marking functions such as exit points with an attribute #[NoReturn]



improves control flow analysis.









# [Language]



This attribute can be added to string parameters that expect text in any language, such as RegExp, SQL, DQL, and so on.



For arguments, highlighting and additional options will appear.












Let's get back to the new features in PHP 8.



Declaring properties in the constructor



Regular properties can be converted to promoted or vice versa using the Convert to promoted property quick fix .







PhpStorm ensures that properties are only used in a way that is allowed in PHP 8:

  • You can only declare properties in the constructor.

  • Cannot be declared in an abstract constructor.

  • You cannot declare a variadic property this way.

  • The property cannot be of type 'Callable'.

  • Property overrides are not allowed.











If the property is declared in a new way, but initialization remains in the body of the constructor, then PhpStorm will offer to delete it.







Match expression



The new expression is similar to switch



but uses strict comparison and can be assigned to a variable or returned.



PhpStorm detects if a block can switch



be rewritten into match



, and will do it automatically with a quick-fix by pressing Alt + Enter:







It can be difficult to see the incorrect use of a new expression, so PhpStorm will highlight all errors.









Duplicate values ​​will be found in the conditions: A







match expression with one branch and a default branch can be safely replaced with a ternary expression.







And if only the default branch is left, then the match is not needed at all.







Finally, if bodies are the same in different branches, they can be merged.







Nullsafe operator



Instead of a bunch of conditions with a check for null, you can now use a chain of calls with a new operator ?->



.



PhpStorm will check the correct use of the operator:







Hanging comma



It is now permissible to add a comma after the last argument when calling functions and in a closure list use



.







Non-capturing catches



In PHP 8, you can catch an exception in a catch block without a variable.







Throw expression



Exceptions can now be thrown in arrow functions and short operators ??



, as well as in ternary ? :



.







You can use shorthand thr



and press tab - this is a live template .







Constant :: class on objects



Previously, to get the FQN of an object, you had to use a function get_class()



. In PHP 8, the call get_class($object)



can be safely replaced with $object::class



.



Actually, by pressing Alt + Enter, such a replacement can be done. Incorrect use of ::class



PhpStorm constant will highlight.







New functions for strings: str_contains (), str_starts_with (), str_ends_with ()



How do I check if a string contains a specific word? Is the most viewed PHP question on Stack Overflow. PHP 8 has a clear answer to this question: use a function str_contains()



.



PhpStorm 2020.3 all calls strpos()



that can be replaced by str_contains()



:







There are also new str_starts_with()



, and str_ends_with()



to determine whether the start or end line specific substring. PhpStorm highlights where calls substr()



can be replaced with new alternatives:







Reclassified engine warnings



In PHP 8, the type of warning thrown has been revised for many errors. Namely, instead of Notice in many cases, there will be Exception or Type Error.



In PhpStorm, due to this, some inspections have two different severity levels: for PHP 8 and for older versions.







These are all of the most notable ones from PHP 8. There are a whole bunch of smaller changes that will be visible when you upgrade to PHP 8.





Psalm and PHPStan support



Both static analyzers can be used in PhpStorm 2020.3 to highlight issues directly in the editor.







If PHPStan or Psalm are added as dependencies in composer.json



, there will be a wrench icon next to them, which opens the tool settings.







From there, you can go to the inspection settings and turn on the highlighting in the editor. This is done by selecting the appropriate inspection in the PHP | Quality tools in Settings / Preferences | Editor | Inspections .



️ It is better to turn on only one of the instruments, rather than both at the same time.







Here you can also specify the path to the configuration file and configure the command line arguments.



️ PHPStan can work without a configuration file, but Psalm requires it. If there are psalm.xml



or in the root directory phpstan.neon



, PhpStorm will pull them up automatically.



When everything is set up, open any file and you will see a highlight from static analyzers. There may be a short delay before the backlight appears.







Annotations



All Psalm annotations are @psalm-*



now correctly highlighted in the editor. But in general, now you can safely remove the prefix @psalm-



from the tags, that is @psalm-return



-> @return



and @psalm-param



-> @param



.







Type support



We added support for some Psalm types, and based on the information from the tags, we improved our type inference. This made checks, code generation, and auto-completion more precise.



Pseudo-types

Psalm pseudo- types are supported, such as scalar, numeric, etc.







Constants in types

Supports constant joins and *



tagging param and var...







Typehints for arrays Array

descriptions are array<array-key, Type>



also supported, including nested ones.







Generics and @tempate Generic

support is a feature for advanced users that does not have a complete correct specification and many edge cases. However, we decided to implement basic support for @template



the Psalm-based syntax to see how this will be used.



So far, only the most primitive case is supported, when the function returns one of its parameters.







, . , . , .


Xdebug 3



The popular PHP debugger has been updated to make it much faster and easier to configure. Read more about Xdebug 3 in the Upgrade guide .



To configure Xdebug 3, one xdebug.mode option is now enough (like this XDEBUG_MODE=debug



).



Also the default Xdebug port has been changed: instead of 9000



now 9003



. To simplify migration, PhpStorm listens on both ports by default. Port settings and other options for Xdebug are found in Preferences / Settings | Languages ​​& Frameworks | PHP | Debug .









Debugger improvements



Debugging capabilities in PhpStorm have been expanded with two new features.



Interactive Hints

Now in debug mode, you can expand the output of variables to see all fields. You can also change the values ​​right there.







Inline Watches

In previous versions, you could add a variable or expression to the watch list and watch the value change step by step.



In PhpStorm 2020.3, you can add watches directly in the context, and they will be displayed next to the code.



Click Add as Inline Watch in the popup on the hint.





Or click Add Inline Watch in the editor context menu.





Or select the variable and select Add Inline Watch from the context menu .





Highlighting and renaming variables in Twig



Select a variable or place the cursor on it and all its uses in the template will be highlighted. And to rename all occurrences, press Shift + F6.









Co-development - Code With Me



PhpStorm 2020.3 comes with Code With Me plugin, JetBrains new collaborative development and pair programming tool. With it, you can share an open project with other users and work on it together in real time. Read more about Code With Me in these posts .









HTTP client



Integrating Guzzle with HTTP Client in PhpStorm



Guzzle is one of the most popular HTTP clients for PHP. Imagine that somewhere in the code there is an HTTP request and you want to test it without running the code itself. Previously, you would have to copy all parameters manually.



PhpStorm 2020.3 allows you to convert simple Guzzle requests to .http files. If the request is supported, an icon will appear next to it. By clicking on it, you will open a new scratch file with the correct URL, request parameters, methods, headers, body.







Now, from the editor, the query can be run and fiddled with, and then saved as an http file in the project.



More about the HTTP client in the video review .


Copy HTTP request to cURL



To export the HTTP request to a cURL string, press Alt + Enter on the request in the editor and select Convert to cURL and copy to clipboard . It can now be inserted into terminal, documentation, or any API testing tool.









Editor



Improvements for Markdown



You can use the Mermaid.js syntax in markdown files to describe charts and graphs . PhpStorm can now render previews for them right in the editor. Included in Preferences / Settings | Languages ​​& Frameworks | Markdown .







It is also now possible to reformat the contents of .md files according to popular styles. Done by pressing ⌘βŒ₯L / Ctrl + Alt + L.



Configurable in Preferences / Settings | Editor | Code Style | Markdown .







Finally, if you click the Auto-Scroll Preview button in the upper right corner of the editor, the scrolling of the preview and the text will be synchronized.



Improved spelling and grammar checking



Typos and grammar problems can now be corrected much faster:

  • First, an explanation of the error will appear in a pop-up window.

  • And if you press Alt + Enter on the highlighted text, the replacement options will be offered at the top, and not hidden in a sub-item, as before.









Split editor by drag and drop



To open multiple files side by side, simply drag the tab to the desired corner of the screen.







There is another way to open a file in split mode - Shift + Enter.

The combination can be clicked on the selected file in the Project view or in the file search results.







Preview tab



If you need to quickly view the files, now it is not necessary to open each one in a separate tab. You can use the new Preview tab .



To enable it, click on the gear in the Project view and select Enable Preview Tab and Open Files with Single Click .







You can also view files by pressing the spacebar in the Project view without opening them.









IDE



Improvements for Search Everywhere





The results are grouped by relevance:





You can do simple math operations without opening the google calculator:





You can search by Git history:





Automatic switch to light or dark theme



In Preferences / Settings | Appearance & Behavior | Appearance | Theme select Sync with OS .







New set of hotkeys for macOS



An alternate keyboard shortcut layout for macOS minimizes the use of function keys so that you don't have to stretch your hand across the entire keyboard when performing basic actions. For example, instead of Fn + Shift + F6, the Rename refactoring uses βŒ₯ + ⌘ + R.







Words instead of icons for macOS hotkeys



You can make the words Alt, Cmd, etc. appear instead of icons like ⌘ . Enabled



in the Registry section by the ide.macos.disable.native.shortcut.symbols option . To access the registry use Find Action Cmd + Shift + A and write Registry there .



Set PhpStorm as default application for different files



The Preferences | Settings / Editor / File Types click Associate file types with PhpStorm… . In the dialog box, select the file extensions and they will open in PhpStorm.



A reboot is required on macOS.







Templates can generate multiple files



You can simultaneously generate several files at once, for example a skeleton for a module or a combo controller-view.



In Preferences / Settings | Editor | Click on File and Code Templates to create a new template and then click on the Create Child Template File icon . Variables of type



can be used in the File name field . And here's an example of how to generate a controller and template in Symfony: ${NAME}





















Git stage support



You can enable it by checking the Enable staging area checkbox in Preferences / Settings | Version Control | Git .



In the Commit tool window (Cmd + 0 / Alt + 0), two groups of files will appear: staged and unstaged.



To add a file to staged , click on the + next to it.







Or you can select specific lines and add them with an icon in the editor. In this case, you can commit some of the changes from the file, and continue working on the rest.









DB Tools



PhpStorm includes DataGrip features out of the box , which are covered in the DataGrip 2020.3 release overview from our colleagues.



SQL for MongoDB



Now you can use SQL queries against MongoDB. PhpStorm 2020.3 supports SELECT-



queries JOIN



, WHERE



, GROUP BY



, HAVING



, ORDER BY



, LIMIT



, OFFSET



and all the features of MongoDB apart map, reduce, filter, and let. Read more in the blog post .







Web



As always, PhpStorm includes all updates from WebStorm 2020.3 . Most notable is the support for Tailwind CSS.



Tailwind CSS



PhpStorm complements the Tailwind classes in HTML files and after the @apply directive. It will also provide pseudo-class completion.



tailwind-completion-after-apply



If you hover over a class in HTML and CSS files, a preview of the resulting CSS is displayed. Preview is also available during code completion, in the pop-up documentation window F1 / Ctrl + Q.



tailwind-completion-for-pseudo-class-variants



PhpStorm supports customizations from tailwind.config.js. For example, if you define a theme with new colors, then in the pop-up autocomplete window there will be created classes with the name of the custom color.



tailwind-customization-support








You can download PhpStorm 2020.3 on the β€œ What's new ”page .



And here is a video (in English) showing the main features of the release:





That's all this time. We will be glad to have any questions, wishes, bug reports and just thoughts in the comments.



All Articles