Generic typehints for DynamicEntityReferenceFieldItemList

Created on 27 February 2023, almost 2 years ago
Updated 29 June 2023, over 1 year ago

Improve generic typehints when used with phpstan + phpstan-drupal.

The suggested changes can be used in combination with the below code:

Wherein CollectionContentItem extends \Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceItem

/**
 * @property int $target_id
 * @property string $target_type
 * @property string $alias
 * @property \Drupal\Core\Entity\ContentEntityInterface|null $entity
 */
class CollectionContentItem extends DynamicEntityReferenceItem {
}

For example, a entity bundle class:

/**
 * Collection microcontent.
 */
final class Collection extends MySiteMicrocontentBase {

  /**
   * Get the contents field list.
   *
   * @return \Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceFieldItemList<\Drupal\mymodule\Plugin\Field\FieldType\CollectionContentItem>
   *   Collection items.
   */
  public function getContentsList(): DynamicEntityReferenceFieldItemList {
    return $this->contents;
  }

Such that calling code:

assert($collection instanceof Collection);
$contents = $collection->getContentsList();
\PHPStan\dumpType($contents);
// phpstan: Dumped type: Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceFieldItemList<\Drupal\mymodule\Plugin\Field\FieldType\CollectionContentItem>
\PHPStan\dumpType($contents[0]);
// phpstan: Dumped type: Drupal\mymodule\Plugin\Field\FieldType\CollectionContentItem|null
\PHPStan\dumpType($contents[0]->alias);
// phpstan: Dumped type: string
πŸ“Œ Task
Status

Fixed

Version

4.0

Component

Code

Created by

πŸ‡¦πŸ‡ΊAustralia dpi Perth, Australia

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024