如何为Symfony自定义createForm方法提供更具体的FormInterface返回类型?
解决PHPStan Level 6的FormInterface返回类型问题
要解决这个问题,你需要利用泛型关联传入的表单类型与返回的表单实例类型,让PHPStan能推断出更具体的返回类型,而非抽象的FormInterface。
方法一:兼容PHP <8.0的泛型注解方案
修改方法的PHPDoc与签名,添加泛型模板参数关联输入和返回类型:
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormInterface; /** * @template TForm of FormInterface * @param class-string<AbstractType> $type * @param ?object $data * @param array<string, mixed> $options * @return TForm */ public function createForm(string $type, ?object $data = null, array $options = []): FormInterface { // 你的自定义代码 return $this->formFactory->create($type, $data, $options); }
方法二:PHP 8.0+原生泛型方案
如果项目使用PHP 8.0及以上版本,可直接在方法签名中声明泛型,让类型推断更直观:
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormInterface; /** * @param class-string<AbstractType> $type * @param ?object $data * @param array<string, mixed> $options * @template TForm of FormInterface * @return TForm */ public function createForm<TForm extends FormInterface>(string $type, ?object $data = null, array $options = []): TForm { // 你的自定义代码 return $this->formFactory->create($type, $data, $options); }
原理说明
Symfony的FormFactory::create方法本身已实现泛型,通过给你的包装方法添加泛型注解,PHPStan可以根据传入的$type(具体表单类型的类名)自动推断出返回表单实例的具体类型,满足Level 6对返回类型具体化的要求。
内容的提问来源于stack exchange,提问作者Stephan Vierkant
相关产品推荐
相关产品推荐

