Giter Site home page Giter Site logo

phpstorm-attributes's Introduction

official JetBrains project

PhpStorm attributes

Use these PHP 8 attributes in PhpStorm to get more advanced code completion and analysis.

Learn more in the blog post.

Installation

The attributes are available in PhpStorm 2020.3 and later. They are bundled with PhpStorm so you don’t need to install them separately.

If you are using other static analysis tools and don’t want to get Class not found issues, then you might want to add the attributes package to your composer.json as a dev dependency:

composer require --dev jetbrains/phpstorm-attributes

#[Deprecated]

Use this attribute when you want to notify users that an entity will be removed in the future.

Provide the explanation tip in reason and updating suggestion in replacement.

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

Deprecated

#[ArrayShape]

Use Array Shape when you deal with object-like arrays and want to specify the keys’ names and types for values to get better coding assistance.

#[ArrayShape([
 // 'key' => 'type',
    'key1' => 'int',
    'key2' => 'string',
    'key3' => 'Foo',
    'key3' => App\PHP8\Foo::class,
])]
function functionName(...): array

The attribute works with PHP ≤ 7.4 if specified in one line.

ArrayShape

#[ObjectShape]

The attribute specifies possible object field names and their types. If applied, an IDE will suggest the specified field names and infer the specified types.

#[ObjectShape(["age" => "int", "name" => "string"])]
function functionName(): object {...}

$obj = functionName();

This usage effectively means that the $obj has 2 fields, the names are age and name, and the corresponding types are int and string.

#[Immutable]

Mark properties or entire objects with this attribute if you want to guarantee they won't be changed after initialization.

#[Immutable]
class DTO
{
    public string $val;

    public function __construct(string $val)
    {
        $this->val = $val;
    }
}

The attribute works with PHP ≤ 7.4 if specified in one line.

Immutable

#[Pure]

Use this attribute for functions that do not produce any side effects. All such PHP internal functions are already marked in PhpStorm.

#[Pure]
function compare(Foo $a, Foo $b): int
{
    return $a->a <=> $b->b;
}

Pure

#[ExpectedValues]

Use this attribute to specify which values exactly a function accepts as parameters and which it can return. This will improve coding assistance.

function response(
    #[ExpectedValues(valuesFromClass: Response::class)] $httpStatusCode,
    //...
) {
    //...
}

ExpectedValues

#[NoReturn]

Mark functions that terminate script execution as exit points with this attribute to get a more accurate control flow analysis.

#[NoReturn]
function redirect(): void {
   //...
   exit();
}

NoReturn

#[Language]

Add this attribute to mark string parameters that contain text in some other [programming] language, for example, RegExp, SQL, and so on. This will improve highlighting and reveal additional features of PhpStorm for you.

Language

Bugs and feature requests

Please report any issues to the PhpStorm issue tracker https://youtrack.jetbrains.com/newIssue?project=WI.

Pull requests are also welcome.

phpstorm-attributes's People

Contributors

deyv avatar krzysztofrewak avatar mzztin avatar pestretsov avatar pronskiy avatar wbars avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpstorm-attributes's Issues

How do I set the expected value from 0 to infinity?

How can I use the #[ExpectedValues] attribute to indicate that a method or function argument can be 0 or more? And it can only be an integer.

I would like something like this:

#[ExpectedValues([0,1, ...])]
public function test(int $arg) {}

Using `ExpectedValues` attribute with a splat argument

Hi, is it currently possible to define expected values in a function where the argument has a splat operator (...).

For example:

/**
 * @param  string ...$permissions
 * @return bool
 */
public function hasPermissionTo(
    #[ExpectedValues(['view users', 'create users', 'etc'])]
    ...$permissions
): bool
{
    //
}

Currently, I'm seeing code completion only when adding the first argument. After that, nothing.

image

image

ExpectedValues do not support enum class

ExpectedValues do not support enum class, sample code below

use JetBrains\PhpStorm\ExpectedValues;

enum Color:string
{
    case RED='red';
    case BLUE='blue';
}


function test(#[ExpectedValues(valuesFromClass: Color::class)] string $color):string
{
    return $color;
}


test();//autocomplete not working yet

PhpStorm complains about multiple definitions when installing this package

Today I installed PhpStorm 2020.3 and noticed this package - awesome! Works as expected and I like how the IDE proposes to add the correct attributes when it believes it's required, like for Pure and Immutable.

However, to ensure my code base is also compatible with non-PhpStorm environments, I've also installed this package with composer require --dev jetbrains/phpstorm-attributes and now PhpStorm complains how there are multiple definitions for the attribute classes I use: "Multiple definitions exist for class 'Immutable'". It detects both the class loaded via PhpStorm and the class loaded via Composer in the vendor directory.

Is there any way to convince PhpStorm to use either?

Add ImPure annotation?

Hey! Since there is a Pure annotation, shouldn't there be an ImPure annotation, or at least a way to set the opposite pure state?

This is supported by PHPStan:

There are two new annotations that can be used above function and method declarations: @phpstan-pure and @phpstan-impure. Additionally, functions and methods that return void are also considered impure.
https://phpstan.org/blog/remembering-and-forgetting-returned-values

Again with Attributes

Hello guys first and foremost sorry for my bad English, but not is my primary language.

PHP Attributes are supported by PHPStorm and the downloadable package in this github allows users to provide attributes even to those who use IDEs different from PHPStorm.

The question at this point is only one.

If I want to define custom Attributes how can I tell PHPStorm not to use its built-in?

In the Settings->Inspection section I saw that it is possible to disable the inspection, but in doing so the help that PHPStorm gives to programmers during the inspection phase is lost by signaling when it would be useful/necessary to use an Attribute.

Wouldn't it be possible to make the inspection go further in the case of a Custom Attribute by merely indicating that that method or property needs an attribute?

I believe that allowing developers to harness the power of PHPStorm inspection by allowing them to customize attributes would be a very useful feature.

At the moment if I assign a custom attribute to a method or property PHPStorm keeps saying that it wants to use its built-in.

I hope I have explained myself in an understandable way.

I wish you a good job, keep it up.

Adriano

[ArrayShape] for maps/associative arrays as dynamic array indexes

Right now if I have following attribute

class Shema {
   #[ArrayShape(['string' => Property::class])]
    public array $properties;
}

$schema->properties['prop1'] = new Property();
$shcema->properties['prop2'] = new Property();

PHPStorm (PhpStorm 2023.3.4) will report on key Value should be one of: 'string' (why value?).

Is there any way to show possible index values? Like "string" / "int" / "SomeEnum->getValues()"

Screenshot 2024-02-28 at 10 59 34

Is there any documentation on ArrayShape?

I can't seem to find any.
The example provided in this repos readme is way too shallow to be useful in the vast majority of real-world usecases.

How do I define that the keys do not matter but the value types do?

// My impression, of how a solution could look like
#[ArrayShape([
    '*' => 'string',
])]

How do I define optional keys?

#[ArrayShape([
   'name' => 'string',
   'occupation?' => 'string',
])]

How do I define multiple valid types?

#[ArrayShape([
   'spouse' => 'string|array',
])]

How do I define numeric arrays?

#[ArrayShape([
 'int', 'int', 'int'
])]

Of arbitrary size?

#[ArrayShape([
 'int+'
])]

In my experience having required, and only required keys is quite the niche usecase. But that's the only usecase shown in the readme. Is there any way to solve the usecases presented above? Otherwise I think my code would be better documented using phpdoc's description feature...

I hope you can point me in the right direction!
Thanks! :3

How about #[Internal]?

Similar to the @internal Annotation it would be useful to mark classes and methods for internal use (limited scope) only. The annotation is currently only supported for classes, not methods.

Can we get a release?

PHPStan is flagging items like this because the only tag in this project does not include all of the changes.
image

Parameter Attribute for expected class attributes

Suggestion to add an attribute to ensure an instance has a class attribute.

class ExpectsAttribute
{
    public function __construct(
        #[ExpectedAttribute(CustomAttribute::class)]
        object $instance,
    ) {
        $this->instance = $instance;
    }
}
#[CustomAttribute]
class MyOKClass
{
}
class NotOKClass
{
}
// OK
new ExpectsAttribute(new MyOKClass());

//    Expects parameter 1 to have CustomAttribute
new ExpectsAttribute(new NotOKClass());

Thoughts?

Using attributes with PHP < 8.0

Hi!

On the anouncement page it says that some of these attributes work on older versions of PHP if used on a single line (so that PHP thinks they are comments).

However if PHPStorm is configured to sync settings with this composer.json:

{
    "require": {
        "php": "^7.4 | ^8.0"
    },
    "autoload": {
        "psr-4": {
            "Acme\\": "src"
        }
    }
}

Then the attribute is shown with an error:

image

And the error:

image

At the same time the attribute works in other code:

image

Is that the indented behavior?

[ArrayShape] Not working on properties

<?php

declare(strict_types=1);

namespace App;

use DateTimeInterface;
use IteratorAggregate;
use JetBrains\PhpStorm\ArrayShape;

final class MyList implements IteratorAggregate
{
    #[
        ArrayShape([
            'name' => 'string',
            'from' => DateTimeInterface::class,
            'to'   => '?' . DateTimeInterface::class,
        ])
    ]
    private array $rawList;

    public function __construct(
        iterable $rawList
    ) {
        $this->rawList = $rawList;
    }

    public function getIterator()
    {
        foreach ($this->rawList as $rawItem) {
            $rawItem[''] // expecting autocomplete but nothing shows.
        }
    }
}

With the above example the autocomplete is not working... Did I do something wrong ?

ArrayShape does not support `list()`.

<?php

#[\JetBrains\PhpStorm\ArrayShape(['int', \Throwable::class])]
function foo()
{
    return [];
}

$ret = foo();
$ret[1]->getMessage(); // Ok

[$id, $driver] = foo();
$driver->getMessage(); // Not work

[ArrayShape] doesn't work for structure inside the array

Hello, pseudocode:

    #[ArrayShape(['soldCount' => 'int', 'bookId' => 'int'])]
    public function foo(): array
    {
        $arr = [];

        $arr[] = [
            'soldCount' => 123,
            'bookId' => 453478,
        ];

        $arr[] = [
            'soldCount' => 22,
            'bookId' => 7863,
        ];


        return $arr;
    }

I'm not able to make phpstorm to suggest 'soldCount' and 'bookId' inside foreach. Is there any way how to define ArrayShape for structure inside list of items in array?

foreach ($this->foo() as $item) {
   echo $item['soldCount']; // phpstorm doesn't suggest
}

Specify two ArrayShapes for a function.

Hi, its posible specify two ArrayShapes for a function.

public function text(array $attributes = [], array $config = []): self

I would like to specify the attributes for each array try:

#[ArrayShape(['attributes' => ['dirname' => 'string'], 'config' => ['key' => int]])]
public function text(array $attributes = [], array $config = []): self

But it didn't work thanks for the help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.