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 assert;
15: use function file_get_contents;
16:
17: /**
18: * This source locator loads an entire file, specified in the constructor
19: * argument.
20: *
21: * This is useful for loading a class that does not have a namespace. This is
22: * also the class required if you want to use Reflector->getClassesFromFile
23: * (which loads all classes from specified file)
24: */
25: class SingleFileSourceLocator extends AbstractSourceLocator
26: {
27: /**
28: * @var non-empty-string
29: */
30: private string $fileName;
31: /**
32: * @param non-empty-string $fileName
33: *
34: * @throws InvalidFileLocation
35: */
36: public function __construct(string $fileName, Locator $astLocator)
37: {
38: $this->fileName = $fileName;
39: FileChecker::assertReadableFile($fileName);
40:
41: parent::__construct($astLocator);
42: }
43:
44: /**
45: * {@inheritDoc}
46: *
47: * @throws InvalidArgumentException
48: * @throws InvalidFileLocation
49: */
50: protected function createLocatedSource(Identifier $identifier): ?\PHPStan\BetterReflection\SourceLocator\Located\LocatedSource
51: {
52: $fileContents = file_get_contents($this->fileName);
53: assert($fileContents !== false);
54:
55: return new LocatedSource(
56: $fileContents,
57: $identifier->getName(),
58: $this->fileName,
59: );
60: }
61: }
62: