Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpStorm autocompletion in traits

I have a trait that must always be mixed in to a subclass of \PHPUnit_Framework_TestCase. PhpStorm doesn't know this. Is there anything I can do to get PhpStorm to autocomplete and "typecheck" things like assertNull inside the trait?

<?php
trait MyTestUtils
{
    public function foo()
    {
        $this->assertNu // autocomplete?
    }
}

The best I could come up with so far is putting the following in each method:

/** @var \PHPUnit_Framework_TestCase|MyTestUtils $this */

But this is repetitive and doesn't understand protected memebers. Is there a better option?

like image 493
mpartel Avatar asked Jul 01 '13 11:07

mpartel


People also ask

How to enable autocomplete in PhpStorm?

By default, PhpStorm displays the code completion popup automatically as you type. If automatic completion is disabled, press Ctrl+Space or choose Code | Code Completion | Basic from the main menu. If necessary, press Ctrl+Space for the second time (or press Ctrl+Alt+Space ).

What language does PhpStorm use?

Supported languages With PhpStorm, you can develop applications in PHP 5.3, PHP 5.4, PHP 5.5, PHP 5.6, PHP 7, PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, and PHP 8.1.

What is PhpStorm used for?

PhpStorm provides tools and code assistance features for working with databases and SQL in your projects. Connect to databases, edit schemas and table data, run queries, and even analyze schemas with UML diagrams.

What is new in PhpStorm?

PhpStorm 2022.1 is a major update that brings support for multiline and nested array shapes, inplace Extract Method refactoring, enhanced support for Blade templates, WordPress, generics in PHP, and much more.


1 Answers

Besides using the php docblock to document $this, the only other way I'm aware of, which also, arguably makes your trait more "safe" anyway, is to define abstract methods on the trait itself, e.g.:

 trait F {

    /**
     * @return string[]
     */
    abstract public function Foo();

    /**
     * @return self
     */
    abstract public function Bar();
}

abstract class Bar {
    use F;

    /**
     * @return bool|string[]
     */
    public function Baz () {
        if ($this->Bar()) {
            return $this->Foo();
        }

        return false;
    }
}
like image 66
Stephen Avatar answered Nov 15 '22 13:11

Stephen