在 phpstorm 中,您可以通过 alt + insert> setters > 选择变量来为类成员生成 setter 方法。
但是,即使 phpstorm 知道变量的类型/类,它也不会在参数列表中插入类型提示。
如何让 phpstorm 生成带有类型提示的 setter,但仅针对可提示类型?
示例类
class CodeGenerationTest {
/* @var \DateTimeInterface */
private $date;
/* @var int */
private $num;
}
所需的生成器应该是:
/**
* @param DateTimeInterface $date
*/
public function setDate(DateTimeInterface $date)
{
$this->date = $date;
}
/**
* @param int $num
*/
public function setNum($num)
{
$this->num = $num;
}
setNum
是正确的,但是生成的 setDate
缺少参数的类型提示:
/**
* @param DateTimeInterface $date
*/
public function setDate($date)
{
$this->date = $date;
}
最佳答案
您需要在 PhpStorm 中更改 PHP Setter 方法的模板以指定类型提示。
打开 PhpStorm 的首选项和“文件和代码模板”菜单,在“代码”选项卡下有一个名为“PHP Setter 方法”的选项。将其修改为如下所示:
#set($typeHintText = "$TYPE_HINT ")
## First we check against a blacklist of primitive and other common types used in documentation.
#set($nonTypeHintableTypes = ["", "string", "int", "mixed", "number", "void", "object", "real", "double", "float", "resource", "null", "bool", "boolean"])
#foreach($nonTypeHintableType in $nonTypeHintableTypes)
#if ($nonTypeHintableType == $TYPE_HINT)
#set($typeHintText = "")
#end
#end
## Make sure the type hint actually looks like a legal php class name(permitting namespaces too) for future proofing reasons.
## This is important because PSR-5 is coming soon, and will allow documentation of types with syntax like SplStack<int>
#if (!$TYPE_HINT.matches('^((\\)?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)+$'))
#set($typeHintText = "")
#end
## Next, we check if this is using the array syntax like "MyClass[]", and type hint it as a plain array
#if ($TYPE_HINT.endsWith("[]"))
#set($typeHintText = "array ")
#end
/**
* @param ${TYPE_HINT} $${PARAM_NAME}
*/
public ${STATIC} function set${NAME}($typeHintText$${PARAM_NAME})
{
#if (${STATIC} == "static")
self::$${FIELD_NAME} = $${PARAM_NAME};
#else
$this->${FIELD_NAME} = $${PARAM_NAME};
#end
}
实际上,自从php primitive list实际上很短,可以检测它是否是原始类型。
所以:
class CodeGenerationTest {
/**
* @var DateTimeInterface
*/
private $date;
/**
* @var int
*/
private $num;
}
实际上会生成这个:
/**
* @var \DateTimeInterface $date
*/
public function setDate(\DateTimeInterface $date)
{
$this->date = $date;
}
/**
* @var int $num
*/
public function setNum($num)
{
$this->num = $num;
}
您可以在此处找到有关模板变量的帮助: https://www.jetbrains.com/phpstorm/webhelp/file-template-variables.html
关于phpstorm 生成带有类型提示的 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559070/