Skip to content

Commit bef2a91

Browse files
Merge pull request #20 from dimitriBouteille/15-parser-class
Fix parser with multiple class/namespace label in file content
2 parents a55de1d + 26e6363 commit bef2a91

File tree

3 files changed

+54
-4
lines changed

3 files changed

+54
-4
lines changed

src/Helpers/Parser.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,29 @@ public static function findClassName(?string $fileContent): ?string
2525
throw new \InvalidArgumentException('The content does not contain PHP code.');
2626
}
2727

28-
if (preg_match('#^namespace\s+(.+?);.*class\s+(\w+).+;$#sm', $fileContent, $m)) {
29-
return $m[1].'\\'.$m[2];
28+
$class = null;
29+
$i = 0;
30+
$counter = count($tokens);
31+
for (;$i < $counter;$i++) {
32+
if ($tokens[$i][0] === T_CLASS) {
33+
for ($j = $i + 1;$j < $counter;$j++) {
34+
if ($tokens[$j] === '{') {
35+
$class = $tokens[$i + 2][1];
36+
}
37+
}
38+
}
3039
}
3140

32-
return null;
41+
if ($class === null || $class === '') {
42+
return null;
43+
}
44+
45+
$namespace = null;
46+
if (preg_match('#(^|\s)namespace(.*?)\s*;#sm', $fileContent, $m)) {
47+
$namespace = $m[2] ?? null;
48+
$namespace = $namespace !== null ? trim($namespace) : null;
49+
}
50+
51+
return $namespace ? $namespace . "\\" . $class : $class;
3352
}
3453
}

tests/Helpers/ParserTest.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public static function providerFindClassName(): \Generator
4343
return $fileContent;
4444
};
4545

46-
yield 'Light php file' => [
46+
yield 'Light php file' => [
4747
$load('source-1.php'),
4848
'App\Routes\MyRoute',
4949
];
@@ -57,6 +57,11 @@ public static function providerFindClassName(): \Generator
5757
$load('source-3.php'),
5858
'App\Routes\MyRoute',
5959
];
60+
61+
yield 'With phpdoc intro & multiple class/namespace label' => [
62+
$load('source-4.php'),
63+
'App\Routes\MyRoute',
64+
];
6065
}
6166

6267
/**
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
/**
3+
* Copyright (c) 2024 Dimitri BOUTEILLE (https://github.com/dimitriBouteille)
4+
* See LICENSE.txt for license details.
5+
*
6+
* Author: Dimitri BOUTEILLE <bonjour@dimitri-bouteille.fr>
7+
*/
8+
9+
namespace App\Routes;
10+
11+
use Dbout\WpRestApi\Attributes\Action;
12+
use Dbout\WpRestApi\Attributes\Route;
13+
use Dbout\WpRestApi\Enums\Method;
14+
15+
#[Route(
16+
namespace: 'app/v2',
17+
route: 'document/(?P<documentId>\d+)'
18+
)]
19+
class MyRoute
20+
{
21+
#[Action(Method::GET)]
22+
public function get(): \WP_REST_Response
23+
{
24+
throw new \Exception('Invalid builder class type.');
25+
}
26+
}

0 commit comments

Comments
 (0)