我发现@Pier 的解决方案非常有用,因此我更新了他的模板以生成具有类型提示 和 可选类型转换的设置器。希望这对其他人有帮助。
给定:
class CodeGenerationTest
{
/**
* @var \DateTime
*/
private $date;
/**
* @var int
*/
private $id;
/**
* @var string|null
*/
private $notes;
}
将生成:
/**
* @param \DateTime $date
*/
public function setDate(\DateTime $date)
{
$this->date = $date;
}
/**
* @param int $id
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* @param null|string $notes
*/
public function setNotes($notes)
{
$this->notes = is_null($notes) ? null : (string)$notes;
}
下面是复制/粘贴到 PHPStorm 中的代码模板:
Settings > Editor > File and Code Templates > Code > PHP Setter Method
#set($typeHintText = "$TYPE_HINT ")
## First we check against a blacklist of primitive and other common types used in documentation.
#set($nonTypeHintableTypes = ["", "string", "int", "integer", "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
## Set this or self
#set($thisOrSelf = "$this->")
#if (${STATIC} == "static")
#set($thisOrSelf = "self::$")
#end
## Type cast incoming variable that can also be null, using the ternary operator
#set($ternaryCast = "")
#if ($TYPE_HINT.contains('null|') || $TYPE_HINT.contains('|null'))
#set($ternaryCast = "is_null($${PARAM_NAME}) ? null : ")
#end
## Type cast incoming variable
#set($cast = " ")
#if ($TYPE_HINT.contains('string'))
#set($cast = "(string) ")
#elseif ($TYPE_HINT.contains('object'))
#set($cast = "(object) ")
#elseif ($TYPE_HINT.contains('int'))
#set($cast = "(int) ")
#elseif ($TYPE_HINT.contains('bool'))
#set($cast = "(bool) ")
#elseif ($TYPE_HINT.contains('float') || $TYPE_HINT.contains('double') || $TYPE_HINT.contains('real'))
#set($cast = "(float) ")
#end
/**
* @param ${TYPE_HINT} $${PARAM_NAME}
*/
public ${STATIC} function set${NAME}($typeHintText$${PARAM_NAME})
{
$thisOrSelf${FIELD_NAME} = $ternaryCast$cast$${PARAM_NAME};
}