1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace PHPStan\BetterReflection\SourceLocator\Type;
6:
7: use PHPStan\BetterReflection\Identifier\Identifier;
8: use PHPStan\BetterReflection\Identifier\IdentifierType;
9: use PHPStan\BetterReflection\Reflection\Reflection;
10: use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
11: use PHPStan\BetterReflection\Reflector\Reflector;
12: use PHPStan\BetterReflection\SourceLocator\Ast\Exception\ParseToAstFailure;
13: use PHPStan\BetterReflection\SourceLocator\Ast\Locator as AstLocator;
14: use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
15:
16: abstract class AbstractSourceLocator implements SourceLocator
17: {
18: private AstLocator $astLocator;
19: /**
20: * Children should implement this method and return a LocatedSource object
21: * which contains the source and the file from which it was located.
22: *
23: * @example
24: * return new LocatedSource(['<?php class Foo {}', null]);
25: * return new LocatedSource([\file_get_contents('Foo.php'), 'Foo.php']);
26: */
27: abstract protected function createLocatedSource(Identifier $identifier): ?\PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
28:
29: public function __construct(AstLocator $astLocator)
30: {
31: $this->astLocator = $astLocator;
32: }
33:
34: /**
35: * {@inheritDoc}
36: *
37: * @throws ParseToAstFailure
38: */
39: public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?\PHPStan\BetterReflection\Reflection\Reflection
40: {
41: $locatedSource = $this->createLocatedSource($identifier);
42:
43: if (! $locatedSource) {
44: return null;
45: }
46:
47: try {
48: return $this->astLocator->findReflection($reflector, $locatedSource, $identifier);
49: } catch (IdentifierNotFound $exception) {
50: return null;
51: }
52: }
53:
54: /**
55: * {@inheritDoc}
56: *
57: * @throws ParseToAstFailure
58: */
59: final public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array
60: {
61: $locatedSource = $this->createLocatedSource(new Identifier(Identifier::WILDCARD, $identifierType));
62:
63: if (! $locatedSource) {
64: return [];
65: }
66:
67: return $this->astLocator->findReflectionsOfType(
68: $reflector,
69: $locatedSource,
70: $identifierType,
71: );
72: }
73: }
74: