forked from thecodingmachine/graphqlite-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphQLiteCompilerPass.php
More file actions
498 lines (421 loc) · 21.5 KB
/
Copy pathGraphQLiteCompilerPass.php
File metadata and controls
498 lines (421 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<?php
namespace TheCodingMachine\GraphQLite\Bundle\DependencyInjection;
use Generator;
use GraphQL\Server\ServerConfig;
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use Kcs\ClassFinder\Finder\ComposerFinder;
use Psr\SimpleCache\CacheInterface;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
use Symfony\Component\Cache\Psr16Cache;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use TheCodingMachine\CacheUtils\ClassBoundCache;
use TheCodingMachine\CacheUtils\ClassBoundCacheContract;
use TheCodingMachine\CacheUtils\ClassBoundCacheContractInterface;
use TheCodingMachine\CacheUtils\ClassBoundMemoryAdapter;
use TheCodingMachine\CacheUtils\FileBoundCache;
use TheCodingMachine\GraphQLite\AggregateControllerQueryProviderFactory;
use TheCodingMachine\GraphQLite\AnnotationReader;
use TheCodingMachine\GraphQLite\Annotations\Autowire;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Mutation;
use TheCodingMachine\GraphQLite\Annotations\Query;
use TheCodingMachine\GraphQLite\Bundle\Controller\GraphQL\LoginController;
use TheCodingMachine\GraphQLite\Bundle\Controller\GraphQL\MeController;
use TheCodingMachine\GraphQLite\Bundle\Types\SymfonyUserInterfaceType;
use TheCodingMachine\GraphQLite\GraphQLRuntimeException as GraphQLException;
use TheCodingMachine\GraphQLite\Mappers\StaticClassListTypeMapperFactory;
use TheCodingMachine\GraphQLite\Mappers\StaticTypeMapper;
use TheCodingMachine\GraphQLite\SchemaFactory;
use Webmozart\Assert\Assert;
use function assert;
use function class_exists;
use function filter_var;
use function ini_get;
use function interface_exists;
/**
* Detects controllers and types automatically and tag them.
*/
class GraphQLiteCompilerPass implements CompilerPassInterface
{
private ?AnnotationReader $annotationReader = null;
private string $cacheDir;
private ?CacheInterface $cache = null;
private ?ClassBoundCacheContractInterface $codeCache = null;
/**
* You can modify the container here before it is dumped to PHP code.
*/
public function process(ContainerBuilder $container): void
{
$reader = $this->getAnnotationReader();
$cacheDir = $container->getParameter('kernel.cache_dir');
assert(is_string($cacheDir));
$this->cacheDir = $cacheDir;
//$inputTypeUtils = new InputTypeUtils($reader, $namingStrategy);
// Let's scan the whole container and tag the services that belong to the namespace we want to inspect.
$controllersNamespaces = $container->getParameter('graphqlite.namespace.controllers');
$typesNamespaces = $container->getParameter('graphqlite.namespace.types');
assert(is_iterable($controllersNamespaces));
assert(is_iterable($typesNamespaces));
$firewallName = $container->getParameter('graphqlite.security.firewall_name');
assert(is_string($firewallName));
$firewallConfigServiceName = 'security.firewall.map.config.'.$firewallName;
// 2 seconds of TTL in environment mode. Otherwise, let's cache forever!
$schemaFactory = $container->getDefinition(SchemaFactory::class);
$env = $container->getParameter('kernel.environment');
if ($env === 'prod') {
$schemaFactory->addMethodCall('prodMode');
} elseif ($env === 'dev') {
$schemaFactory->addMethodCall('devMode');
}
$disableLogin = false;
if ($container->getParameter('graphqlite.security.enable_login') === 'auto'
&& (!$container->has($firewallConfigServiceName) ||
!$container->has(UserPasswordHasherInterface::class) ||
!$container->has(TokenStorageInterface::class) ||
!$container->has('session.factory')
)) {
$disableLogin = true;
}
if ($container->getParameter('graphqlite.security.enable_login') === 'off') {
$disableLogin = true;
}
// If the security is disabled, let's remove the LoginController
if ($disableLogin === true) {
$container->removeDefinition(LoginController::class);
}
if ($container->getParameter('graphqlite.security.enable_login') === 'on') {
if (!$container->has('session.factory')) {
throw new GraphQLException('In order to enable the login/logout mutations (via the graphqlite.security.enable_login parameter), you need to enable session support (via the "framework.session.enabled" config parameter).');
}
if (!$container->has(UserPasswordHasherInterface::class) || !$container->has(TokenStorageInterface::class) || !$container->has($firewallConfigServiceName)) {
throw new GraphQLException('In order to enable the login/logout mutations (via the graphqlite.security.enable_login parameter), you need to install the security bundle. Please be sure to correctly configure the user provider (in the security.providers configuration settings)');
}
}
if ($disableLogin === false) {
// Let's do some dark magic. We need the user provider. We need its name. It is stored in the "config" object.
$providerConfigKey = 'security.firewall.map.config.'.$firewallName;
$provider = $container->findDefinition($providerConfigKey)->getArgument(5);
if (!is_string($provider)){
throw new GraphQLException('Expecting to find user provider name from ' . $providerConfigKey);
}
$container->findDefinition(LoginController::class)->setArgument(0, new Reference($provider));
$this->registerController(LoginController::class, $container);
}
$disableMe = false;
if ($container->getParameter('graphqlite.security.enable_me') === 'auto'
&& !$container->has(TokenStorageInterface::class)) {
$disableMe = true;
}
if ($container->getParameter('graphqlite.security.enable_me') === 'off') {
$disableMe = true;
}
// If the security is disabled, let's remove the LoginController
if ($disableMe === true) {
$container->removeDefinition(MeController::class);
}
if ($container->getParameter('graphqlite.security.enable_me') === 'on') {
if (!$container->has(TokenStorageInterface::class)) {
throw new GraphQLException('In order to enable the "me" query (via the graphqlite.security.enable_me parameter), you need to install the security bundle.');
}
}
// ServerConfig rules
$serverConfigDefinition = $container->findDefinition(ServerConfig::class);
$rulesDefinition = [];
if ($container->getParameter('graphqlite.security.disableIntrospection')) {
$rulesDefinition[] = $container->findDefinition(DisableIntrospection::class);
}
$complexity = $container->getParameter('graphqlite.security.maximum_query_complexity');
if ($complexity) {
Assert::integerish($complexity);
$rulesDefinition[] = $container->findDefinition(QueryComplexity::class)
->setArgument(0, (int) $complexity);
}
$depth = $container->getParameter('graphqlite.security.maximum_query_depth');
if ($depth) {
Assert::integerish($depth);
$rulesDefinition[] = $container->findDefinition(QueryDepth::class)
->setArgument(0, (int) $depth);
}
$serverConfigDefinition->addMethodCall('setValidationRules', [$rulesDefinition]);
if ($disableMe === false) {
$this->registerController(MeController::class, $container);
}
// Perf improvement: let's remove the AggregateControllerQueryProviderFactory if it is empty.
if (empty($container->findDefinition(AggregateControllerQueryProviderFactory::class)->getArgument(0))) {
$container->removeDefinition(AggregateControllerQueryProviderFactory::class);
}
// Let's register the mapping with UserInterface if UserInterface is available.
if (interface_exists(UserInterface::class)) {
$staticTypes = $container->getDefinition(StaticClassListTypeMapperFactory::class)->getArgument(0);
if (!is_array($staticTypes)){
throw new GraphQLException(sprintf('Expecting array in %s, arg #1', StaticClassListTypeMapperFactory::class));
}
$staticTypes[] = SymfonyUserInterfaceType::class;
$container->getDefinition(StaticClassListTypeMapperFactory::class)->setArgument(0, $staticTypes);
}
foreach ($container->getDefinitions() as $definition) {
if ($definition->isAbstract() || $definition->getClass() === null) {
continue;
}
/** @var class-string $class */
$class = $definition->getClass();
foreach ($typesNamespaces as $typesNamespace) {
\assert(\is_string($typesNamespace));
if (false === str_starts_with($class, $typesNamespace)) {
continue;
}
// Set the types public
$reflectionClass = new ReflectionClass($class);
$typeAnnotation = $this->getAnnotationReader()->getTypeAnnotation($reflectionClass);
if ($typeAnnotation !== null && $typeAnnotation->isSelfType()) {
continue;
}
if ($typeAnnotation !== null || $this->getAnnotationReader()->getExtendTypeAnnotation($reflectionClass) !== null) {
$definition->setPublic(true);
}
foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$factory = $reader->getFactoryAnnotation($method);
if ($factory !== null) {
$definition->setPublic(true);
}
}
}
}
foreach ($controllersNamespaces as $controllersNamespace) {
\assert(\is_string($controllersNamespace));
$schemaFactory->addMethodCall('addNamespace', [ $controllersNamespace ]);
foreach ($this->getClassList($controllersNamespace) as $refClass) {
$this->makePublicInjectedServices($refClass, $reader, $container, true);
}
}
foreach ($typesNamespaces as $typeNamespace) {
\assert(\is_string($typeNamespace));
$schemaFactory->addMethodCall('addNamespace', [ $typeNamespace ]);
foreach ($this->getClassList($typeNamespace) as $refClass) {
$this->makePublicInjectedServices($refClass, $reader, $container, false);
}
}
// Register custom output types
$taggedServices = $container->findTaggedServiceIds('graphql.output_type');
$customTypes = [];
$customNotMappedTypes = [];
foreach ($taggedServices as $id => $tags) {
foreach ($tags as $attributes) {
\assert(\is_array($attributes));
if (isset($attributes['class']) && is_string($attributes['class'])) {
$phpClass = $attributes['class'];
if (false === class_exists($phpClass)) {
throw new \RuntimeException(sprintf('The class attribute of the graphql.output_type annotation of the %s service must point to an existing PHP class. Value passed: %s', $id, $phpClass));
}
$customTypes[$phpClass] = new Reference($id);
} else {
$customNotMappedTypes[] = new Reference($id);
}
}
}
$staticMapperDefinition = new Definition(StaticTypeMapper::class, [
'$types' => $customTypes,
'$notMappedTypes' => $customNotMappedTypes
]);
$staticMapperDefinition->addTag('graphql.type_mapper');
$container->setDefinition(StaticTypeMapper::class, $staticMapperDefinition);
// Register graphql.queryprovider
$this->mapAdderToTag('graphql.queryprovider', 'addQueryProvider', $container, $schemaFactory);
$this->mapAdderToTag('graphql.queryprovider_factory', 'addQueryProviderFactory', $container, $schemaFactory);
$this->mapAdderToTag('graphql.root_type_mapper_factory', 'addRootTypeMapperFactory', $container, $schemaFactory);
$this->mapAdderToTag('graphql.parameter_middleware', 'addParameterMiddleware', $container, $schemaFactory);
$this->mapAdderToTag('graphql.field_middleware', 'addFieldMiddleware', $container, $schemaFactory);
$this->mapAdderToTag('graphql.type_mapper', 'addTypeMapper', $container, $schemaFactory);
$this->mapAdderToTag('graphql.type_mapper_factory', 'addTypeMapperFactory', $container, $schemaFactory);
// Configure cache
if (ApcuAdapter::isSupported() && (PHP_SAPI !== 'cli' || filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN))) {
$container->setAlias('graphqlite.cache', 'graphqlite.apcucache');
} else {
$container->setAlias('graphqlite.cache', 'graphqlite.phpfilescache');
}
}
private function registerController(string $controllerClassName, ContainerBuilder $container): void
{
$aggregateQueryProvider = $container->findDefinition(AggregateControllerQueryProviderFactory::class);
$controllersList = $aggregateQueryProvider->getArgument(0);
if (!is_array($controllersList)){
throw new GraphQLException(sprintf('Expecting array in %s, arg #1', AggregateControllerQueryProviderFactory::class));
}
$controllersList[] = $controllerClassName;
$aggregateQueryProvider->setArgument(0, $controllersList);
$serviceLocatorMap = [];
foreach ($controllersList as $controller) {
\assert(\is_string($controller));
$serviceLocatorMap[$controller] = new Reference($controller);
}
$aggregateQueryProvider->setArgument(1, new ServiceLocatorArgument($serviceLocatorMap));
}
/**
* Register a method call on SchemaFactory for each tagged service, passing the service in parameter.
*/
private function mapAdderToTag(string $tag, string $methodName, ContainerBuilder $container, Definition $schemaFactory): void
{
$taggedServices = $container->findTaggedServiceIds($tag);
foreach ($taggedServices as $id => $tags) {
$schemaFactory->addMethodCall($methodName, [new Reference($id)]);
}
}
/**
* @param ReflectionClass<object> $refClass
*/
private function makePublicInjectedServices(ReflectionClass $refClass, AnnotationReader $reader, ContainerBuilder $container, bool $isController): void
{
$services = $this->getCodeCache()->get($refClass, function() use ($refClass, $reader, $container, $isController): array {
$services = [];
foreach ($refClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$resolveResult = $this->resolveFieldGraphqlElement($reader, $method);
if ($resolveResult['exists']) {
if ($isController) {
$services[$refClass->getName()] = $refClass->getName();
}
$services += $this->getListOfInjectedServices($method, $container);
$field = $resolveResult['field'];
if (null !== $field && $field->getPrefetchMethod() !== null) {
$services += $this->getListOfInjectedServices($refClass->getMethod($field->getPrefetchMethod()), $container);
}
}
}
return $services;
});
if (!is_array($services)){
throw new GraphQLException('An error occurred in compiler pass');
}
foreach ($services as $service) {
if (!is_string($service)){
throw new GraphQLException('expecting string as service');
}
if ($container->hasAlias($service)) {
$container->getAlias($service)->setPublic(true);
} else {
$container->getDefinition($service)->setPublic(true);
}
}
}
/**
* @return array<string, string> key = value = service name
*/
private function getListOfInjectedServices(ReflectionMethod $method, ContainerBuilder $container): array
{
/** @var array<string, string> $services */
$services = [];
$parametersByName = null;
$annotations = $this->getAnnotationReader()->getParameterAnnotationsPerParameter($method->getParameters());
foreach ($annotations as $parameterName => $parameterAnnotations) {
$parameterAutowireAnnotation = $parameterAnnotations->getAnnotationsByType(Autowire::class);
foreach ($parameterAutowireAnnotation as $autowire) {
$id = $autowire->getIdentifier();
if ($id !== null) {
$services[$id] = $id;
continue;
}
$parametersByName ??= self::getParametersByName($method);
if (!isset($parametersByName[$parameterName])) {
throw new \LogicException('Should not happen');
}
$parameter = $parametersByName[$parameterName];
$type = $parameter->getType();
if ($type instanceof ReflectionNamedType) {
$fqcn = $type->getName();
if ($container->has($fqcn)) {
$services[$fqcn] = $fqcn;
}
}
}
}
return $services;
}
/**
* @return array<string, ReflectionParameter>
*/
private static function getParametersByName(ReflectionMethod $method): array
{
$parameters = [];
foreach ($method->getParameters() as $parameter) {
$parameters[$parameter->getName()] = $parameter;
}
return $parameters;
}
/**
* Returns a GraphQLite annotation reader.
* Note: we cannot get the annotation reader service in the container as we are in a compiler pass.
*/
private function getAnnotationReader(): AnnotationReader
{
return $this->annotationReader ??= new AnnotationReader();
}
private function getPsr16Cache(): CacheInterface
{
if ($this->cache === null) {
if (ApcuAdapter::isSupported()) {
$this->cache = new Psr16Cache(new ApcuAdapter('graphqlite_bundle'));
} else {
$this->cache = new Psr16Cache(new PhpFilesAdapter('graphqlite_bundle', 0, $this->cacheDir));
}
}
return $this->cache;
}
private function getCodeCache(): ClassBoundCacheContractInterface
{
return $this->codeCache ??= new ClassBoundCacheContract(
new ClassBoundMemoryAdapter(new ClassBoundCache(new FileBoundCache($this->getPsr16Cache())))
);
}
/**
* Returns the array of globbed classes.
* Only instantiable classes are returned.
*
* @return Generator<class-string, ReflectionClass<object>, void, void>
*/
private function getClassList(string $namespace): Generator
{
// dev note: this code will be broken if there's a broken class (which has mismatch in real namespace
// with PSR-4 configuration) in the configured namespace
// see also: https://github.com/alekitto/class-finder/issues/24#issuecomment-2480847327
$finder = new ComposerFinder();
foreach ($finder->inNamespace($namespace) as $class) {
assert($class instanceof ReflectionClass);
yield $class->getName() => $class;
}
}
/**
* @return array{exists: bool, field: Field|null}
*/
private function resolveFieldGraphqlElement(AnnotationReader $reader, ReflectionMethod $method): array
{
// backward compatibility with graphqlite v8.1
// @phpstan-ignore function.alreadyNarrowedType
if (false === \method_exists($reader, 'getGraphQLElementAnnotation')) {
// graphqlite versions in this BC branch expose getRequestAnnotation instead.
// @phpstan-ignore method.notFound
$element = $reader->getRequestAnnotation($method, Field::class)
// @phpstan-ignore method.notFound
?? $reader->getRequestAnnotation($method, Query::class)
// @phpstan-ignore method.notFound
?? $reader->getRequestAnnotation($method, Mutation::class);
return ['exists' => null !== $element, 'field' => ($element instanceof Field ? $element : null)];
}
$element = $reader->getGraphQLElementAnnotation($method, Field::class)
?? $reader->getGraphQLElementAnnotation($method, Query::class)
?? $reader->getGraphQLElementAnnotation($method, Mutation::class);
return ['exists' => null !== $element, 'field' => ($element instanceof Field ? $element : null)];
}
}