1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\DependencyInjection;
4:
5: use Nette\Bootstrap\Extensions\PhpExtension;
6: use Nette\DI\Config\Adapters\PhpAdapter;
7: use Nette\DI\Definitions\Statement;
8: use Nette\DI\Helpers;
9: use Nette\Schema\Context as SchemaContext;
10: use Nette\Schema\Elements\AnyOf;
11: use Nette\Schema\Elements\Structure;
12: use Nette\Schema\Elements\Type;
13: use Nette\Schema\Expect;
14: use Nette\Schema\Processor;
15: use Nette\Schema\Schema;
16: use Nette\Utils\Strings;
17: use Nette\Utils\Validators;
18: use Phar;
19: use PhpParser\Parser;
20: use PHPStan\Analyser\ExprHandlerRegistry;
21: use PHPStan\Analyser\StmtHandlerRegistry;
22: use PHPStan\BetterReflection\BetterReflection;
23: use PHPStan\BetterReflection\Reflector\Reflector;
24: use PHPStan\BetterReflection\SourceLocator\SourceStubber\PhpStormStubsSourceStubber;
25: use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
26: use PHPStan\Command\CommandHelper;
27: use PHPStan\Command\Environment;
28: use PHPStan\DependencyInjection\AttributeServices\AttributeServicesDirectoriesResolver;
29: use PHPStan\DependencyInjection\AttributeServices\AttributeServicesDiscoveryContext;
30: use PHPStan\File\FileHelper;
31: use PHPStan\Node\Printer\Printer;
32: use PHPStan\Php\PhpVersion;
33: use PHPStan\Reflection\PhpVersionStaticAccessor;
34: use PHPStan\Reflection\ReflectionProvider;
35: use PHPStan\Reflection\ReflectionProviderStaticAccessor;
36: use PHPStan\ShouldNotHappenException;
37: use PHPStan\Type\ObjectType;
38: use PHPStan\Type\TypeCombinator;
39: use WeakReference;
40: use function array_diff_key;
41: use function array_intersect;
42: use function array_key_exists;
43: use function array_keys;
44: use function array_map;
45: use function array_merge;
46: use function array_slice;
47: use function array_unique;
48: use function count;
49: use function dirname;
50: use function extension_loaded;
51: use function implode;
52: use function ini_get;
53: use function is_array;
54: use function is_file;
55: use function is_readable;
56: use function is_string;
57: use function sprintf;
58: use function str_ends_with;
59: use function substr;
60:
61: /**
62: * @api
63: */
64: final class ContainerFactory
65: {
66:
67: private FileHelper $fileHelper;
68:
69: private string $rootDirectory;
70:
71: private string $configDirectory;
72:
73: /** @var WeakReference<Container>|null */
74: private static ?WeakReference $lastInitializedContainer = null;
75:
76: private bool $journalContainer = false;
77:
78: /** @api */
79: public function __construct(private string $currentWorkingDirectory)
80: {
81: $this->fileHelper = new FileHelper($currentWorkingDirectory);
82:
83: $rootDir = __DIR__ . '/../..';
84: $originalRootDir = $this->fileHelper->normalizePath($rootDir);
85: if (extension_loaded('phar')) {
86: $pharPath = Phar::running(false);
87: if ($pharPath !== '') {
88: $rootDir = dirname($pharPath);
89: }
90: }
91: $this->rootDirectory = $this->fileHelper->normalizePath($rootDir);
92: $this->configDirectory = $originalRootDir . '/conf';
93: }
94:
95: public function setJournalContainer(): void
96: {
97: $this->journalContainer = true;
98: }
99:
100: /**
101: * @param string[] $additionalConfigFiles
102: * @param string[] $analysedPaths
103: * @param string[] $composerAutoloaderProjectPaths
104: * @param string[] $analysedPathsFromConfig
105: * @param array<mixed> $additionalParameters
106: */
107: public function create(
108: string $tempDirectory,
109: array $additionalConfigFiles,
110: array $analysedPaths,
111: array $composerAutoloaderProjectPaths = [],
112: array $analysedPathsFromConfig = [],
113: string $usedLevel = CommandHelper::DEFAULT_LEVEL,
114: ?string $generateBaselineFile = null,
115: ?string $cliAutoloadFile = null,
116: ?string $singleReflectionFile = null,
117: ?string $singleReflectionInsteadOfFile = null,
118: array $additionalParameters = [],
119: ): Container
120: {
121: [$allConfigFiles, $projectConfig] = $this->detectDuplicateIncludedFiles(
122: array_merge([__DIR__ . '/../../conf/parametersSchema.neon'], $additionalConfigFiles),
123: [
124: 'rootDir' => $this->rootDirectory,
125: 'currentWorkingDirectory' => $this->currentWorkingDirectory,
126: 'env' => Environment::getCleanedArray(),
127: ],
128: );
129:
130: $directoriesResolver = new AttributeServicesDirectoriesResolver($this->fileHelper, $composerAutoloaderProjectPaths);
131: $attributeServicesDirectories = $directoriesResolver->resolve($projectConfig['attributeServicesDirectories'] ?? []);
132: AttributeServicesDiscoveryContext::set($attributeServicesDirectories);
133:
134: $configurator = new Configurator(new LoaderFactory(
135: $this->fileHelper,
136: $this->rootDirectory,
137: $this->currentWorkingDirectory,
138: $generateBaselineFile,
139: $projectConfig['expandRelativePaths'],
140: ), $this->journalContainer);
141: $configurator->defaultExtensions = [
142: 'php' => PhpExtension::class,
143: // registers everything marked with #[ContainerExtension] and handles `extensions:` sections
144: 'extensions' => ContainerExtensionsExtension::class,
145: ];
146: $configurator->setDebugMode(true);
147: $configurator->setTempDirectory($tempDirectory);
148: $configurator->addParameters(array_merge([
149: 'rootDir' => $this->rootDirectory,
150: 'currentWorkingDirectory' => $this->currentWorkingDirectory,
151: 'cliArgumentsVariablesRegistered' => ini_get('register_argc_argv') === '1',
152: 'tmpDir' => $tempDirectory,
153: 'additionalConfigFiles' => $additionalConfigFiles,
154: 'allConfigFiles' => $allConfigFiles,
155: 'composerAutoloaderProjectPaths' => $composerAutoloaderProjectPaths,
156: 'generateBaselineFile' => $generateBaselineFile,
157: 'usedLevel' => $usedLevel,
158: 'cliAutoloadFile' => $cliAutoloadFile,
159: 'attributeServicesDirectories' => $attributeServicesDirectories->getDirectoryPaths(),
160: // filled by AutowiredAttributeServicesExtension
161: 'attributeServicesClasses' => [],
162: 'env' => Environment::getCleanedArray(),
163: ], $additionalParameters));
164: $configurator->addDynamicParameters([
165: 'singleReflectionFile' => $singleReflectionFile,
166: 'singleReflectionInsteadOfFile' => $singleReflectionInsteadOfFile,
167: 'analysedPaths' => $analysedPaths,
168: 'analysedPathsFromConfig' => $analysedPathsFromConfig,
169: ]);
170: $configurator->addConfig($this->configDirectory . '/config.neon');
171: foreach ($additionalConfigFiles as $additionalConfigFile) {
172: $configurator->addConfig($additionalConfigFile);
173: }
174:
175: $configurator->setAllConfigFiles($allConfigFiles);
176: $configurator->setAttributeServicesDirectoriesCacheKey($attributeServicesDirectories->getCacheKeyComponent());
177:
178: $container = $configurator->createContainer()->getByType(Container::class);
179: $this->validateParameters($container->getParameters(), $projectConfig['parametersSchema']);
180: self::postInitializeContainer($container);
181:
182: return $container;
183: }
184:
185: /** @internal */
186: public static function postInitializeContainer(Container $container): void
187: {
188: // Comparing spl_object_id()s would be wrong: an id is recycled as soon as its
189: // container is freed, so a fresh container could inherit the last initialized
190: // one's id and silently skip installing its own global state.
191: $lastInitializedContainer = self::$lastInitializedContainer?->get();
192: if ($lastInitializedContainer === $container) {
193: return;
194: }
195:
196: self::$lastInitializedContainer = WeakReference::create($container);
197:
198: // Both registries memoize handler instances per container, keyed by the
199: // container's spl_object_id() - a recycled id would otherwise hand this
200: // container the freed one's handlers, which carry the other container's
201: // services and parameters.
202: ExprHandlerRegistry::clearCache();
203: StmtHandlerRegistry::clearCache();
204:
205: /** @var SourceLocator $sourceLocator */
206: $sourceLocator = $container->getService('betterReflectionSourceLocator');
207:
208: /** @var Reflector $reflector */
209: $reflector = $container->getService('betterReflectionReflector');
210:
211: /** @var Parser $phpParser */
212: $phpParser = $container->getService('phpParserDecorator');
213:
214: BetterReflection::populate(
215: $container->getByType(PhpVersion::class)->getVersionId(),
216: $sourceLocator,
217: $reflector,
218: $phpParser,
219: $container->getByType(PhpStormStubsSourceStubber::class),
220: $container->getByType(Printer::class),
221: );
222:
223: ReflectionProviderStaticAccessor::registerInstance($container->getByType(ReflectionProvider::class));
224: PhpVersionStaticAccessor::registerInstance($container->getByType(PhpVersion::class));
225: ObjectType::resetCaches();
226:
227: $container->getService('typeSpecifier');
228:
229: BleedingEdgeToggle::setBleedingEdge($container->getParameter('featureToggles')['bleedingEdge']);
230: ReportUnsafeArrayStringKeyCastingToggle::setLevel($container->getParameter('reportUnsafeArrayStringKeyCasting'));
231:
232: // Type operations read global state — the toggles above, the reflection provider,
233: // the PHP version — so a memoized result is only valid for the state it was computed
234: // under. Clearing must be the LAST step: building the typeSpecifier service runs
235: // extension constructors that can already perform type operations, and entries
236: // memoized before the toggles are set would encode the previous container's state.
237: TypeCombinator::clearCache();
238: }
239:
240: public function getCurrentWorkingDirectory(): string
241: {
242: return $this->currentWorkingDirectory;
243: }
244:
245: public function getRootDirectory(): string
246: {
247: return $this->rootDirectory;
248: }
249:
250: public function getConfigDirectory(): string
251: {
252: return $this->configDirectory;
253: }
254:
255: /**
256: * @param string[] $configFiles
257: * @param array<string, mixed> $loaderParameters
258: * @return array{list<string>, array<mixed>}
259: * @throws DuplicateIncludedFilesException
260: */
261: private function detectDuplicateIncludedFiles(
262: array $configFiles,
263: array $loaderParameters,
264: ): array
265: {
266: // attributeServicesDirectories must come out absolutized relative to the declaring file
267: // even in this pre-pass - ContainerFactory reads the section before the container compiles
268: $neonAdapter = new NeonCachedFileReader(['[attributeServicesDirectories][]']);
269: $phpAdapter = new PhpAdapter();
270: $allConfigFiles = [];
271: $configArray = [];
272: foreach ($configFiles as $configFile) {
273: [$tmpConfigFiles, $tmpConfigArray] = self::getConfigFiles($this->fileHelper, $neonAdapter, $phpAdapter, $configFile, $loaderParameters, null);
274: $allConfigFiles = array_merge($allConfigFiles, $tmpConfigFiles);
275:
276: /** @var array<mixed> $configArray */
277: $configArray = \Nette\Schema\Helpers::merge($tmpConfigArray, $configArray);
278: }
279:
280: $normalized = array_map(fn (string $file): string => $this->fileHelper->normalizePath($file), $allConfigFiles);
281:
282: $deduplicated = array_unique($normalized);
283: if (count($normalized) <= count($deduplicated)) {
284: return [$normalized, $configArray];
285: }
286:
287: $duplicateFiles = array_unique(array_diff_key($normalized, $deduplicated));
288:
289: throw new DuplicateIncludedFilesException($duplicateFiles);
290: }
291:
292: /**
293: * @param array<string, string> $loaderParameters
294: * @return array{list<string>, array<mixed>}
295: */
296: private static function getConfigFiles(
297: FileHelper $fileHelper,
298: NeonCachedFileReader $neonAdapter,
299: PhpAdapter $phpAdapter,
300: string $configFile,
301: array $loaderParameters,
302: ?string $generateBaselineFile,
303: ): array
304: {
305: if ($generateBaselineFile === $fileHelper->normalizePath($configFile)) {
306: return [[], []];
307: }
308: if (!is_file($configFile) || !is_readable($configFile)) {
309: return [[], []];
310: }
311:
312: if (str_ends_with($configFile, '.php')) {
313: $data = $phpAdapter->load($configFile);
314: } else {
315: $data = $neonAdapter->load($configFile);
316: }
317: $allConfigFiles = [$configFile];
318: if (isset($data['includes'])) {
319: Validators::assert($data['includes'], 'list', sprintf("section 'includes' in file '%s'", $configFile));
320: $includes = Helpers::expand($data['includes'], $loaderParameters);
321: foreach ($includes as $include) {
322: $include = self::expandIncludedFile($include, $configFile);
323: [$tmpConfigFiles, $tmpConfigArray] = self::getConfigFiles($fileHelper, $neonAdapter, $phpAdapter, $include, $loaderParameters, $generateBaselineFile);
324: $allConfigFiles = array_merge($allConfigFiles, $tmpConfigFiles);
325:
326: /** @var array<mixed> $data */
327: $data = \Nette\Schema\Helpers::merge($tmpConfigArray, $data);
328: }
329: }
330:
331: return [$allConfigFiles, $data];
332: }
333:
334: private static function expandIncludedFile(string $includedFile, string $mainFile): string
335: {
336: return Strings::match($includedFile, '#([a-z]+:)?[/\\\\]#Ai') !== null // is absolute
337: ? $includedFile
338: : dirname($mainFile) . '/' . $includedFile;
339: }
340:
341: /**
342: * @param array<mixed> $parameters
343: * @param array<mixed> $parametersSchema
344: */
345: private function validateParameters(array $parameters, array $parametersSchema): void
346: {
347: if (!(bool) $parameters['__validate']) {
348: return;
349: }
350:
351: $schema = $this->processArgument(
352: new Statement('schema', [
353: new Statement('structure', [$parametersSchema]),
354: ]),
355: );
356: $processor = new Processor();
357: $processor->onNewContext[] = static function (SchemaContext $context): void {
358: $context->path = ['parameters'];
359: };
360: $processor->process($schema, $parameters);
361:
362: if (
363: array_key_exists('phpVersion', $parameters)
364: && is_array($parameters['phpVersion'])
365: ) {
366: $phpVersion = $parameters['phpVersion'];
367:
368: if ($phpVersion['max'] < $phpVersion['min']) {
369: throw new InvalidPhpVersionException('Invalid PHP version range: phpVersion.max should be greater or equal to phpVersion.min.');
370: }
371: }
372:
373: foreach ($parameters['ignoreErrors'] ?? [] as $ignoreError) {
374: if (is_string($ignoreError)) {
375: continue;
376: }
377:
378: $atLeastOneOf = ['message', 'messages', 'rawMessage', 'rawMessages', 'identifier', 'identifiers', 'path', 'paths'];
379: if (array_intersect($atLeastOneOf, array_keys($ignoreError)) === []) {
380: throw new InvalidIgnoredErrorException('An ignoreErrors entry must contain at least one of the following fields: ' . implode(', ', $atLeastOneOf) . '.');
381: }
382:
383: foreach ([
384: ['rawMessage', 'rawMessages', 'message', 'messages'],
385: ['identifier', 'identifiers'],
386: ['path', 'paths'],
387: ] as $incompatibleFields) {
388: foreach ($incompatibleFields as $index => $field1) {
389: $fieldsToCheck = array_slice($incompatibleFields, $index + 1);
390: foreach ($fieldsToCheck as $field2) {
391: if (array_key_exists($field1, $ignoreError) && array_key_exists($field2, $ignoreError)) {
392: throw new InvalidIgnoredErrorException(sprintf('An ignoreErrors entry cannot contain both %s and %s fields.', $field1, $field2));
393: }
394: }
395: }
396: }
397:
398: if (array_key_exists('count', $ignoreError) && !array_key_exists('path', $ignoreError)) {
399: throw new InvalidIgnoredErrorException('An ignoreErrors entry with count field must also contain path field.');
400: }
401: }
402: }
403:
404: /**
405: * @param Statement[] $statements
406: */
407: private function processSchema(array $statements, bool $required = true): Schema
408: {
409: if (count($statements) === 0) {
410: throw new ShouldNotHappenException();
411: }
412:
413: $parameterSchema = null;
414: foreach ($statements as $statement) {
415: $processedArguments = array_map(fn ($argument) => $this->processArgument($argument), $statement->arguments);
416: $entity = $statement->getEntity();
417: if (!is_string($entity)) {
418: throw new ShouldNotHappenException();
419: }
420: if ($parameterSchema === null) {
421: /** @var Type|AnyOf|Structure $parameterSchema */
422: $parameterSchema = Expect::{$entity}(...$processedArguments);
423: } else {
424: $parameterSchema->{$entity}(...$processedArguments);
425: }
426: }
427:
428: if ($required) {
429: $parameterSchema->required();
430: }
431:
432: return $parameterSchema;
433: }
434:
435: /**
436: * @param mixed $argument
437: * @return mixed
438: */
439: private function processArgument($argument, bool $required = true)
440: {
441: if ($argument instanceof Statement) {
442: if ($argument->entity === 'schema') {
443: $arguments = [];
444: foreach ($argument->arguments as $schemaArgument) {
445: if (!$schemaArgument instanceof Statement) {
446: throw new ShouldNotHappenException('schema() should contain another statement().');
447: }
448:
449: $arguments[] = $schemaArgument;
450: }
451:
452: if (count($arguments) === 0) {
453: throw new ShouldNotHappenException('schema() should have at least one argument.');
454: }
455:
456: return $this->processSchema($arguments, $required);
457: }
458:
459: return $this->processSchema([$argument], $required);
460: } elseif (is_array($argument)) {
461: $processedArray = [];
462: foreach ($argument as $key => $val) {
463: $required = $key[0] !== '?';
464: $key = $required ? $key : substr($key, 1);
465: $processedArray[$key] = $this->processArgument($val, $required);
466: }
467:
468: return $processedArray;
469: }
470:
471: return $argument;
472: }
473:
474: }
475: