Skip to content

howto - add type hinting to phpstorms generated setter method

A colleague of me forwarded me this super cool solution/template to remove one of the little annoying corners of the great PHPStorm IDE (beside the sad fact, that it is closed source software of course).
The template is fixing the problem with the generated setter methods and the missing type hinting.

Open PhpStorm's Preferences and "File and Code Templates" menu, under the "Code" tab there's an option called "PHP Setter Method". Modify it to look like this:
#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

This is important because PSR-5 is coming soon, and will allow documentation of types with syntax like SplStack

if (!$TYPEHINT.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 ${TYPEHINT} $${PARAMNAME} */ public ${STATIC} function set${NAME}($typeHintText$${PARAM_NAME}) {

if (${STATIC} == "static")

self::$${FIELD_NAME} = $${PARAM_NAME};

else

$this->${FIELD_NAME} = $${PARAM_NAME};

end

}


source
File Template Variables

Translate to de es fr it pt ja

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Markdown format allowed
Form options