Last active
January 23, 2016 02:35
-
-
Save NigelGreenway/03b995ef9b2c159ba73d to your computer and use it in GitHub Desktop.
check for return type hints with interfaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__.'/test.file.php'; | |
$class = new ReflectionClass(Some\TheThing::class); | |
//// | |
// Better way to find if the class has strict_type enabled | |
//// | |
$tokens = token_get_all(file_get_contents(__DIR__.'/test.file.php')); | |
foreach ($tokens as $key => $token) { | |
if (is_array($token)) { | |
$foundKey = array_search('strict_types', $token); | |
if (is_bool($foundKey) === false) { | |
if ((bool) $tokens[$key+2][1] === false) { | |
throw new \RuntimeException('File is not strict, no need'); | |
} | |
} | |
} | |
} | |
//// | |
// End of strict_type check | |
//// | |
foreach ($class->getMethods() as $method) { | |
if (strpos($method->getDocComment(), '@inheritdoc') !== false) { | |
foreach ($class->getInterfaces() as $interface) { | |
if ($interface->hasMethod($method->getName())) { | |
$intMeth = $interface->getMethod( | |
$method->getName() | |
); | |
if (strpos($intMeth->getDocComment(), '@return')) { | |
if (preg_match('/(string|array|float|int)/', $intMeth->getDocComment(), $match)) { | |
if ( | |
$method->hasReturnType() | |
&& (string) $method->getReturnType() === $match[0] | |
) { | |
continue; | |
} | |
$log[] = sprintf( | |
"%s#%s should have a return type of [%s]\n(as per %s#%s)", | |
$class->getName(), | |
$method->getName(), | |
$match[0], | |
$interface->getName(), | |
$intMeth->getName() | |
); | |
} | |
} | |
} | |
} | |
} | |
} | |
var_dump($log); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Some; | |
interface Something | |
{ | |
/** @return string */ | |
function getString(); | |
/** @return int */ | |
function getInt(); | |
/** @return float */ | |
function getFloat(); | |
/** @return null */ | |
function getNull(); | |
} | |
final class TheThing implements Something | |
{ | |
/** @inheritdoc */ | |
function getString() :string { return 'string'; } | |
/** @inheritdoc */ | |
function getInt() { return 1; } | |
/** @inheritdoc */ | |
function getFloat() { return 3.14; } | |
/** @inheritdoc */ | |
function getNull() { return null; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment