Skip to content

Instantly share code, notes, and snippets.

@slucero
Last active November 2, 2023 21:15
Show Gist options
  • Save slucero/5ac70402316224ee3fe1ec98a461320e to your computer and use it in GitHub Desktop.
Save slucero/5ac70402316224ee3fe1ec98a461320e to your computer and use it in GitHub Desktop.
PHPDoc Type Specification Notes

Advanced PHPDoc Type Specification

Notes

  • Cannot currently specify strict limiting of array keys (issue)
    • Array shapes are assumed to be incomplete and allow additional key/value assignments by default.
  • The Drupal coding standards don't currently play nicely with multiline array shapes and type specifications.
    • @param specifications warn about not having a variable name on the same line
    • Array shape properties warn about indentation errors
    • Closing curly braces warn about a missing opening curly brace
    • @param section is expected to always be the first annotation set in the docblock, so any @template or @phpstan-* annotations have to go later in the docblock with a blank line separating them.
  • The current suggestion for using these with Drupal coding standards seems to be to disable some of the rules during scanning.
  • Array shape unions don't work at the moment in PHPStan, but it seems they may work in Psalm.
  • Associative array structures may be specified more clearly like array<string, mixed> if specific keys aren't predicted or known.
  • ObjectProphecy is defined as a generic and you may specify the object type it's mocking like this ObjectProphecy<EntityInterface>.
  • MockBuilder objects aren't as easily specified and have to be specified with a union instead like MockObject&EntityInterface.
  • Type aliases defined with @phpstan-type work for PHPStan scanning, but they don't get expanded in a helpful way when viewing tooltips for functions and such.
    • The best compromise seems to be defining the fully-expanded array shape in the @param specification, and then referencing the type alias as an override via an additional @phpstan-param annotation.

      /**
      * @param array{
      *   pattern_id: string,
      *   data?: array,
      *   is_new?: bool,
      * } $values
      *   An associative array of configuration values to assign to the mock's
      *   related methods.
      *
      * @phpstan-param BlockEntityMockConfig $values
      */
      
    • The tooltip for functions still shows the @param type definition, but it also includes a reference to the name of the type definition (no further details about it are displayed though, unfortunately.)

    • PHPStorm lets you click through recognized type aliases to view their original declaration.

    • Autocomplete and suggestions seem to use the @param definition rather than reading through to the type alias.

Resources

Reference

Tools

PHPStorm Support

Drupal Support

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment