Skip to content

Commit

Permalink
Merge pull request #20 from dimitriBouteille/15-parser-class
Browse files Browse the repository at this point in the history
Fix parser with multiple class/namespace label in file content
  • Loading branch information
dimitriBouteille authored Apr 25, 2024
2 parents a55de1d + 26e6363 commit bef2a91
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 4 deletions.
25 changes: 22 additions & 3 deletions src/Helpers/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,29 @@ public static function findClassName(?string $fileContent): ?string
throw new \InvalidArgumentException('The content does not contain PHP code.');
}

if (preg_match('#^namespace\s+(.+?);.*class\s+(\w+).+;$#sm', $fileContent, $m)) {
return $m[1].'\\'.$m[2];
$class = null;
$i = 0;
$counter = count($tokens);
for (;$i < $counter;$i++) {
if ($tokens[$i][0] === T_CLASS) {
for ($j = $i + 1;$j < $counter;$j++) {
if ($tokens[$j] === '{') {
$class = $tokens[$i + 2][1];
}
}
}
}

return null;
if ($class === null || $class === '') {
return null;
}

$namespace = null;
if (preg_match('#(^|\s)namespace(.*?)\s*;#sm', $fileContent, $m)) {
$namespace = $m[2] ?? null;
$namespace = $namespace !== null ? trim($namespace) : null;
}

return $namespace ? $namespace . "\\" . $class : $class;
}
}
7 changes: 6 additions & 1 deletion tests/Helpers/ParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static function providerFindClassName(): \Generator
return $fileContent;
};

yield 'Light php file' => [
yield 'Light php file' => [
$load('source-1.php'),
'App\Routes\MyRoute',
];
Expand All @@ -57,6 +57,11 @@ public static function providerFindClassName(): \Generator
$load('source-3.php'),
'App\Routes\MyRoute',
];

yield 'With phpdoc intro & multiple class/namespace label' => [
$load('source-4.php'),
'App\Routes\MyRoute',
];
}

/**
Expand Down
26 changes: 26 additions & 0 deletions tests/fixtures/route-classes/source-4.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php
/**
* Copyright (c) 2024 Dimitri BOUTEILLE (https://github.com/dimitriBouteille)
* See LICENSE.txt for license details.
*
* Author: Dimitri BOUTEILLE <[email protected]>
*/

namespace App\Routes;

use Dbout\WpRestApi\Attributes\Action;
use Dbout\WpRestApi\Attributes\Route;
use Dbout\WpRestApi\Enums\Method;

#[Route(
namespace: 'app/v2',
route: 'document/(?P<documentId>\d+)'
)]
class MyRoute
{
#[Action(Method::GET)]
public function get(): \WP_REST_Response
{
throw new \Exception('Invalid builder class type.');
}
}

0 comments on commit bef2a91

Please sign in to comment.