Skip to content

Commit

Permalink
Use tokens instead of regex
Browse files Browse the repository at this point in the history
  • Loading branch information
jakublabno committed Apr 2, 2022
1 parent a3e4984 commit eaf93b3
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/Finder/ClassNameFromPathGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,44 @@

class ClassNameFromPathGenerator
{
private const TOKEN_NAMESPACE = 'T_NAMESPACE';
private const TOKEN_CLASSNAME = 'T_CLASS';

public static function getFullClassNameFromFile(string $path): ?string
{
if (is_dir($path)) {
return null;
}

$file = file_get_contents($path);
$tokens = token_get_all($file, TOKEN_PARSE);

if (!$file) {
return null;
$namespaceAtLine = null;
$classNameAtLine = null;

foreach ($tokens as $token) {
if (!is_array($token)) {
continue;
}

list($id, $name, $line) = $token;

if (token_name($id) == self::TOKEN_NAMESPACE) {
$namespaceAtLine = $line;
}

if (token_name($id) == self::TOKEN_CLASSNAME) {
$classNameAtLine = $line;
}
}

preg_match('/(?<=namespace\s)(.*)(?=;).*(?<=class\s)(.*)(?=\s)/sU', $file, $matches);
if ($namespaceAtLine && $classNameAtLine) {
$splittedFile = explode(PHP_EOL, $file);

$namespace = rtrim(ltrim($splittedFile[$namespaceAtLine - 1], 'namespace '), ';');
$className = rtrim(ltrim($splittedFile[$classNameAtLine - 1], 'class '), ';');

if (isset($matches[1], $matches[2])) {
return implode("\\", array_slice($matches, 1, 2));
return $namespace . '\\' . $className;
}

return null;
Expand Down

0 comments on commit eaf93b3

Please sign in to comment.