[ArrayShape] Not working on properties
Neirda24 opened this issue · comments
<?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 ?
Hello. In your example, $rawItem
is an element type of field, but ArrayShape
specifies only current array elements, so you should try to do this $this->rawList['<caret>']
.
Also, concatenation inside ArrayShape
is not supported at this point as well. To provide nullable type, please consider to write string literal with |null
. Here is a working example:
Indeed. My bad didn't thought of that... I was mislead by the naming Array...
I guess Would there be a way to define it easily for the property instead of per item ?
@wbars hello, please, what do you mean by: $this->rawList['<caret>']
? Ran into a similar problem, need to put ArrayShape definition for structure which look like this, but it simply doesn't work:
#[ArrayShape(['soldCount' => 'int', 'bookId' => 'int'])]
public function foo(): array
{
$arr = [];
$arr[] = [
'soldCount' => 123,
'bookId' => 453478,
];
$arr[] = [
'soldCount' => 22,
'bookId' => 7863,
];
return $arr;
}
#[ArrayShape(['soldCount' => 'int', 'bookId' => 'int'])]
means that array has structure ['soldCount' => $a, 'bookId' => $b]
. To provide nested arrays with keys the following option is supported in the nearest EAP:
#[ArrayShape(['outerKey' => ['soldCount' => 'int', 'bookId' => 'int'] ])]
=> [ 'outerKey' => ['soldCount' => $a, 'bookId' => $b] ]
Syntax for nested arrays [ ['soldCount' => $a, 'bookId' => $b] ]
without keys is not supported at this point. Please follow this feature request: https://youtrack.jetbrains.com/issue/WI-65168. We'll try to implement it for 2022.1 release.