How to use Vim substitute command (a use case)

As the security support for PHP 8.0 recently finished, it’s time to move forward and update my projects, including the open-source ones. The silver lining in all of this is that I can finally switch to attributes in tests. I think the attributes are better and have some advantages over annotations. So, let’s do it, but let’s try to do it as fast as possible with the power of Vim.

As you probably know, Vim has a powerful :substitute command for search and replace. The syntax of this command is :s/<pattern>/<replacement>/<flags>. This Ex (colon) command has lots of options and possibilities. I would recommend to read the Vim Wiki if you never used it.

But, back to the use case. In PHPUnit test methods were usually tagged with the @test annotation:

/** @test */
public function it_can_extract_words(): void
{

Starting from PHPUnit 10, test methods can be tagged with attributes. In order to use attributes, the PHPDoc annotations should be substituted with the attribute syntax:

#[Test]
public function it_can_extract_words(): void
{

My final substitute command looks like this (%s stands for the substitution in a whole file):

:%s/\/\*\*\ \+@test \+\*\//#[Test]/

As you can see, it substitutes the entire lines with the given annotation. So, this solution won’t work for annotations with more than just @test annotation. On the other hand, the manual work after updating tests is inevitable.

Updated: I came up with even a better solution that takes new lines into account (c flag stands for confirmation):

:%s/\/\*\*\_[^\@]*\@test\_[^\/]*\*\//#[Test]/c

Note: works in IdeaVim too.