Generate mixin for requests (by analysing rules)

0
open
uuf6429
uuf6429
Posted 1 month ago

Generate mixin for requests (by analysing rules) #1251

Summary

Consider the following code:

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Routing\Controller;

class CreateProductRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => 'string|min:3|max:30',
            'gtin' => 'string|min:8|max:14|unique:products,gtin',
            'tags' => 'array|required',
            'tags.*' => 'string|min:2|distinct',
            'prices' => 'array|required',
            'prices.*.currency' => 'string|required|exists:EUR,USD',
            'prices.*.amount' => 'integer|required',
        ];
    }
}

class CreateProductEndpoint extends Controller
{
    public function __invoke(CreateProductRequest $request)
    {
//                     vvvv
        echo $request->name . '\'s first price is: ';
        echo $request->prices[0]['amount'];
//                     ^^^^^^^^^^^^^^^^^^^--- no autocompletion
    }
}

My proposal would be to generate:

/**
 * MyApp\Http\Requests\CreateProductRequest
 *
 * @mixin IdeHelperCreateProductRequest
 * @property string $name
 * @property string $gtin
 * @property string[] $tags
 * @property array[] $prices
 */
class IdeHelperCreateProductRequest extends \Illuminate\Foundation\Http\FormRequest {}

Sadly, PHPDoc doesn't seem to support array shapes (nor phpstan supporting properties, so $prices ends up as a simple array of arrays).