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