-
Notifications
You must be signed in to change notification settings - Fork 37
/
GraphqliteCompilerPass.php
504 lines (447 loc) · 22.2 KB
/
GraphqliteCompilerPass.php
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
499
500
501
502
503
504
<?php
namespace TheCodingMachine\Graphqlite\Bundle\DependencyInjection;
use GraphQL\Server\ServerConfig;
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use ReflectionNamedType;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\PhpFilesAdapter;
use Symfony\Component\Cache\Psr16Cache;
use TheCodingMachine\GraphQLite\Mappers\StaticClassListTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\StaticClassListTypeMapperFactory;
use function class_exists;
use Doctrine\Common\Annotations\AnnotationException;
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Cache\ApcuCache;
use function error_log;
use Mouf\Composer\ClassNameMapper;
use Psr\SimpleCache\CacheInterface;
use ReflectionParameter;
use Symfony\Component\Cache\Simple\ApcuCache as SymfonyApcuCache;
use Symfony\Component\Cache\Simple\PhpFilesCache as SymfonyPhpFilesCache;
use function filter_var;
use function function_exists;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\ObjectType;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionMethod;
use function ini_get;
use function interface_exists;
use function php_sapi_name;
use function str_replace;
use function strpos;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use TheCodingMachine\CacheUtils\ClassBoundCache;
use TheCodingMachine\CacheUtils\ClassBoundCacheContract;
use TheCodingMachine\CacheUtils\ClassBoundCacheContractInterface;
use TheCodingMachine\CacheUtils\ClassBoundMemoryAdapter;
use TheCodingMachine\CacheUtils\FileBoundCache;
use TheCodingMachine\ClassExplorer\Glob\GlobClassExplorer;
use TheCodingMachine\GraphQLite\AggregateControllerQueryProviderFactory;
use TheCodingMachine\GraphQLite\AnnotationReader;
use TheCodingMachine\GraphQLite\Annotations\AbstractRequest;
use TheCodingMachine\GraphQLite\Annotations\Autowire;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Mutation;
use TheCodingMachine\GraphQLite\Annotations\Parameter;
use TheCodingMachine\GraphQLite\Annotations\Query;
use TheCodingMachine\Graphqlite\Bundle\Controller\GraphQL\LoginController;
use TheCodingMachine\Graphqlite\Bundle\Controller\GraphQL\MeController;
use TheCodingMachine\GraphQLite\FieldsBuilder;
use TheCodingMachine\GraphQLite\FieldsBuilderFactory;
use TheCodingMachine\GraphQLite\GraphQLRuntimeException as GraphQLException;
use TheCodingMachine\GraphQLite\InputTypeGenerator;
use TheCodingMachine\GraphQLite\InputTypeUtils;
use TheCodingMachine\GraphQLite\Mappers\CompositeTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\GlobTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\RecursiveTypeMapperInterface;
use TheCodingMachine\GraphQLite\Mappers\Root\CompositeRootTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\StaticTypeMapper;
use TheCodingMachine\GraphQLite\NamingStrategy;
use TheCodingMachine\GraphQLite\SchemaFactory;
use TheCodingMachine\GraphQLite\TypeGenerator;
use TheCodingMachine\GraphQLite\Types\MutableObjectType;
use TheCodingMachine\GraphQLite\Types\ResolvableInputObjectType;
use function var_dump;
use TheCodingMachine\Graphqlite\Bundle\Types\SymfonyUserInterfaceType;
/**
* Detects controllers and types automatically and tag them.
*/
class GraphqliteCompilerPass implements CompilerPassInterface
{
/**
* @var AnnotationReader
*/
private $annotationReader;
/**
* @var string
*/
private $cacheDir;
/**
* You can modify the container here before it is dumped to PHP code.
*/
public function process(ContainerBuilder $container): void
{
$reader = $this->getAnnotationReader();
$this->cacheDir = $container->getParameter('kernel.cache_dir');
//$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');
$firewallName = $container->getParameter('graphqlite.security.firewall_name');
$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(UserPasswordEncoderInterface::class) ||
!$container->has(TokenStorageInterface::class) ||
!$container->has(SessionInterface::class)
)) {
$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(SessionInterface::class)) {
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(UserPasswordEncoderInterface::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.
$provider = $container->findDefinition('security.firewall.map.config.'.$firewallName)->getArgument(5);
$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.introspection') === false) {
$rulesDefinition[] = $container->findDefinition(DisableIntrospection::class);
}
if ($container->getParameter('graphqlite.security.maximum_query_complexity')) {
$complexity = (int) $container->getParameter('graphqlite.security.maximum_query_complexity');
$rulesDefinition[] = $container->findDefinition(QueryComplexity::class)->setArgument(0, $complexity);
}
if ($container->getParameter('graphqlite.security.maximum_query_depth')) {
$depth = (int) $container->getParameter('graphqlite.security.maximum_query_depth');
$rulesDefinition[] = $container->findDefinition(QueryDepth::class)->setArgument(0, $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);
$staticTypes[] = SymfonyUserInterfaceType::class;
$container->getDefinition(StaticClassListTypeMapperFactory::class)->setArgument(0, $staticTypes);
}
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isAbstract() || $definition->getClass() === null) {
continue;
}
/**
* @var class-string $class
*/
$class = $definition->getClass();
/* foreach ($controllersNamespaces as $controllersNamespace) {
if (strpos($class, $controllersNamespace) === 0) {
$definition->addTag('graphql.annotated.controller');
}
}*/
foreach ($typesNamespaces as $typesNamespace) {
if (strpos($class, $typesNamespace) === 0) {
//$definition->addTag('graphql.annotated.type');
// 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) {
$schemaFactory->addMethodCall('addControllerNamespace', [ $controllersNamespace ]);
foreach ($this->getClassList($controllersNamespace) as $className => $refClass) {
$this->makePublicInjectedServices($refClass, $reader, $container, true);
}
}
foreach ($typesNamespaces as $typeNamespace) {
$schemaFactory->addMethodCall('addTypeNamespace', [ $typeNamespace ]);
foreach ($this->getClassList($typeNamespace) as $className => $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) {
if (isset($attributes["class"])) {
$phpClass = $attributes["class"];
if (!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);
}
}
}
if (!empty($customTypes)) {
$definition = $container->getDefinition(StaticTypeMapper::class);
$definition->addMethodCall('setTypes', [$customTypes]);
}
if (!empty($customNotMappedTypes)) {
$definition = $container->getDefinition(StaticTypeMapper::class);
$definition->addMethodCall('setNotMappedTypes', [$customNotMappedTypes]);
}
// 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);
$controllersList[] = $controllerClassName;
$aggregateQueryProvider->setArgument(0, $controllersList);
}
/**
* Register a method call on SchemaFactory for each tagged service, passing the service in parameter.
*
* @param string $tag
* @param string $methodName
*/
private function mapAdderToTag(string $tag, string $methodName, ContainerBuilder $container, Definition $schemaFactory): void
{
$taggedServices = $container->findTaggedServiceIds($tag);
foreach ($taggedServices as $id => $tags) {
// add the transport service to the TransportChain service
$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) {
$services = [];
foreach ($refClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$field = $reader->getRequestAnnotation($method, AbstractRequest::class);
if ($field !== null) {
if ($isController) {
$services[$refClass->getName()] = $refClass->getName();
}
$services += $this->getListOfInjectedServices($method, $container);
if ($field instanceof Field && $field->getPrefetchMethod() !== null) {
$services += $this->getListOfInjectedServices($refClass->getMethod($field->getPrefetchMethod()), $container);
}
}
}
return $services;
});
foreach ($services as $service) {
if ($container->hasAlias($service)) {
$container->getAlias($service)->setPublic(true);
} else {
$container->getDefinition($service)->setPublic(true);
}
}
}
/**
* @param ReflectionMethod $method
* @param ContainerBuilder $container
* @return array<string, string> key = value = service name
*/
private function getListOfInjectedServices(ReflectionMethod $method, ContainerBuilder $container): array
{
$services = [];
/**
* @var Autowire[] $autowireAnnotations
*/
$autowireAnnotations = $this->getAnnotationReader()->getMethodAnnotations($method, Autowire::class);
$parametersByName = null;
foreach ($autowireAnnotations as $autowire) {
$target = $autowire->getTarget();
if ($parametersByName === null) {
$parametersByName = self::getParametersByName($method);
}
if (!isset($parametersByName[$target])) {
throw new GraphQLException('In method '.$method->getDeclaringClass()->getName().'::'.$method->getName().', the @Autowire annotation refers to a non existing parameter named "'.$target.'"');
}
$id = $autowire->getIdentifier();
if ($id !== null) {
$services[$id] = $id;
} else {
$parameter = $parametersByName[$target];
$type = $parameter->getType();
if ($type !== null && $type instanceof ReflectionNamedType) {
$fqcn = $type->getName();
if ($container->has($fqcn)) {
$services[$fqcn] = $fqcn;
}
}
}
}
return $services;
}
/**
* @param ReflectionMethod $method
* @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 cached Doctrine annotation reader.
* Note: we cannot get the annotation reader service in the container as we are in a compiler pass.
*/
private function getAnnotationReader(): AnnotationReader
{
if ($this->annotationReader === null) {
AnnotationRegistry::registerLoader('class_exists');
$doctrineAnnotationReader = new DoctrineAnnotationReader();
if (function_exists('apcu_fetch')) {
$doctrineAnnotationReader = new CachedReader($doctrineAnnotationReader, new ApcuCache(), true);
}
$this->annotationReader = new AnnotationReader($doctrineAnnotationReader, AnnotationReader::LAX_MODE);
}
return $this->annotationReader;
}
/**
* @var CacheInterface
*/
private $cache;
private function getPsr16Cache(): CacheInterface
{
if ($this->cache === null) {
if (function_exists('apcu_fetch')) {
$this->cache = new Psr16Cache(new ApcuAdapter('graphqlite_bundle'));
} else {
$this->cache = new Psr16Cache(new PhpFilesAdapter('graphqlite_bundle', 0, $this->cacheDir));
}
}
return $this->cache;
}
/**
* @var ClassBoundCacheContractInterface
*/
private $codeCache;
private function getCodeCache(): ClassBoundCacheContractInterface
{
if ($this->codeCache === null) {
$this->codeCache = new ClassBoundCacheContract(new ClassBoundMemoryAdapter(new ClassBoundCache(new FileBoundCache($this->getPsr16Cache()))));
}
return $this->codeCache;
}
/**
* Returns the array of globbed classes.
* Only instantiable classes are returned.
*
* @return array<string,ReflectionClass<object>> Key: fully qualified class name
*/
private function getClassList(string $namespace, int $globTtl = 2, bool $recursive = true): array
{
$explorer = new GlobClassExplorer($namespace, $this->getPsr16Cache(), $globTtl, ClassNameMapper::createFromComposerFile(null, null, true), $recursive);
$allClasses = $explorer->getClassMap();
$classes = [];
foreach ($allClasses as $className => $phpFile) {
if (! class_exists($className, false)) {
// Let's try to load the file if it was not imported yet.
// We are importing the file manually to avoid triggering the autoloader.
// The autoloader might trigger errors if the file does not respect PSR-4 or if the
// Symfony DebugAutoLoader is installed. (see https://github.com/thecodingmachine/graphqlite/issues/216)
require_once $phpFile;
// Does it exists now?
if (! class_exists($className, false)) {
continue;
}
}
$refClass = new ReflectionClass($className);
if (! $refClass->isInstantiable()) {
continue;
}
$classes[$className] = $refClass;
}
return $classes;
}
}