feat: Add support for dynamic object and array shapes within PHPDoc comments

Aberta
#15,662 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
25/100
Tipo de issue
Funcionalidade
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
php
Domínio
backend, devtools

Direção de pesquisa

Start by reading PHPStan's type parser and existing tests for object and array shapes; the issue does not name specific files or tests. Then trace how PHPDoc shape types are parsed and resolved to assess how the proposed mapped syntax would fit. Done means supporting the examples in the issue with tests for iterable sources and type unions.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

feature-request
Feature request

I would like to propose a new syntax for creating dynamic object and array shapes natively within PHPDoc comments.

Currently, it is really hard to transform generic parameter collections, variadics, or shape templates into a dynamic, structured object{} or array{} shape without writing custom DynamicMethodReturnTypeExtension classes in PHP. I propose introducing a native structural mapped type syntax inside both object and array shapes that can iterate over any iterable type or type union.

Proposed Syntax

By combining index signatures with a colon constraint syntax, we can declare inline mapped shapes inside docblocks without introducing new reserved keywords to the lexer. The constraint can accept any iterable source type:

object{[K: IterableSourceType]: ValueType}
array{[K: IterableSourceType]: ValueType}

This syntax sets up a clear, symmetrical parser boundary where the engine unrolls the keys based on the provided iterable type:

array{ [ K : IterableSourceType ] : ValueType }
        └───┬───────────────────┘   │
            │                       └─ Value mapping assignment (TypeNode)
            └─ Key iterator and constraint collection source

Type Examples

  1. Creating a Dynamic Array Shape via key-of:
/**
 * @template T of array<string, mixed>
 * 
 * @param T $data
 * @return array{[K: key-of<T>]: T[K]}
 */
function foo(array $data): array
{
    // ...
}
  1. Iterating a Type Union (Enum-like behavior for Arrays):
/**
 * @return array{[K: 'status'|'code'|'message']: string}
 * // Resolves to: array{status: string, code: string, message: string}
 */
  1. Unrolling Variadic Generics into an Object Shape:
/**
 * @template TColName of string
 * @template TColVal
 * @param array<int, Column<TColName, TColVal>> $columns
 * @return object{[K: TColName]: TColVal}
 */

Benefits & Use Cases

This feature removes the boilerplate of writing framework-specific extensions for highly dynamic PHP architectures. Real-world applications include:

  • Fluent APIs & Query Builders: Unrolling variadic arguments (like a list of custom configuration or column objects) into a strongly-typed result payload array or object shape.
  • Data Mappers & Hydrators: Safely transforming array shapes or dynamic dictionary structures into matching structural object/array shapes during execution.
  • DTO & Array Transformations: Defining generic wrapper components that dynamically pass down, pluck, filter, or merge array key properties through strict type inference.
Did PHPStan help you today? Did it make you happy in any way?

I am really happy with PHPStan, I use it in almost all of my projects, and I would be really happy if this new feature lands in!

Linguagem predominante
PHP
Estrelas
14.2k
Forks
972
Merge médio
13h 25min
PRs com merge (30d)
142

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de phpstan/phpstan

Todas as issues de phpstan/phpstan

Issues semelhantes

Mais issues de PHP

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.