I would like to have a way to check our php
scripts for missing types in functions/methods.
In the class below, the first method has typed arguments and a return type. The second doesn't:
<?php
class MyClass{
function alter_string(string $a_string): string{
return $a_string;
}
function alter_another_string($a_string){
return $a_string;
}
}
Is there some way to check all return types and argument types are added? I am using Eclipse for PHP Developers as IDE. But any other solution would be nice too.
I could write my own script that reads the php files and checks each function
for a return type. And if there are arguments to the function, that script checks whether the types are added to these arguments. But I am pretty sure there is some existing way to achieve this.
You may use something like the following:
<?php
function check_types($file_path) {
$file_contents = file_get_contents($file_path);
$tokens = token_get_all($file_contents);
$functions = [];
foreach ($tokens as $token) {
if ($token[0] == T_FUNCTION) {
$function_name = $token[1];
$function_args = [];
for ($i = 3; $i < count($token); $i++) {
if ($token[$i][0] == T_VARIABLE) {
$function_args[] = $token[$i][1];
}
}
$functions[$function_name] = $function_args;
}
}
foreach ($functions as $function_name => $function_args) {
if (!isset($function_args['return'])) {
echo "Missing return type for function $function_name\n";
}
foreach ($function_args as $arg_name => $arg_type) {
if ($arg_type == '') {
echo "Missing type for argument $arg_name in function $function_name\n";
}
}
}
}
check_types(__FILE__);
You may also use PHPStan in this case.