Last active
January 3, 2016 14:59
-
-
Save solocommand/8479935 to your computer and use it in GitHub Desktop.
Test of ReflectionMethod getStartLine and getEndLine methods
This file contains 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 | |
class TestClass { | |
public function getSomething() | |
{ | |
$array = array( | |
'A', | |
'B', | |
); | |
} | |
} | |
class TokenManipulator { | |
public static $tokens; | |
public static $line; | |
public static $value; | |
public static function next() | |
{ | |
while ($token = array_shift(self::$tokens)) { | |
self::$line += substr_count(self::value($token), "\n"); | |
if (is_array($token) && in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) { | |
continue; | |
} | |
return $token; | |
} | |
} | |
public static function value($token) | |
{ | |
return is_array($token) ? $token[1] : $token; | |
} | |
} | |
$count = 0; | |
while($count <= 15) | |
{ | |
echo "Iteration $count\r\n"; | |
$test = new TestClass(); | |
$obj = new ReflectionObject($test); | |
$method = $obj->getMethod('getSomething'); | |
$src = file($obj->getFilename()); | |
$lines = array_slice($src, $method->getStartLine(), $method->getEndLine()); | |
echo "Start line: {$method->getStartLine()}, End line: {$method->getEndLine()}. Contents: \r\n"; | |
print_r($lines); | |
TokenManipulator::$tokens = token_get_all('<?php '.implode('', $lines)); | |
TokenManipulator::$line = $method->getStartLine(); | |
while ($token = TokenManipulator::next()) | |
{ | |
if (T_VARIABLE !== $token[0] || '$array' !== $token[1]) continue; | |
// = | |
$token = TokenManipulator::next(); | |
// array | |
$token = TokenManipulator::next(); | |
while ($token = TokenManipulator::next()) { | |
if (',' !== TokenManipulator::value($token)) continue; | |
TokenManipulator::next(); | |
$lines = array_merge( | |
array_slice($src, 0, TokenManipulator::$line - 2), | |
// Appends a separator comma to the current last position of the array | |
array(rtrim(rtrim($src[TokenManipulator::$line - 2]), ',') . ",\n"), | |
array(" '$count',\n"), | |
array_slice($src, TokenManipulator::$line - 1) | |
); | |
file_put_contents($obj->getFilename(), implode('', $lines)); | |
} | |
} | |
unset($obj); | |
$count++; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment