From 5841dce723e98442533b1fd34981a91a61d0b18f Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sun, 12 Jul 2020 09:36:18 +0700 Subject: [PATCH] optimize FileLocator autoloader : use foreach instead of for with count when possible --- system/Autoloader/FileLocator.php | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/system/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php index 4557cb168538..c9d2b78a089c 100644 --- a/system/Autoloader/FileLocator.php +++ b/system/Autoloader/FileLocator.php @@ -171,34 +171,38 @@ public function getClassname(string $file) : string { $php = file_get_contents($file); $tokens = token_get_all($php); - $count = count($tokens); $dlm = false; $namespace = ''; $class_name = ''; - for ($i = 2; $i < $count; $i++) + foreach ($tokens as $i => $token) { - if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $tokens[$i][0] === T_STRING)) + if ($i < 2) + { + continue; + } + + if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $token[0] === T_STRING)) { if (! $dlm) { $namespace = 0; } - if (isset($tokens[$i][1])) + if (isset($token[1])) { - $namespace = $namespace ? $namespace . '\\' . $tokens[$i][1] : $tokens[$i][1]; + $namespace = $namespace ? $namespace . '\\' . $token[1] : $token[1]; $dlm = true; } } - elseif ($dlm && ($tokens[$i][0] !== T_NS_SEPARATOR) && ($tokens[$i][0] !== T_STRING)) + elseif ($dlm && ($token[0] !== T_NS_SEPARATOR) && ($token[0] !== T_STRING)) { $dlm = false; } if (($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass')) && $tokens[$i - 1][0] === T_WHITESPACE - && $tokens[$i][0] === T_STRING) + && $token[0] === T_STRING) { - $class_name = $tokens[$i][1]; + $class_name = $token[1]; break; } }