phpstan-drupal icon indicating copy to clipboard operation
phpstan-drupal copied to clipboard

Type from FieldItemListInterface iterator odd behaviour

Open dpi opened this issue 3 years ago • 1 comments

Since updating from 1.1.10 to 1.1.11 a small thing forced me to add additional typehinting to satisfy phpstan w/ level 8.

Code sample stripped of irrelevant logic:

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  return array_map(function (StringItem $item) {
    // Do something...
    return $item->getValue();
  }, iterator_to_array($items));

This sample now raises this error:

Parameter #1 $callback of function array_map expects (callable(Drupal\Core\TypedData\TypedDataInterface): mixed)|null, Closure(Drupal\Core\Field\Plugin\Field\FieldType\StringItem): mixed given.

To work around this error I updated the code snippet to roughly:

public function viewElements(FieldItemListInterface $items, $langcode = NULL) {
  /** @var \Drupal\Core\Field\Plugin\Field\FieldType\StringItem[] $stringItems */
  $stringItems = iterator_to_array($items);
  return array_map(function (StringItem $item) {
    // Do something...
    return $item->getValue();
  }, $stringItems);

Not sure what to do about this, whether its intentional, or if we can add extra intelligence to phpstan-drupal.

dpi avatar Feb 24 '22 15:02 dpi

Copying the Slack thread from Drupal Slack so I can follow up back with my findings: https://drupal.slack.com/archives/C033S2JUMLJ/p1645714581465309

Basically 1.1.11 added stubs for fields. This made PHPStan aware of things. We need to stub FieldItemListInterface so that it's getIterator at least returns FieldItemInterface.

It shouldn't assume Drupal\Core\TypedData\TypedDataInterface. That doesn't really fix the problem for this inspection.

I wonder if a fix is also:

/** @var \Drupal\Core\Field\FieldItemListInterface<\Drupal\Core\Field\Plugin\Field\FieldType\StringItem>

mglaman avatar Feb 24 '22 15:02 mglaman

@dpi do you know if this went away after https://github.com/mglaman/phpstan-drupal/pull/433? I know it was a super long time ago.

mglaman avatar Feb 14 '24 04:02 mglaman

I cant find this code any longer. Happy to close if you agree

dpi avatar Feb 14 '24 04:02 dpi

Thanks for the follow up! I think the fixes in ListInterface would have solved this, especially given this comment https://github.com/mglaman/phpstan-drupal/issues/353#issuecomment-1049958164

mglaman avatar Feb 14 '24 04:02 mglaman