Releases

PhpStorm 2021.2: Generics, Enums, Array Shapes, Inspections, Refactorings, and More

Read this post in other languages:

PhpStorm 2021.2 is now available!

This major release introduces preliminary support for generics in PHP, enums for PHP 8.1, one-line array shapes, improved automatic formatting of PHP code, new inspections and refactorings, and much more.

Download PhpStorm 2021.2

Here are the main highlights of the release:

PHP

IDE

Version Control

Code With Me

Read this blog post for details about all the significant updates, demonstrated through a ton of GIFs!

PHP

Support for generics

Although generics is one of the most requested features for the PHP language according to the JetBrains Developer Ecosystem survey, there are no plans to add them any time soon.

In this release, we are adding basic support for generics via PHPDoc annotations. This approach was popularized by static analysis tools such as Psalm and PHPStan.

Collections with @template

One of the most popular applications of generics is collections.

In PhpStorm 2021.2, you can use generic class collections. Check out the Generics and why we need them post by Brent Roose to learn more about the advantages of this approach over arrays.

In short, you get more bug-free code and better code completion.

Here is a simple example of the @template annotated collection class:

With Doctrine Collections, you can already get code completion in simple scenarios:

Iterating over the Doctrine’s Collection interface will be supported in the next update. Make sure to watch the ticket WI-61438 so you receive notifications about new changes.

Only first-level depth is supported
Type inference and completion are only available for first-level generics in PhpStorm, i.e. generics like Base<T> or Base<T1, T2>. For such annotations, PhpStorm will understand the T types.

Nested generics like Base<Child<T>> are not supported, and will likely not be supported in the future, because of the performance overhead.

@class-string<T>

Another application of generics is containers and factories. With such code, it is common to pass a class name string as an argument and receive an object as a result.

If you annotate a parameter with a @class-string<T> tag, PhpStorm will provide you with the appropriate type inference:

In fact, if you use the new operator to instantiate an object from a parameter, then there is no need to add a @class-string annotation – it’ll just work out of the box:

What is the future scope?

We will continue to introduce support for generics step-by-step. There are a few known features missing that we’re planning to add in future updates:

  • WI-56034 Support the use of generics on classes
  • WI-60894 Support parameter wrapping
  • WI-61438 Support inference based on IteratorAggregate
  • WI-61497 Generics template @implements should inherit annotations from the interface

We encourage you to create a ticket if you find a use case that we have not covered.

PHP 8.1

The new version of the interpreter is expected to be released in late November. As is our tradition, we will start rolling out support for the new features early.

One of the most significant and expected features will, of course, be enums.

Enums

Declare an enum using the keywords enum and case. PhpStorm will help you with autocompletion and let you know if anything doesn’t follow the language syntax.

Enums can be used as type declarations in parameters, return values, and class properties. PhpStorm will check the type and highlight violations in the editor window.

You can quickly create new cases with a quick-fix. Type the case usage as if it already existed, then press Alt+Enter and choose Add enum case.

Backed enums

By default, enumerated cases are simple singleton objects. But if you want to save them to a database or similar data store, then you can define scalar values for cases.

Enums with scalar equivalents for cases are called backed enums.

If you define a standard enum (unit enum) and then decide to make it a backed one, PhpStorm has a quick-fix to add a type for the whole enum. Press Alt+Enter on the highlighted case value and choose the option to add `: %type%` to the declaration.

Did you know you can call enum Enum? That’s because it’s defined as a context keyword and not a reserved word on its own. So it should not collide with any existing userland implementations of enums that you might have.

You can declare custom methods in the enums, but you cannot declare constructors, destructors, properties, dynamic properties, or magic methods (except __call, __callStatic, and __invoke). PhpStorm will check for violations and highlight them for you.

That’s all for enums. Let us know if you have any ideas about how to make the support better.

Array shapes PHPDoc syntax support

While PHP has a great object system, it сan be convenient to work with simple data structures or object-like arrays when defining a real class feels excessive.

We are adding support for the PHPDoc syntax so you can now define the structure of arrays. This means PhpStorm will provide code completion for the keys and infer type of the values.

This is limited to one-line definitions only. Multiline syntax and nested array shapes are not supported yet. Stay tuned for updates.

Formatter improvements

For a long time, PhpStorm has had some quirks with formatting. While it worked well most of the time, these quirks could be very annoying in some fringe cases.

In PhpStorm 2021.2, we decided to fix all the outstanding formatting issues so you always get what you expect!

To format your code, press Cmd+Alt+L. This works for files and selections, too.

All code style options are available under Settings/Preferences | Editor | Code Style | PHP.

Some PhpStorm features were occasionally unusable if there were formatting issues. For example, formatting issues would cause problems when splitting lists into separate lines or, vice versa, merging them into one.

In arrays, argument lists, or parameter lists, you can now just press Alt+Enter and select Split comma-separated values into multiple lines:

When using multiple lines for lists, you can choose how to align the items. For example, for parameters with type declarations, you can make them more readable by aligning types and names in columns:

If you come across any formatting problems that we missed, please report them to our issue tracker!

New inspections and quick-fixes

This PhpStorm release comes with many new inspections to help you avoid introducing bugs, as they allow you to catch issues while you’re in the editor and before the code has been committed.
We’ve also added quick-fixes to save you from having to perform boring routine tasks and to help you focus on what’s important in your coding.

Here are some of the new inspections that are available in the 2021.2 release.

Condition can be replaced with `?->`

This inspection highlights expressions that can be replaced with the null safe operator from PHP 8. Press Alt+Enter to perform the transformation.

Use constant from a class where it is defined

PhpStorm will highlight constants that are accessed via a subclass or subinterface instead of the entity where the constant is defined. Replace the name of the entity with one where the constant is defined using the Alt+Enter quick-fix.

Redundant conditions in logical expressions

PhpStorm will now evaluate parts of conditions to identify any redundancies.

Here is a simple example:

And here’s a less obvious one:

Refactoring opportunities inspections

We’ve added a new group of inspections in Settings/Preferences | Editor | Inspections.

This group includes inspections that can help you find good candidates for refactoring. They are disabled by default, but even in this disabled state, you’ll see an additional gutter icon near code detected by these inspections (instead of having it underlined in the editor). Clicking the gutter icon will invoke the suggested refactoring.

Let’s take a look at three of them in action and see how you can combine them with PhpStorm refactorings.

Complex class should be refactored

These inspections detect bloated classes based on three metrics: TCC (Tight Class Cohesion), a measure of class cohesiveness; WMC (Weighted Method Count), the sum of cyclomatic complexities for all methods in the class; and ATFD (Access To Foreign Data), the number of fields from another class accessed in this class.

When PhpStorm detects a bloated class, it suggests extracting methods to a new class. If the original class is too large, it may need a few more iterations of refactorings.

Complex function should be refactored

This inspection calculates four different metrics for methods: cyclomatic complexity, nesting depth, number of variables used, and the total number of lines.

If a method’s overall score is poor, then it’s likely a good idea to split it into simpler, more manageable parts.

PhpStorm proposes some candidate blocks to extract to a new method.

Method has Feature Envy of another class

When a method accesses the data of another object more than its own data, that is a sign of Feature Envy.

You might want to move the full method, or a part of it, to the other class.

Feel free to explore and enable other inspections from the Refactoring opportunities group.

Extract Method refactoring, renewed and improved

Extract Method has been available in PhpStorm since 2011, and it is one of the most used refactorings.

Problem: You have a method that’s too big and you want to split it into several smaller ones. Or you have some duplicate code that you want to eliminate.

Solution: Move the code to a new, separate method, and replace the old code with a call to the method.

To use this refactoring, select any piece of code and press ⌘⌥M (Cmd+Alt+M / Ctrl+Alt+M).

Now let’s look at the improvements that were made to the Extract Method refactoring in PhpStorm 2021.2.

Refactoring duplicate code

First of all, it is now easy to find candidates for refactoring thanks to the Duplicated code fragment inspection.

This inspection has already been available, but now there is an added quick-fix to refactor the code.

Press Alt+Enter on the highlighted line and invoke the Extract Method from duplicate code quick-fix.

All duplicate fragments will be replaced with a new method call.

Detecting duplicates during refactoring

PhpStorm can also find smaller duplicates in the current scope (method, class, or file) during refactoring. In v2021.2, this detection process has become a lot smarter.
Select a code fragment and then call the refactoring with Cmd+Alt+M / Ctrl+Alt+M. At the bottom of the Extract Method dialog, a Review and replace duplicates checkbox will appear if any are found.

Note that this detection will now find duplicates when the code is not identical.

New smart selector for code fragments

If you try to invoke the Extract Method refactoring without selecting a piece of code, PhpStorm will suggest a list of possible code fragments. The suggestions can include simple expressions, statements, and full blocks.

PhpStorm verifies the control flow for the selected elements and excludes invalid or meaningless selections. In the following code, for example, the assignment expression is skipped, allowing you to extract the right part of it.

Expand selection improved

You probably already know that you can select a piece of code with the Expand / Shrink selection action ⌥+Up / ⌥+Down (Ctrl+W / Ctrl+Shift+W). This is a quick way to select code for refactoring.
In PhpStorm 2021.2, this refactoring has received a small update – the ability to select blocks without curly braces.

Better naming for extracted methods

PhpStorm 2021.2 is attempting to solve one of the hardest problems in Computer Science – how to name things.
When you use the Extract Method refactoring, PhpStorm will suggest a name for the new method.
If there is a variable used in the extracted code, the method name will be based on that variable’s name. PhpStorm will also take into account the expression type, any method call names, and other factors when suggesting a name.

If the code block is annotated with a comment, PhpStorm will use this comment as a source of the name for the extracted method.

IDE

Browser pages reload on save

As you may know, PhpStorm lets you preview HTML and PHP files in a browser using the built-in web server.
It can now also automatically reload the opened pages when HTML, PHP, or the linked CSS and JavaScript files are changed. Reloading is triggered whenever changes are saved in the IDE, either automatically, using ⌘S / Ctrl+S, or when changes are made to a file externally.
To try this new feature, open an HTML or PHP file, hover over the code, and click on the icon for the browser you want to use (all browsers are supported). You can also preview the file in a browser by going to View | Open in Browser in the main menu.

Reloading on save is turned on by default. To tweak the settings for it or to turn it off, go to the Built-in Server section in Preferences / Settings | Build, Execution, Deployment | Debugger.

Actions on save

PhpStorm supports running various actions explicitly on save.
There were already a few actions that you could set up to work on pressing ⌘S / Ctrl+S. With this release, we’ve reworked all the existing functionality and collected it together in one place.
All the related options are available under Preferences / Settings | Tools | Actions on Save. There you’ll find a list of the actions that can be triggered with ⌘S / Ctrl+S.

To turn an action on, tick the checkbox next to its name. Most of the actions will be triggered on any save, which includes autosave and explicit save actions. For file watchers and the Upload to default server action, you can choose between the two options whenever you want them to be activated.

Change project icons

There is a nice little feature to help you smarten up how your projects look on the Welcome screen. In PhpStorm, you can upload custom icons by right-clicking on any project and selecting Choose project icon from the context menu.
The dialog is now more straightforward, allowing you to easily choose the desired SVG file for each project.

Improvements for scratch files

With scratch files, you can make notes or draft code outside of the project context. To create a new scratch file press ⌘⌥+N .
In this release, you can now select code, press ⌥⏎ / Alt+Enter, and then choose Create new scratch file from selection to quickly create a new scratch file from this piece of code.

In addition to this, PhpStorm will automatically remove empty scratch files as soon as you close them, to help you keep your workspace clean.

Configurable scratch directory

You can configure a folder to store your scratch files. By default it’s the IDE configuration directory, but you can set it to a shared folder and use the same scratch files across different computers.
For that, you need to specify a command line option:
-Didea.scratch.path/scratches=<path>

Improvements to the Preferences / Settings dialog

There’s now a new node with advanced settings in your Preferences / Settings dialog. This node contains some additional configuration options. Most of them were transferred from the Registry.
You’ll also find some new configuration options there, such as the ability to set a left margin in Distraction-free mode.

Additionally, you can now navigate back and forth between open sections in your Preferences / Settings dialog. To do so, use the arrows in the right-hand corner of the window.

Automatic cache and logs cleanup

Previously, PhpStorm’s log and cache files could begin to take up a considerable amount of hard drive space over time.
After each major update, PhpStorm will automatically clean up any cache and log directories that were last updated more than 180 days ago. The system settings and plugin directories will stay intact.
If you want to trigger this process manually, go to Help | Delete Leftover IDE Directories… in the main menu.

New Terminal options

The built-in terminal has two new options. First, you can now select the cursor shape.

Second, we now support Use Option as Meta key, which is similar to the option with the same name in the native Terminal on macOS. It allows the Option () key to act as a meta modifier.
You can tick the checkboxes for these options in Preferences/ Settings | Tools | Terminal.

Quick access to Power Save mode

It is no secret that PhpStorm’s CPU usage can be quite high at times. This is primarily caused by indexing, and the usage is that high to make indexing as fast as possible.
If you are working on a laptop without a power supply and want to get several extra hours of battery life, PhpStorm has got you covered.
You can switch on Power Save mode from the status bar. Find the battery icon or right-click on the bottom right corner of the status bar and you will find it in the list.

When Power Save mode is turned on, syntax errors will still be highlighted and you get a full-fledged editor. But indexing and some battery-hungry code inspections will not run.
With the new icon, you can choose when to run inspections by turning Power Save mode off for a minute or two.

If you notice anything strange involving CPU spikes, please capture your CPU usage snapshot and share it with our support team by following these instructions.

Version Control

Unified behavior for the Show Diff action

PhpStorm now always displays the difference between the initial and changed files in the editor tab.
If you find it more convenient to track changes in a separate window, you can drag the desired file from the editor. If you do so, PhpStorm will remember this, and it will open future diffs in a separate window.

To go back to the default display, click the gear icon and select Show Diff in Editor Tab.

GPG signature for Git

It is now possible to enable Git commit signing with GPG via Preferences/Settings | Version Control | Git.

Text search in Local History revisions

The Local History can save you lots of time when you have made a sequence of changes and did not commit to the VCS in the previous state.
To see the Local History, right-click on the file and select Local History | Show History.
There is also now a search field you can use to help you to find the change you are looking for.

Run tests before commit

PhpStorm can already automatically perform a wide range of actions before a commit.
PhpStorm 2021.2 introduces the new option to Run Tests.
Click the gear icon in the Commit view, select the Run Tests option, and choose the necessary run configuration. PhpStorm will run the tests and notify you if there is anything wrong.

You can now also customize the Analyze code and Cleanup options by clicking Choose profile next to them. The progress and results of pre-commit checks are displayed in the Commit area, without disturbing you with additional modal windows!

Code With Me

Code With Me is a tool for pair programming and collaborative coding, and it comes with PhpStorm out of the box. In this release, it has received a lot of incredible new features and updates.

Screen sharing

One of the most eagerly-awaited features, screen sharing, is finally here. Code With Me 2021.2 now lets participants share an application window from their computer screen. It doesn’t even have to be PhpStorm. It can be any window!

Database Tools

PhpStorm includes almost all of DataGrip’s features as standard. Check out What’s New in DataGrip 2021.2 for an overview of the new features we’ve added for working with databases.

Web

As usual, all the updates for WebStorm 2021.2 have also been incorporated into PhpStorm.


The full list of changes in PhpStorm 2021.2 is available in the really long release notes.

That’s all for today. Thanks for keeping up with the changes! We hope they improve your PhpStorm experience.

Your JetBrains PhpStorm team
The Drive to Develop

image description