Skip to content

Commit 887d79e

Browse files
#15 Fix parser with duplicate class label in file content
1 parent a55de1d commit 887d79e

File tree

3 files changed

+53
-4
lines changed

3 files changed

+53
-4
lines changed

src/Helpers/Parser.php

+21-3
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,28 @@ 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+
for (;$i < count($tokens);$i++) {
31+
if ($tokens[$i][0] === T_CLASS) {
32+
for ($j = $i + 1;$j < count($tokens);$j++) {
33+
if ($tokens[$j] === '{') {
34+
$class = $tokens[$i + 2][1];
35+
}
36+
}
37+
}
3038
}
3139

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

tests/Helpers/ParserTest.php

+6-1
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 class string in file content' => [
62+
$load('source-4.php'),
63+
'App\Routes\MyRoute',
64+
];
6065
}
6166

6267
/**
+26
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 <[email protected]>
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)