Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Symfony\Component\ErrorHandler;
13
 
14
use Composer\InstalledVersions;
15
use Doctrine\Common\Persistence\Proxy as LegacyProxy;
16
use Doctrine\Persistence\Proxy;
17
use Mockery\MockInterface;
18
use Phake\IMock;
19
use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation;
20
use PHPUnit\Framework\MockObject\MockObject;
21
use Prophecy\Prophecy\ProphecySubjectInterface;
22
use ProxyManager\Proxy\ProxyInterface;
23
use Symfony\Component\ErrorHandler\Internal\TentativeTypes;
24
use Symfony\Component\VarExporter\LazyObjectInterface;
25
 
26
/**
27
 * Autoloader checking if the class is really defined in the file found.
28
 *
29
 * The ClassLoader will wrap all registered autoloaders
30
 * and will throw an exception if a file is found but does
31
 * not declare the class.
32
 *
33
 * It can also patch classes to turn docblocks into actual return types.
34
 * This behavior is controlled by the SYMFONY_PATCH_TYPE_DECLARATIONS env var,
35
 * which is a url-encoded array with the follow parameters:
36
 *  - "force": any value enables deprecation notices - can be any of:
37
 *      - "phpdoc" to patch only docblock annotations
38
 *      - "2" to add all possible return types
39
 *      - "1" to add return types but only to tests/final/internal/private methods
40
 *  - "php": the target version of PHP - e.g. "7.1" doesn't generate "object" types
41
 *  - "deprecations": "1" to trigger a deprecation notice when a child class misses a
42
 *                    return type while the parent declares an "@return" annotation
43
 *
44
 * Note that patching doesn't care about any coding style so you'd better to run
45
 * php-cs-fixer after, with rules "phpdoc_trim_consecutive_blank_line_separation"
46
 * and "no_superfluous_phpdoc_tags" enabled typically.
47
 *
48
 * @author Fabien Potencier <fabien@symfony.com>
49
 * @author Christophe Coevoet <stof@notk.org>
50
 * @author Nicolas Grekas <p@tchwork.com>
51
 * @author Guilhem Niot <guilhem.niot@gmail.com>
52
 */
53
class DebugClassLoader
54
{
55
    private const SPECIAL_RETURN_TYPES = [
56
        'void' => 'void',
57
        'null' => 'null',
58
        'resource' => 'resource',
59
        'boolean' => 'bool',
60
        'true' => 'true',
61
        'false' => 'false',
62
        'integer' => 'int',
63
        'array' => 'array',
64
        'bool' => 'bool',
65
        'callable' => 'callable',
66
        'float' => 'float',
67
        'int' => 'int',
68
        'iterable' => 'iterable',
69
        'object' => 'object',
70
        'string' => 'string',
71
        'self' => 'self',
72
        'parent' => 'parent',
73
        'mixed' => 'mixed',
74
        'static' => 'static',
75
        '$this' => 'static',
76
        'list' => 'array',
77
        'class-string' => 'string',
78
        'never' => 'never',
79
    ];
80
 
81
    private const BUILTIN_RETURN_TYPES = [
82
        'void' => true,
83
        'array' => true,
84
        'false' => true,
85
        'bool' => true,
86
        'callable' => true,
87
        'float' => true,
88
        'int' => true,
89
        'iterable' => true,
90
        'object' => true,
91
        'string' => true,
92
        'self' => true,
93
        'parent' => true,
94
        'mixed' => true,
95
        'static' => true,
96
        'null' => true,
97
        'true' => true,
98
        'never' => true,
99
    ];
100
 
101
    private const MAGIC_METHODS = [
102
        '__isset' => 'bool',
103
        '__sleep' => 'array',
104
        '__toString' => 'string',
105
        '__debugInfo' => 'array',
106
        '__serialize' => 'array',
107
    ];
108
 
109
    /**
110
     * @var callable
111
     */
112
    private $classLoader;
113
    private bool $isFinder;
114
    private array $loaded = [];
115
    private array $patchTypes = [];
116
 
117
    private static int $caseCheck;
118
    private static array $checkedClasses = [];
119
    private static array $final = [];
120
    private static array $finalMethods = [];
121
    private static array $finalProperties = [];
122
    private static array $finalConstants = [];
123
    private static array $deprecated = [];
124
    private static array $internal = [];
125
    private static array $internalMethods = [];
126
    private static array $annotatedParameters = [];
127
    private static array $darwinCache = ['/' => ['/', []]];
128
    private static array $method = [];
129
    private static array $returnTypes = [];
130
    private static array $methodTraits = [];
131
    private static array $fileOffsets = [];
132
 
133
    public function __construct(callable $classLoader)
134
    {
135
        $this->classLoader = $classLoader;
136
        $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
137
        parse_str(getenv('SYMFONY_PATCH_TYPE_DECLARATIONS') ?: '', $this->patchTypes);
138
        $this->patchTypes += [
139
            'force' => null,
140
            'php' => \PHP_MAJOR_VERSION.'.'.\PHP_MINOR_VERSION,
141
            'deprecations' => true,
142
        ];
143
 
144
        if ('phpdoc' === $this->patchTypes['force']) {
145
            $this->patchTypes['force'] = 'docblock';
146
        }
147
 
148
        if (!isset(self::$caseCheck)) {
149
            $file = is_file(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
150
            $i = strrpos($file, \DIRECTORY_SEPARATOR);
151
            $dir = substr($file, 0, 1 + $i);
152
            $file = substr($file, 1 + $i);
153
            $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
154
            $test = realpath($dir.$test);
155
 
156
            if (false === $test || false === $i) {
157
                // filesystem is case sensitive
158
                self::$caseCheck = 0;
159
            } elseif (str_ends_with($test, $file)) {
160
                // filesystem is case insensitive and realpath() normalizes the case of characters
161
                self::$caseCheck = 1;
162
            } elseif ('Darwin' === \PHP_OS_FAMILY) {
163
                // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
164
                self::$caseCheck = 2;
165
            } else {
166
                // filesystem case checks failed, fallback to disabling them
167
                self::$caseCheck = 0;
168
            }
169
        }
170
    }
171
 
172
    public function getClassLoader(): callable
173
    {
174
        return $this->classLoader;
175
    }
176
 
177
    /**
178
     * Wraps all autoloaders.
179
     */
180
    public static function enable(): void
181
    {
182
        // Ensures we don't hit https://bugs.php.net/42098
183
        class_exists(\Symfony\Component\ErrorHandler\ErrorHandler::class);
184
        class_exists(\Psr\Log\LogLevel::class);
185
 
186
        if (!\is_array($functions = spl_autoload_functions())) {
187
            return;
188
        }
189
 
190
        foreach ($functions as $function) {
191
            spl_autoload_unregister($function);
192
        }
193
 
194
        foreach ($functions as $function) {
195
            if (!\is_array($function) || !$function[0] instanceof self) {
196
                $function = [new static($function), 'loadClass'];
197
            }
198
 
199
            spl_autoload_register($function);
200
        }
201
    }
202
 
203
    /**
204
     * Disables the wrapping.
205
     */
206
    public static function disable(): void
207
    {
208
        if (!\is_array($functions = spl_autoload_functions())) {
209
            return;
210
        }
211
 
212
        foreach ($functions as $function) {
213
            spl_autoload_unregister($function);
214
        }
215
 
216
        foreach ($functions as $function) {
217
            if (\is_array($function) && $function[0] instanceof self) {
218
                $function = $function[0]->getClassLoader();
219
            }
220
 
221
            spl_autoload_register($function);
222
        }
223
    }
224
 
225
    public static function checkClasses(): bool
226
    {
227
        if (!\is_array($functions = spl_autoload_functions())) {
228
            return false;
229
        }
230
 
231
        $loader = null;
232
 
233
        foreach ($functions as $function) {
234
            if (\is_array($function) && $function[0] instanceof self) {
235
                $loader = $function[0];
236
                break;
237
            }
238
        }
239
 
240
        if (null === $loader) {
241
            return false;
242
        }
243
 
244
        static $offsets = [
245
            'get_declared_interfaces' => 0,
246
            'get_declared_traits' => 0,
247
            'get_declared_classes' => 0,
248
        ];
249
 
250
        foreach ($offsets as $getSymbols => $i) {
251
            $symbols = $getSymbols();
252
 
253
            for (; $i < \count($symbols); ++$i) {
254
                if (!is_subclass_of($symbols[$i], MockObject::class)
255
                    && !is_subclass_of($symbols[$i], ProphecySubjectInterface::class)
256
                    && !is_subclass_of($symbols[$i], Proxy::class)
257
                    && !is_subclass_of($symbols[$i], ProxyInterface::class)
258
                    && !is_subclass_of($symbols[$i], LazyObjectInterface::class)
259
                    && !is_subclass_of($symbols[$i], LegacyProxy::class)
260
                    && !is_subclass_of($symbols[$i], MockInterface::class)
261
                    && !is_subclass_of($symbols[$i], IMock::class)
262
                ) {
263
                    $loader->checkClass($symbols[$i]);
264
                }
265
            }
266
 
267
            $offsets[$getSymbols] = $i;
268
        }
269
 
270
        return true;
271
    }
272
 
273
    public function findFile(string $class): ?string
274
    {
275
        return $this->isFinder ? ($this->classLoader[0]->findFile($class) ?: null) : null;
276
    }
277
 
278
    /**
279
     * Loads the given class or interface.
280
     *
281
     * @throws \RuntimeException
282
     */
283
    public function loadClass(string $class): void
284
    {
285
        $e = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
286
 
287
        try {
288
            if ($this->isFinder && !isset($this->loaded[$class])) {
289
                $this->loaded[$class] = true;
290
                if (!$file = $this->classLoader[0]->findFile($class) ?: '') {
291
                    // no-op
292
                } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
293
                    include $file;
294
 
295
                    return;
296
                } elseif (false === include $file) {
297
                    return;
298
                }
299
            } else {
300
                ($this->classLoader)($class);
301
                $file = '';
302
            }
303
        } finally {
304
            error_reporting($e);
305
        }
306
 
307
        $this->checkClass($class, $file);
308
    }
309
 
310
    private function checkClass(string $class, string $file = null): void
311
    {
312
        $exists = null === $file || class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
313
 
314
        if (null !== $file && $class && '\\' === $class[0]) {
315
            $class = substr($class, 1);
316
        }
317
 
318
        if ($exists) {
319
            if (isset(self::$checkedClasses[$class])) {
320
                return;
321
            }
322
            self::$checkedClasses[$class] = true;
323
 
324
            $refl = new \ReflectionClass($class);
325
            if (null === $file && $refl->isInternal()) {
326
                return;
327
            }
328
            $name = $refl->getName();
329
 
330
            if ($name !== $class && 0 === strcasecmp($name, $class)) {
331
                throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
332
            }
333
 
334
            $deprecations = $this->checkAnnotations($refl, $name);
335
 
336
            foreach ($deprecations as $message) {
337
                @trigger_error($message, \E_USER_DEPRECATED);
338
            }
339
        }
340
 
341
        if (!$file) {
342
            return;
343
        }
344
 
345
        if (!$exists) {
346
            if (str_contains($class, '/')) {
347
                throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
348
            }
349
 
350
            throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
351
        }
352
 
353
        if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
354
            throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
355
        }
356
    }
357
 
358
    public function checkAnnotations(\ReflectionClass $refl, string $class): array
359
    {
360
        if (
361
            'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7' === $class
362
            || 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV6' === $class
363
        ) {
364
            return [];
365
        }
366
        $deprecations = [];
367
 
368
        $className = str_contains($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
369
 
370
        // Don't trigger deprecations for classes in the same vendor
371
        if ($class !== $className) {
372
            $vendor = preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' : '';
373
            $vendorLen = \strlen($vendor);
374
        } elseif (2 > $vendorLen = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) {
375
            $vendorLen = 0;
376
            $vendor = '';
377
        } else {
378
            $vendor = str_replace('_', '\\', substr($class, 0, $vendorLen));
379
        }
380
 
381
        $parent = get_parent_class($class) ?: null;
382
        self::$returnTypes[$class] = [];
383
        $classIsTemplate = false;
384
 
385
        // Detect annotations on the class
386
        if ($doc = $this->parsePhpDoc($refl)) {
387
            $classIsTemplate = isset($doc['template']);
388
 
389
            foreach (['final', 'deprecated', 'internal'] as $annotation) {
390
                if (null !== $description = $doc[$annotation][0] ?? null) {
391
                    self::${$annotation}[$class] = '' !== $description ? ' '.$description.(preg_match('/[.!]$/', $description) ? '' : '.') : '.';
392
                }
393
            }
394
 
395
            if ($refl->isInterface() && isset($doc['method'])) {
396
                foreach ($doc['method'] as $name => [$static, $returnType, $signature, $description]) {
397
                    self::$method[$class][] = [$class, $static, $returnType, $name.$signature, $description];
398
 
399
                    if ('' !== $returnType) {
400
                        $this->setReturnType($returnType, $refl->name, $name, $refl->getFileName(), $parent);
401
                    }
402
                }
403
            }
404
        }
405
 
406
        $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
407
        if ($parent) {
408
            $parentAndOwnInterfaces[$parent] = $parent;
409
 
410
            if (!isset(self::$checkedClasses[$parent])) {
411
                $this->checkClass($parent);
412
            }
413
 
414
            if (isset(self::$final[$parent])) {
415
                $deprecations[] = sprintf('The "%s" class is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $className);
416
            }
417
        }
418
 
419
        // Detect if the parent is annotated
420
        foreach ($parentAndOwnInterfaces + class_uses($class, false) as $use) {
421
            if (!isset(self::$checkedClasses[$use])) {
422
                $this->checkClass($use);
423
            }
424
            if (isset(self::$deprecated[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen) && !isset(self::$deprecated[$class])) {
425
                $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
426
                $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
427
 
428
                $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s', $className, $type, $verb, $use, self::$deprecated[$use]);
429
            }
430
            if (isset(self::$internal[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)) {
431
                $deprecations[] = sprintf('The "%s" %s is considered internal%s It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $className);
432
            }
433
            if (isset(self::$method[$use])) {
434
                if ($refl->isAbstract()) {
435
                    if (isset(self::$method[$class])) {
436
                        self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]);
437
                    } else {
438
                        self::$method[$class] = self::$method[$use];
439
                    }
440
                } elseif (!$refl->isInterface()) {
441
                    if (!strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)
442
                        && str_starts_with($className, 'Symfony\\')
443
                        && (!class_exists(InstalledVersions::class)
444
                            || 'symfony/symfony' !== InstalledVersions::getRootPackage()['name'])
445
                    ) {
446
                        // skip "same vendor" @method deprecations for Symfony\* classes unless symfony/symfony is being tested
447
                        continue;
448
                    }
449
                    $hasCall = $refl->hasMethod('__call');
450
                    $hasStaticCall = $refl->hasMethod('__callStatic');
451
                    foreach (self::$method[$use] as [$interface, $static, $returnType, $name, $description]) {
452
                        if ($static ? $hasStaticCall : $hasCall) {
453
                            continue;
454
                        }
455
                        $realName = substr($name, 0, strpos($name, '('));
456
                        if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
457
                            $deprecations[] = sprintf('Class "%s" should implement method "%s::%s%s"%s', $className, ($static ? 'static ' : '').$interface, $name, $returnType ? ': '.$returnType : '', null === $description ? '.' : ': '.$description);
458
                        }
459
                    }
460
                }
461
            }
462
        }
463
 
464
        if (trait_exists($class)) {
465
            $file = $refl->getFileName();
466
 
467
            foreach ($refl->getMethods() as $method) {
468
                if ($method->getFileName() === $file) {
469
                    self::$methodTraits[$file][$method->getStartLine()] = $class;
470
                }
471
            }
472
 
473
            return $deprecations;
474
        }
475
 
476
        // Inherit @final, @internal, @param and @return annotations for methods
477
        self::$finalMethods[$class] = [];
478
        self::$internalMethods[$class] = [];
479
        self::$annotatedParameters[$class] = [];
480
        self::$finalProperties[$class] = [];
481
        self::$finalConstants[$class] = [];
482
        foreach ($parentAndOwnInterfaces as $use) {
483
            foreach (['finalMethods', 'internalMethods', 'annotatedParameters', 'returnTypes', 'finalProperties', 'finalConstants'] as $property) {
484
                if (isset(self::${$property}[$use])) {
485
                    self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
486
                }
487
            }
488
 
489
            if (null !== (TentativeTypes::RETURN_TYPES[$use] ?? null)) {
490
                foreach (TentativeTypes::RETURN_TYPES[$use] as $method => $returnType) {
491
                    $returnType = explode('|', $returnType);
492
                    foreach ($returnType as $i => $t) {
493
                        if ('?' !== $t && !isset(self::BUILTIN_RETURN_TYPES[$t])) {
494
                            $returnType[$i] = '\\'.$t;
495
                        }
496
                    }
497
                    $returnType = implode('|', $returnType);
498
 
499
                    self::$returnTypes[$class] += [$method => [$returnType, str_starts_with($returnType, '?') ? substr($returnType, 1).'|null' : $returnType, $use, '']];
500
                }
501
            }
502
        }
503
 
504
        foreach ($refl->getMethods() as $method) {
505
            if ($method->class !== $class) {
506
                continue;
507
            }
508
 
509
            if (null === $ns = self::$methodTraits[$method->getFileName()][$method->getStartLine()] ?? null) {
510
                $ns = $vendor;
511
                $len = $vendorLen;
512
            } elseif (2 > $len = 1 + (strpos($ns, '\\') ?: strpos($ns, '_'))) {
513
                $len = 0;
514
                $ns = '';
515
            } else {
516
                $ns = str_replace('_', '\\', substr($ns, 0, $len));
517
            }
518
 
519
            if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
520
                [$declaringClass, $message] = self::$finalMethods[$parent][$method->name];
521
                $deprecations[] = sprintf('The "%s::%s()" method is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className);
522
            }
523
 
524
            if (isset(self::$internalMethods[$class][$method->name])) {
525
                [$declaringClass, $message] = self::$internalMethods[$class][$method->name];
526
                if (strncmp($ns, $declaringClass, $len)) {
527
                    $deprecations[] = sprintf('The "%s::%s()" method is considered internal%s It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className);
528
                }
529
            }
530
 
531
            // To read method annotations
532
            $doc = $this->parsePhpDoc($method);
533
 
534
            if (($classIsTemplate || isset($doc['template'])) && $method->hasReturnType()) {
535
                unset($doc['return']);
536
            }
537
 
538
            if (isset(self::$annotatedParameters[$class][$method->name])) {
539
                $definedParameters = [];
540
                foreach ($method->getParameters() as $parameter) {
541
                    $definedParameters[$parameter->name] = true;
542
                }
543
 
544
                foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
545
                    if (!isset($definedParameters[$parameterName]) && !isset($doc['param'][$parameterName])) {
546
                        $deprecations[] = sprintf($deprecation, $className);
547
                    }
548
                }
549
            }
550
 
551
            $forcePatchTypes = $this->patchTypes['force'];
552
 
553
            if ($canAddReturnType = null !== $forcePatchTypes && !str_contains($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
554
                if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
555
                    $this->patchTypes['force'] = $forcePatchTypes ?: 'docblock';
556
                }
557
 
558
                $canAddReturnType = 2 === (int) $forcePatchTypes
559
                    || false !== stripos($method->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR)
560
                    || $refl->isFinal()
561
                    || $method->isFinal()
562
                    || $method->isPrivate()
563
                    || ('.' === (self::$internal[$class] ?? null) && !$refl->isAbstract())
564
                    || '.' === (self::$final[$class] ?? null)
565
                    || '' === ($doc['final'][0] ?? null)
566
                    || '' === ($doc['internal'][0] ?? null)
567
                ;
568
            }
569
 
570
            if (null !== ($returnType = self::$returnTypes[$class][$method->name] ?? null) && 'docblock' === $this->patchTypes['force'] && !$method->hasReturnType() && isset(TentativeTypes::RETURN_TYPES[$returnType[2]][$method->name])) {
571
                $this->patchReturnTypeWillChange($method);
572
            }
573
 
574
            if (null !== ($returnType ??= self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !isset($doc['return'])) {
575
                [$normalizedType, $returnType, $declaringClass, $declaringFile] = \is_string($returnType) ? [$returnType, $returnType, '', ''] : $returnType;
576
 
577
                if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) {
578
                    $this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
579
                }
580
                if (!isset($doc['deprecated']) && strncmp($ns, $declaringClass, $len)) {
581
                    if ('docblock' === $this->patchTypes['force']) {
582
                        $this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
583
                    } elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) {
584
                        $deprecations[] = sprintf('Method "%s::%s()" might add "%s" as a native return type declaration in the future. Do the same in %s "%s" now to avoid errors or add an explicit @return annotation to suppress this message.', $declaringClass, $method->name, $normalizedType, interface_exists($declaringClass) ? 'implementation' : 'child class', $className);
585
                    }
586
                }
587
            }
588
 
589
            if (!$doc) {
590
                $this->patchTypes['force'] = $forcePatchTypes;
591
 
592
                continue;
593
            }
594
 
595
            if (isset($doc['return']) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
596
                $this->setReturnType($doc['return'] ?? self::MAGIC_METHODS[$method->name], $method->class, $method->name, $method->getFileName(), $parent, $method->getReturnType());
597
 
598
                if (isset(self::$returnTypes[$class][$method->name][0]) && $canAddReturnType) {
599
                    $this->fixReturnStatements($method, self::$returnTypes[$class][$method->name][0]);
600
                }
601
 
602
                if ($method->isPrivate()) {
603
                    unset(self::$returnTypes[$class][$method->name]);
604
                }
605
            }
606
 
607
            $this->patchTypes['force'] = $forcePatchTypes;
608
 
609
            if ($method->isPrivate()) {
610
                continue;
611
            }
612
 
613
            $finalOrInternal = false;
614
 
615
            foreach (['final', 'internal'] as $annotation) {
616
                if (null !== $description = $doc[$annotation][0] ?? null) {
617
                    self::${$annotation.'Methods'}[$class][$method->name] = [$class, '' !== $description ? ' '.$description.(preg_match('/[[:punct:]]$/', $description) ? '' : '.') : '.'];
618
                    $finalOrInternal = true;
619
                }
620
            }
621
 
622
            if ($finalOrInternal || $method->isConstructor() || !isset($doc['param']) || StatelessInvocation::class === $class) {
623
                continue;
624
            }
625
            if (!isset(self::$annotatedParameters[$class][$method->name])) {
626
                $definedParameters = [];
627
                foreach ($method->getParameters() as $parameter) {
628
                    $definedParameters[$parameter->name] = true;
629
                }
630
            }
631
            foreach ($doc['param'] as $parameterName => $parameterType) {
632
                if (!isset($definedParameters[$parameterName])) {
633
                    self::$annotatedParameters[$class][$method->name][$parameterName] = sprintf('The "%%s::%s()" method will require a new "%s$%s" argument in the next major version of its %s "%s", not defining it is deprecated.', $method->name, $parameterType ? $parameterType.' ' : '', $parameterName, interface_exists($className) ? 'interface' : 'parent class', $className);
634
                }
635
            }
636
        }
637
 
638
        $finals = isset(self::$final[$class]) || $refl->isFinal() ? [] : [
639
            'finalConstants' => $refl->getReflectionConstants(\ReflectionClassConstant::IS_PUBLIC | \ReflectionClassConstant::IS_PROTECTED),
640
            'finalProperties' => $refl->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED),
641
        ];
642
        foreach ($finals as $type => $reflectors) {
643
            foreach ($reflectors as $r) {
644
                if ($r->class !== $class) {
645
                    continue;
646
                }
647
 
648
                $doc = $this->parsePhpDoc($r);
649
 
650
                foreach ($parentAndOwnInterfaces as $use) {
651
                    if (isset(self::${$type}[$use][$r->name]) && !isset($doc['deprecated']) && ('finalConstants' === $type || substr($use, 0, strrpos($use, '\\')) !== substr($use, 0, strrpos($class, '\\')))) {
652
                        $msg = 'finalConstants' === $type ? '%s" constant' : '$%s" property';
653
                        $deprecations[] = sprintf('The "%s::'.$msg.' is considered final. You should not override it in "%s".', self::${$type}[$use][$r->name], $r->name, $class);
654
                    }
655
                }
656
 
657
                if (isset($doc['final']) || ('finalProperties' === $type && str_starts_with($class, 'Symfony\\') && !$r->hasType())) {
658
                    self::${$type}[$class][$r->name] = $class;
659
                }
660
            }
661
        }
662
 
663
        return $deprecations;
664
    }
665
 
666
    public function checkCase(\ReflectionClass $refl, string $file, string $class): ?array
667
    {
668
        $real = explode('\\', $class.strrchr($file, '.'));
669
        $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
670
 
671
        $i = \count($tail) - 1;
672
        $j = \count($real) - 1;
673
 
674
        while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
675
            --$i;
676
            --$j;
677
        }
678
 
679
        array_splice($tail, 0, $i + 1);
680
 
681
        if (!$tail) {
682
            return null;
683
        }
684
 
685
        $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
686
        $tailLen = \strlen($tail);
687
        $real = $refl->getFileName();
688
 
689
        if (2 === self::$caseCheck) {
690
            $real = $this->darwinRealpath($real);
691
        }
692
 
693
        if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
694
            && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
695
        ) {
696
            return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)];
697
        }
698
 
699
        return null;
700
    }
701
 
702
    /**
703
     * `realpath` on MacOSX doesn't normalize the case of characters.
704
     */
705
    private function darwinRealpath(string $real): string
706
    {
707
        $i = 1 + strrpos($real, '/');
708
        $file = substr($real, $i);
709
        $real = substr($real, 0, $i);
710
 
711
        if (isset(self::$darwinCache[$real])) {
712
            $kDir = $real;
713
        } else {
714
            $kDir = strtolower($real);
715
 
716
            if (isset(self::$darwinCache[$kDir])) {
717
                $real = self::$darwinCache[$kDir][0];
718
            } else {
719
                $dir = getcwd();
720
 
721
                if (!@chdir($real)) {
722
                    return $real.$file;
723
                }
724
 
725
                $real = getcwd().'/';
726
                chdir($dir);
727
 
728
                $dir = $real;
729
                $k = $kDir;
730
                $i = \strlen($dir) - 1;
731
                while (!isset(self::$darwinCache[$k])) {
732
                    self::$darwinCache[$k] = [$dir, []];
733
                    self::$darwinCache[$dir] = &self::$darwinCache[$k];
734
 
735
                    while ('/' !== $dir[--$i]) {
736
                    }
737
                    $k = substr($k, 0, ++$i);
738
                    $dir = substr($dir, 0, $i--);
739
                }
740
            }
741
        }
742
 
743
        $dirFiles = self::$darwinCache[$kDir][1];
744
 
745
        if (!isset($dirFiles[$file]) && str_ends_with($file, ') : eval()\'d code')) {
746
            // Get the file name from "file_name.php(123) : eval()'d code"
747
            $file = substr($file, 0, strrpos($file, '(', -17));
748
        }
749
 
750
        if (isset($dirFiles[$file])) {
751
            return $real.$dirFiles[$file];
752
        }
753
 
754
        $kFile = strtolower($file);
755
 
756
        if (!isset($dirFiles[$kFile])) {
757
            foreach (scandir($real, 2) as $f) {
758
                if ('.' !== $f[0]) {
759
                    $dirFiles[$f] = $f;
760
                    if ($f === $file) {
761
                        $kFile = $k = $file;
762
                    } elseif ($f !== $k = strtolower($f)) {
763
                        $dirFiles[$k] = $f;
764
                    }
765
                }
766
            }
767
            self::$darwinCache[$kDir][1] = $dirFiles;
768
        }
769
 
770
        return $real.$dirFiles[$kFile];
771
    }
772
 
773
    /**
774
     * `class_implements` includes interfaces from the parents so we have to manually exclude them.
775
     *
776
     * @return string[]
777
     */
778
    private function getOwnInterfaces(string $class, ?string $parent): array
779
    {
780
        $ownInterfaces = class_implements($class, false);
781
 
782
        if ($parent) {
783
            foreach (class_implements($parent, false) as $interface) {
784
                unset($ownInterfaces[$interface]);
785
            }
786
        }
787
 
788
        foreach ($ownInterfaces as $interface) {
789
            foreach (class_implements($interface) as $interface) {
790
                unset($ownInterfaces[$interface]);
791
            }
792
        }
793
 
794
        return $ownInterfaces;
795
    }
796
 
797
    private function setReturnType(string $types, string $class, string $method, string $filename, ?string $parent, \ReflectionType $returnType = null): void
798
    {
799
        if ('__construct' === $method) {
800
            return;
801
        }
802
 
803
        if ('null' === $types) {
804
            self::$returnTypes[$class][$method] = ['null', 'null', $class, $filename];
805
 
806
            return;
807
        }
808
 
809
        if ($nullable = str_starts_with($types, 'null|')) {
810
            $types = substr($types, 5);
811
        } elseif ($nullable = str_ends_with($types, '|null')) {
812
            $types = substr($types, 0, -5);
813
        }
814
        $arrayType = ['array' => 'array'];
815
        $typesMap = [];
816
        $glue = str_contains($types, '&') ? '&' : '|';
817
        foreach (explode($glue, $types) as $t) {
818
            $t = self::SPECIAL_RETURN_TYPES[strtolower($t)] ?? $t;
819
            $typesMap[$this->normalizeType($t, $class, $parent, $returnType)][$t] = $t;
820
        }
821
 
822
        if (isset($typesMap['array'])) {
823
            if (isset($typesMap['Traversable']) || isset($typesMap['\Traversable'])) {
824
                $typesMap['iterable'] = $arrayType !== $typesMap['array'] ? $typesMap['array'] : ['iterable'];
825
                unset($typesMap['array'], $typesMap['Traversable'], $typesMap['\Traversable']);
826
            } elseif ($arrayType !== $typesMap['array'] && isset(self::$returnTypes[$class][$method]) && !$returnType) {
827
                return;
828
            }
829
        }
830
 
831
        if (isset($typesMap['array']) && isset($typesMap['iterable'])) {
832
            if ($arrayType !== $typesMap['array']) {
833
                $typesMap['iterable'] = $typesMap['array'];
834
            }
835
            unset($typesMap['array']);
836
        }
837
 
838
        $iterable = $object = true;
839
        foreach ($typesMap as $n => $t) {
840
            if ('null' !== $n) {
841
                $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || str_contains($n, 'Iterator'));
842
                $object = $object && (\in_array($n, ['callable', 'object', '$this', 'static']) || !isset(self::SPECIAL_RETURN_TYPES[$n]));
843
            }
844
        }
845
 
846
        $phpTypes = [];
847
        $docTypes = [];
848
 
849
        foreach ($typesMap as $n => $t) {
850
            if ('null' === $n) {
851
                $nullable = true;
852
                continue;
853
            }
854
 
855
            $docTypes[] = $t;
856
 
857
            if ('mixed' === $n || 'void' === $n) {
858
                $nullable = false;
859
                $phpTypes = ['' => $n];
860
                continue;
861
            }
862
 
863
            if ('resource' === $n) {
864
                // there is no native type for "resource"
865
                return;
866
            }
867
 
868
            if (!preg_match('/^(?:\\\\?[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)+$/', $n)) {
869
                // exclude any invalid PHP class name (e.g. `Cookie::SAMESITE_*`)
870
                continue;
871
            }
872
 
873
            if (!isset($phpTypes[''])) {
874
                $phpTypes[] = $n;
875
            }
876
        }
877
        $docTypes = array_merge([], ...$docTypes);
878
 
879
        if (!$phpTypes) {
880
            return;
881
        }
882
 
883
        if (1 < \count($phpTypes)) {
884
            if ($iterable && '8.0' > $this->patchTypes['php']) {
885
                $phpTypes = $docTypes = ['iterable'];
886
            } elseif ($object && 'object' === $this->patchTypes['force']) {
887
                $phpTypes = $docTypes = ['object'];
888
            } elseif ('8.0' > $this->patchTypes['php']) {
889
                // ignore multi-types return declarations
890
                return;
891
            }
892
        }
893
 
894
        $phpType = sprintf($nullable ? (1 < \count($phpTypes) ? '%s|null' : '?%s') : '%s', implode($glue, $phpTypes));
895
        $docType = sprintf($nullable ? '%s|null' : '%s', implode($glue, $docTypes));
896
 
897
        self::$returnTypes[$class][$method] = [$phpType, $docType, $class, $filename];
898
    }
899
 
900
    private function normalizeType(string $type, string $class, ?string $parent, ?\ReflectionType $returnType): string
901
    {
902
        if (isset(self::SPECIAL_RETURN_TYPES[$lcType = strtolower($type)])) {
903
            if ('parent' === $lcType = self::SPECIAL_RETURN_TYPES[$lcType]) {
904
                $lcType = null !== $parent ? '\\'.$parent : 'parent';
905
            } elseif ('self' === $lcType) {
906
                $lcType = '\\'.$class;
907
            }
908
 
909
            return $lcType;
910
        }
911
 
912
        // We could resolve "use" statements to return the FQDN
913
        // but this would be too expensive for a runtime checker
914
 
915
        if (!str_ends_with($type, '[]')) {
916
            return $type;
917
        }
918
 
919
        if ($returnType instanceof \ReflectionNamedType) {
920
            $type = $returnType->getName();
921
 
922
            if ('mixed' !== $type) {
923
                return isset(self::SPECIAL_RETURN_TYPES[$type]) ? $type : '\\'.$type;
924
            }
925
        }
926
 
927
        return 'array';
928
    }
929
 
930
    /**
931
     * Utility method to add #[ReturnTypeWillChange] where php triggers deprecations.
932
     */
933
    private function patchReturnTypeWillChange(\ReflectionMethod $method)
934
    {
935
        if (\count($method->getAttributes(\ReturnTypeWillChange::class))) {
936
            return;
937
        }
938
 
939
        if (!is_file($file = $method->getFileName())) {
940
            return;
941
        }
942
 
943
        $fileOffset = self::$fileOffsets[$file] ?? 0;
944
 
945
        $code = file($file);
946
 
947
        $startLine = $method->getStartLine() + $fileOffset - 2;
948
 
949
        if (false !== stripos($code[$startLine], 'ReturnTypeWillChange')) {
950
            return;
951
        }
952
 
953
        $code[$startLine] .= "    #[\\ReturnTypeWillChange]\n";
954
        self::$fileOffsets[$file] = 1 + $fileOffset;
955
        file_put_contents($file, $code);
956
    }
957
 
958
    /**
959
     * Utility method to add @return annotations to the Symfony code-base where it triggers self-deprecations.
960
     */
961
    private function patchMethod(\ReflectionMethod $method, string $returnType, string $declaringFile, string $normalizedType)
962
    {
963
        static $patchedMethods = [];
964
        static $useStatements = [];
965
 
966
        if (!is_file($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) {
967
            return;
968
        }
969
 
970
        $patchedMethods[$file][$startLine] = true;
971
        $fileOffset = self::$fileOffsets[$file] ?? 0;
972
        $startLine += $fileOffset - 2;
973
        if ($nullable = str_ends_with($returnType, '|null')) {
974
            $returnType = substr($returnType, 0, -5);
975
        }
976
        $glue = str_contains($returnType, '&') ? '&' : '|';
977
        $returnType = explode($glue, $returnType);
978
        $code = file($file);
979
 
980
        foreach ($returnType as $i => $type) {
981
            if (preg_match('/((?:\[\])+)$/', $type, $m)) {
982
                $type = substr($type, 0, -\strlen($m[1]));
983
                $format = '%s'.$m[1];
984
            } else {
985
                $format = null;
986
            }
987
 
988
            if (isset(self::SPECIAL_RETURN_TYPES[$type]) || ('\\' === $type[0] && !$p = strrpos($type, '\\', 1))) {
989
                continue;
990
            }
991
 
992
            [$namespace, $useOffset, $useMap] = $useStatements[$file] ??= self::getUseStatements($file);
993
 
994
            if ('\\' !== $type[0]) {
995
                [$declaringNamespace, , $declaringUseMap] = $useStatements[$declaringFile] ??= self::getUseStatements($declaringFile);
996
 
997
                $p = strpos($type, '\\', 1);
998
                $alias = $p ? substr($type, 0, $p) : $type;
999
 
1000
                if (isset($declaringUseMap[$alias])) {
1001
                    $type = '\\'.$declaringUseMap[$alias].($p ? substr($type, $p) : '');
1002
                } else {
1003
                    $type = '\\'.$declaringNamespace.$type;
1004
                }
1005
 
1006
                $p = strrpos($type, '\\', 1);
1007
            }
1008
 
1009
            $alias = substr($type, 1 + $p);
1010
            $type = substr($type, 1);
1011
 
1012
            if (!isset($useMap[$alias]) && (class_exists($c = $namespace.$alias) || interface_exists($c) || trait_exists($c))) {
1013
                $useMap[$alias] = $c;
1014
            }
1015
 
1016
            if (!isset($useMap[$alias])) {
1017
                $useStatements[$file][2][$alias] = $type;
1018
                $code[$useOffset] = "use $type;\n".$code[$useOffset];
1019
                ++$fileOffset;
1020
            } elseif ($useMap[$alias] !== $type) {
1021
                $alias .= 'FIXME';
1022
                $useStatements[$file][2][$alias] = $type;
1023
                $code[$useOffset] = "use $type as $alias;\n".$code[$useOffset];
1024
                ++$fileOffset;
1025
            }
1026
 
1027
            $returnType[$i] = null !== $format ? sprintf($format, $alias) : $alias;
1028
        }
1029
 
1030
        if ('docblock' === $this->patchTypes['force'] || ('object' === $normalizedType && '7.1' === $this->patchTypes['php'])) {
1031
            $returnType = implode($glue, $returnType).($nullable ? '|null' : '');
1032
 
1033
            if (str_contains($code[$startLine], '#[')) {
1034
                --$startLine;
1035
            }
1036
 
1037
            if ($method->getDocComment()) {
1038
                $code[$startLine] = "     * @return $returnType\n".$code[$startLine];
1039
            } else {
1040
                $code[$startLine] .= <<<EOTXT
1041
    /**
1042
     * @return $returnType
1043
     */
1044
 
1045
EOTXT;
1046
            }
1047
 
1048
            $fileOffset += substr_count($code[$startLine], "\n") - 1;
1049
        }
1050
 
1051
        self::$fileOffsets[$file] = $fileOffset;
1052
        file_put_contents($file, $code);
1053
 
1054
        $this->fixReturnStatements($method, $normalizedType);
1055
    }
1056
 
1057
    private static function getUseStatements(string $file): array
1058
    {
1059
        $namespace = '';
1060
        $useMap = [];
1061
        $useOffset = 0;
1062
 
1063
        if (!is_file($file)) {
1064
            return [$namespace, $useOffset, $useMap];
1065
        }
1066
 
1067
        $file = file($file);
1068
 
1069
        for ($i = 0; $i < \count($file); ++$i) {
1070
            if (preg_match('/^(class|interface|trait|abstract) /', $file[$i])) {
1071
                break;
1072
            }
1073
 
1074
            if (str_starts_with($file[$i], 'namespace ')) {
1075
                $namespace = substr($file[$i], \strlen('namespace '), -2).'\\';
1076
                $useOffset = $i + 2;
1077
            }
1078
 
1079
            if (str_starts_with($file[$i], 'use ')) {
1080
                $useOffset = $i;
1081
 
1082
                for (; str_starts_with($file[$i], 'use '); ++$i) {
1083
                    $u = explode(' as ', substr($file[$i], 4, -2), 2);
1084
 
1085
                    if (1 === \count($u)) {
1086
                        $p = strrpos($u[0], '\\');
1087
                        $useMap[substr($u[0], false !== $p ? 1 + $p : 0)] = $u[0];
1088
                    } else {
1089
                        $useMap[$u[1]] = $u[0];
1090
                    }
1091
                }
1092
 
1093
                break;
1094
            }
1095
        }
1096
 
1097
        return [$namespace, $useOffset, $useMap];
1098
    }
1099
 
1100
    private function fixReturnStatements(\ReflectionMethod $method, string $returnType)
1101
    {
1102
        if ('docblock' !== $this->patchTypes['force']) {
1103
            if ('7.1' === $this->patchTypes['php'] && 'object' === ltrim($returnType, '?')) {
1104
                return;
1105
            }
1106
 
1107
            if ('7.4' > $this->patchTypes['php'] && $method->hasReturnType()) {
1108
                return;
1109
            }
1110
 
1111
            if ('8.0' > $this->patchTypes['php'] && (str_contains($returnType, '|') || \in_array($returnType, ['mixed', 'static'], true))) {
1112
                return;
1113
            }
1114
 
1115
            if ('8.1' > $this->patchTypes['php'] && str_contains($returnType, '&')) {
1116
                return;
1117
            }
1118
        }
1119
 
1120
        if (!is_file($file = $method->getFileName())) {
1121
            return;
1122
        }
1123
 
1124
        $fixedCode = $code = file($file);
1125
        $i = (self::$fileOffsets[$file] ?? 0) + $method->getStartLine();
1126
 
1127
        if ('?' !== $returnType && 'docblock' !== $this->patchTypes['force']) {
1128
            $fixedCode[$i - 1] = preg_replace('/\)(?::[^;\n]++)?(;?\n)/', "): $returnType\\1", $code[$i - 1]);
1129
        }
1130
 
1131
        $end = $method->isGenerator() ? $i : $method->getEndLine();
688 lars 1132
        $inClosure = false;
1133
        $braces = 0;
148 lars 1134
        for (; $i < $end; ++$i) {
688 lars 1135
            if (!$inClosure) {
1136
                $inClosure = str_contains($code[$i], 'function (');
1137
            }
1138
 
1139
            if ($inClosure) {
1140
                $braces += substr_count($code[$i], '{') - substr_count($code[$i], '}');
1141
                $inClosure = $braces > 0;
1142
 
1143
                continue;
1144
            }
1145
 
148 lars 1146
            if ('void' === $returnType) {
1147
                $fixedCode[$i] = str_replace('    return null;', '    return;', $code[$i]);
1148
            } elseif ('mixed' === $returnType || '?' === $returnType[0]) {
1149
                $fixedCode[$i] = str_replace('    return;', '    return null;', $code[$i]);
1150
            } else {
1151
                $fixedCode[$i] = str_replace('    return;', "    return $returnType!?;", $code[$i]);
1152
            }
1153
        }
1154
 
1155
        if ($fixedCode !== $code) {
1156
            file_put_contents($file, $fixedCode);
1157
        }
1158
    }
1159
 
1160
    /**
1161
     * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflector
1162
     */
1163
    private function parsePhpDoc(\Reflector $reflector): array
1164
    {
1165
        if (!$doc = $reflector->getDocComment()) {
1166
            return [];
1167
        }
1168
 
1169
        $tagName = '';
1170
        $tagContent = '';
1171
 
1172
        $tags = [];
1173
 
1174
        foreach (explode("\n", substr($doc, 3, -2)) as $line) {
1175
            $line = ltrim($line);
1176
            $line = ltrim($line, '*');
1177
 
1178
            if ('' === $line = trim($line)) {
1179
                if ('' !== $tagName) {
1180
                    $tags[$tagName][] = $tagContent;
1181
                }
1182
                $tagName = $tagContent = '';
1183
                continue;
1184
            }
1185
 
1186
            if ('@' === $line[0]) {
1187
                if ('' !== $tagName) {
1188
                    $tags[$tagName][] = $tagContent;
1189
                    $tagContent = '';
1190
                }
1191
 
1192
                if (preg_match('{^@([-a-zA-Z0-9_:]++)(\s|$)}', $line, $m)) {
1193
                    $tagName = $m[1];
1194
                    $tagContent = str_replace("\t", ' ', ltrim(substr($line, 2 + \strlen($tagName))));
1195
                } else {
1196
                    $tagName = '';
1197
                }
1198
            } elseif ('' !== $tagName) {
1199
                $tagContent .= ' '.str_replace("\t", ' ', $line);
1200
            }
1201
        }
1202
 
1203
        if ('' !== $tagName) {
1204
            $tags[$tagName][] = $tagContent;
1205
        }
1206
 
1207
        foreach ($tags['method'] ?? [] as $i => $method) {
1208
            unset($tags['method'][$i]);
1209
 
1210
            $parts = preg_split('{(\s++|\((?:[^()]*+|(?R))*\)(?: *: *[^ ]++)?|<(?:[^<>]*+|(?R))*>|\{(?:[^{}]*+|(?R))*\})}', $method, -1, \PREG_SPLIT_DELIM_CAPTURE);
1211
            $returnType = '';
1212
            $static = 'static' === $parts[0];
1213
 
1214
            for ($i = $static ? 2 : 0; null !== $p = $parts[$i] ?? null; $i += 2) {
1215
                if (\in_array($p, ['', '|', '&', 'callable'], true) || \in_array(substr($returnType, -1), ['|', '&'], true)) {
1216
                    $returnType .= trim($parts[$i - 1] ?? '').$p;
1217
                    continue;
1218
                }
1219
 
1220
                $signature = '(' === ($parts[$i + 1][0] ?? '(') ? $parts[$i + 1] ?? '()' : null;
1221
 
1222
                if (null === $signature && '' === $returnType) {
1223
                    $returnType = $p;
1224
                    continue;
1225
                }
1226
 
1227
                if ($static && 2 === $i) {
1228
                    $static = false;
1229
                    $returnType = 'static';
1230
                }
1231
 
1232
                if (\in_array($description = trim(implode('', \array_slice($parts, 2 + $i))), ['', '.'], true)) {
1233
                    $description = null;
1234
                } elseif (!preg_match('/[.!]$/', $description)) {
1235
                    $description .= '.';
1236
                }
1237
 
1238
                $tags['method'][$p] = [$static, $returnType, $signature ?? '()', $description];
1239
                break;
1240
            }
1241
        }
1242
 
1243
        foreach ($tags['param'] ?? [] as $i => $param) {
1244
            unset($tags['param'][$i]);
1245
 
1246
            if (\strlen($param) !== strcspn($param, '<{(')) {
1247
                $param = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $param);
1248
            }
1249
 
1250
            if (false === $i = strpos($param, '$')) {
1251
                continue;
1252
            }
1253
 
1254
            $type = 0 === $i ? '' : rtrim(substr($param, 0, $i), ' &');
1255
            $param = substr($param, 1 + $i, (strpos($param, ' ', $i) ?: (1 + $i + \strlen($param))) - $i - 1);
1256
 
1257
            $tags['param'][$param] = $type;
1258
        }
1259
 
1260
        foreach (['var', 'return'] as $k) {
1261
            if (null === $v = $tags[$k][0] ?? null) {
1262
                continue;
1263
            }
1264
            if (\strlen($v) !== strcspn($v, '<{(')) {
1265
                $v = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $v);
1266
            }
1267
 
1268
            $tags[$k] = substr($v, 0, strpos($v, ' ') ?: \strlen($v)) ?: null;
1269
        }
1270
 
1271
        return $tags;
1272
    }
1273
}