-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathPhpFileParser.php
More file actions
188 lines (163 loc) · 7.4 KB
/
Copy pathPhpFileParser.php
File metadata and controls
188 lines (163 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
<?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\ClassMapGenerator;
use RuntimeException;
use Composer\Pcre\Preg;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PhpFileParser
{
/**
* Regex fragment matching a named extension declaration (proposed "Extension Methods" RFC)
*
* Captures the declared name (extname) and the raw target token after "on" (exttarget). The
* target is captured exactly as written in the source — possibly a relative name or an alias
* from a "use" import, unresolved — in anticipation of the target-hint optimization described
* in the RFC's Future Scope. It is not used yet and is not part of the class map output.
*
* Must remain embeddable in a case-insensitive, whitespace-extended ("ix") pattern.
*
* @internal
*/
public const EXTENSION_REGEX = '\b(?<![\\\\$:>])(?P<ext>extension) \s++ (?P<extname>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+) \s++ on \s++ (?P<exttarget>\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+) \s*+ \$[a-zA-Z_\x7f-\xff]';
/**
* Extract the classes in the given file
*
* @param string $path The file to check
* @throws RuntimeException
* @return list<class-string> The found classes
*/
public static function findClasses(string $path): array
{
$extraTypes = self::getExtraTypes();
if (!\function_exists('php_strip_whitespace')) {
throw new RuntimeException('Classmap generation relies on the php_strip_whitespace function, but it has been disabled by the disable_functions directive.');
}
// Use @ here instead of Silencer to actively suppress 'unhelpful' output
// @link https://github.com/composer/composer/pull/4886
$contents = @php_strip_whitespace($path);
if ('' === $contents) {
if (!file_exists($path)) {
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!self::isReadable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim((string) file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return [];
} else {
$message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted';
}
$error = error_get_last();
if (isset($error['message'])) {
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
}
throw new RuntimeException(\sprintf($message, $path));
}
// return early if there is no chance of matching anything in this file
Preg::matchAllStrictGroups('{\b(?:class|interface|trait|extension'.$extraTypes.')\s}i', $contents, $matches);
if ([] === $matches[0]) {
return [];
}
$p = new PhpFileCleaner($contents, \count($matches[0]));
$contents = $p->clean();
unset($p);
Preg::matchAll('{
(?:
\b(?<![\\\\$:>])(?P<type>class|interface|trait'.$extraTypes.') \s++ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
| '.self::EXTENSION_REGEX.'
| \b(?<![\\\\$:>])(?P<ns>namespace) (?P<nsname>\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;]
)
}ix', $contents, $matches);
$classes = [];
$namespace = '';
for ($i = 0, $len = \count($matches['type']); $i < $len; ++$i) {
if (isset($matches['ns'][$i]) && $matches['ns'][$i] !== '') {
$namespace = str_replace([' ', "\t", "\r", "\n"], '', (string) $matches['nsname'][$i]) . '\\';
} elseif (isset($matches['ext'][$i]) && $matches['ext'][$i] !== '') {
// named extension declarations (proposed "Extension Methods" RFC) declare the identifier
// before "on"; the target type after "on" and the receiver variable are not part of the name,
// and the anonymous form ("extension Target $var {") declares no autoloadable symbol at all
$name = $matches['extname'][$i];
\assert(\is_string($name));
/** @var class-string */
$className = ltrim($namespace . $name, '\\');
$classes[] = $className;
} else {
$name = $matches['name'][$i];
\assert(\is_string($name));
// skip anon classes extending/implementing
if ($name === 'extends') {
continue;
}
if ($name === 'implements') {
continue;
}
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp'.substr(str_replace(['-', ':'], ['_', '__'], $name), 1);
} elseif (strtolower((string) $matches['type'][$i]) === 'enum') {
// something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
// or:
// enum Foo:int { HERP = '123'; }
// The regex above captures the colon and type, which isn't part of
// the class name.
$colonPos = strrpos($name, ':');
if (false !== $colonPos) {
$name = substr($name, 0, $colonPos);
}
}
/** @var class-string */
$className = ltrim($namespace . $name, '\\');
$classes[] = $className;
}
}
return $classes;
}
private static function getExtraTypes(): string
{
static $extraTypes = null;
if (null === $extraTypes) {
$extraTypes = '';
$extraTypesArray = [];
if (PHP_VERSION_ID >= 80100 || (\defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>='))) {
$extraTypes .= '|enum';
$extraTypesArray = ['enum'];
}
PhpFileCleaner::setTypeConfig(array_merge(['class', 'interface', 'trait', 'extension'], $extraTypesArray));
}
return $extraTypes;
}
/**
* Cross-platform safe version of is_readable()
*
* This will also check for readability by reading the file as is_readable can not be trusted on network-mounts
* and \\wsl$ paths. See https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926
*
* @see Composer\Util\Filesystem::isReadable
*
* @return bool
*/
private static function isReadable(string $path)
{
if (is_readable($path)) {
return true;
}
if (is_file($path)) {
return false !== @file_get_contents($path, false, null, 0, 1);
}
// assume false otherwise
return false;
}
}