1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace PHPStan\BetterReflection\SourceLocator\Type;
6:
7: use InvalidArgumentException;
8: use PHPStan\BetterReflection\Identifier\Identifier;
9: use PHPStan\BetterReflection\SourceLocator\Ast\Locator;
10: use PHPStan\BetterReflection\SourceLocator\Exception\InvalidFileLocation;
11: use PHPStan\BetterReflection\SourceLocator\FileChecker;
12: use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
13:
14: use function file_get_contents;
15:
16: /**
17: * This source locator loads an entire file, specified in the constructor
18: * argument.
19: *
20: * This is useful for loading a class that does not have a namespace. This is
21: * also the class required if you want to use Reflector->getClassesFromFile
22: * (which loads all classes from specified file)
23: */
24: class SingleFileSourceLocator extends AbstractSourceLocator
25: {
26: /**
27: * @var non-empty-string
28: */
29: private $fileName;
30: /**
31: * @param non-empty-string $fileName
32: *
33: * @throws InvalidFileLocation
34: */
35: public function __construct(string $fileName, Locator $astLocator)
36: {
37: $this->fileName = $fileName;
38: FileChecker::assertReadableFile($fileName);
39:
40: parent::__construct($astLocator);
41: }
42:
43: /**
44: * {@inheritDoc}
45: *
46: * @throws InvalidArgumentException
47: * @throws InvalidFileLocation
48: */
49: protected function createLocatedSource(Identifier $identifier): ?\PHPStan\BetterReflection\SourceLocator\Located\LocatedSource
50: {
51: return new LocatedSource(file_get_contents($this->fileName), $identifier->getName(), $this->fileName);
52: }
53: }
54: