/
SchemaFactory.php
474 lines (399 loc) · 17.4 KB
/
SchemaFactory.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
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite;
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Cache\ApcuCache;
use Doctrine\Common\Cache\PhpFileCache;
use GraphQL\Type\SchemaConfig;
use Mouf\Composer\ClassNameMapper;
use PackageVersions\Versions;
use Psr\Container\ContainerInterface;
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\Adapter\Psr16Adapter;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use TheCodingMachine\GraphQLite\Mappers\CompositeTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\GlobTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Parameters\ContainerParameterHandler;
use TheCodingMachine\GraphQLite\Mappers\Parameters\InjectUserParameterHandler;
use TheCodingMachine\GraphQLite\Mappers\Parameters\ParameterMiddlewareInterface;
use TheCodingMachine\GraphQLite\Mappers\Parameters\ParameterMiddlewarePipe;
use TheCodingMachine\GraphQLite\Mappers\Parameters\ResolveInfoParameterHandler;
use TheCodingMachine\GraphQLite\Mappers\PorpaginasTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\RecursiveTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\BaseTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\CompoundTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\FinalRootTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\IteratorTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\MyCLabsEnumTypeMapper;
use TheCodingMachine\GraphQLite\Mappers\Root\NullableTypeMapperAdapter;
use TheCodingMachine\GraphQLite\Mappers\Root\RootTypeMapperFactoryContext;
use TheCodingMachine\GraphQLite\Mappers\Root\RootTypeMapperFactoryInterface;
use TheCodingMachine\GraphQLite\Mappers\TypeMapperFactoryInterface;
use TheCodingMachine\GraphQLite\Mappers\TypeMapperInterface;
use TheCodingMachine\GraphQLite\Middlewares\AuthorizationFieldMiddleware;
use TheCodingMachine\GraphQLite\Middlewares\FieldMiddlewareInterface;
use TheCodingMachine\GraphQLite\Middlewares\FieldMiddlewarePipe;
use TheCodingMachine\GraphQLite\Middlewares\SecurityFieldMiddleware;
use TheCodingMachine\GraphQLite\Reflection\CachedDocBlockFactory;
use TheCodingMachine\GraphQLite\Security\AuthenticationServiceInterface;
use TheCodingMachine\GraphQLite\Security\AuthorizationServiceInterface;
use TheCodingMachine\GraphQLite\Security\FailAuthenticationService;
use TheCodingMachine\GraphQLite\Security\FailAuthorizationService;
use TheCodingMachine\GraphQLite\Security\SecurityExpressionLanguageProvider;
use TheCodingMachine\GraphQLite\Types\ArgumentResolver;
use TheCodingMachine\GraphQLite\Types\TypeResolver;
use TheCodingMachine\GraphQLite\Utils\NamespacedCache;
use TheCodingMachine\GraphQLite\Utils\Namespaces\NamespaceFactory;
use function array_map;
use function array_reverse;
use function crc32;
use function function_exists;
use function md5;
use function substr;
use function sys_get_temp_dir;
/**
* A class to help getting started with GraphQLite.
* It is in charge of creating a schema with most sensible defaults.
*/
class SchemaFactory
{
public const GLOB_CACHE_SECONDS = 2;
/** @var string[] */
private $controllerNamespaces = [];
/** @var string[] */
private $typeNamespaces = [];
/** @var QueryProviderInterface[] */
private $queryProviders = [];
/** @var QueryProviderFactoryInterface[] */
private $queryProviderFactories = [];
/** @var RootTypeMapperFactoryInterface[] */
private $rootTypeMapperFactories = [];
/** @var TypeMapperInterface[] */
private $typeMappers = [];
/** @var TypeMapperFactoryInterface[] */
private $typeMapperFactories = [];
/** @var ParameterMiddlewareInterface[] */
private $parameterMiddlewares = [];
/** @var Reader */
private $doctrineAnnotationReader;
/** @var AuthenticationServiceInterface|null */
private $authenticationService;
/** @var AuthorizationServiceInterface|null */
private $authorizationService;
/** @var CacheInterface */
private $cache;
/** @var NamingStrategyInterface|null */
private $namingStrategy;
/** @var ContainerInterface */
private $container;
/** @var ClassNameMapper */
private $classNameMapper;
/** @var SchemaConfig */
private $schemaConfig;
/** @var int|null */
private $globTTL = self::GLOB_CACHE_SECONDS;
/** @var array<int, FieldMiddlewareInterface> */
private $fieldMiddlewares = [];
/** @var ExpressionLanguage|null */
private $expressionLanguage;
/** @var string */
private $cacheNamespace;
public function __construct(CacheInterface $cache, ContainerInterface $container)
{
$this->cacheNamespace = substr(md5(Versions::getVersion('thecodingmachine/graphqlite')), 0, 8);
$this->cache = $cache;
$this->container = $container;
}
/**
* Registers a namespace that can contain GraphQL controllers.
*/
public function addControllerNamespace(string $namespace): self
{
$this->controllerNamespaces[] = $namespace;
return $this;
}
/**
* Registers a namespace that can contain GraphQL types.
*/
public function addTypeNamespace(string $namespace): self
{
$this->typeNamespaces[] = $namespace;
return $this;
}
/**
* Registers a query provider.
*/
public function addQueryProvider(QueryProviderInterface $queryProvider): self
{
$this->queryProviders[] = $queryProvider;
return $this;
}
/**
* Registers a query provider factory.
*/
public function addQueryProviderFactory(QueryProviderFactoryInterface $queryProviderFactory): self
{
$this->queryProviderFactories[] = $queryProviderFactory;
return $this;
}
/**
* Registers a root type mapper factory.
*/
public function addRootTypeMapperFactory(RootTypeMapperFactoryInterface $rootTypeMapperFactory): self
{
$this->rootTypeMapperFactories[] = $rootTypeMapperFactory;
return $this;
}
/**
* Registers a type mapper.
*/
public function addTypeMapper(TypeMapperInterface $typeMapper): self
{
$this->typeMappers[] = $typeMapper;
return $this;
}
/**
* Registers a type mapper factory.
*/
public function addTypeMapperFactory(TypeMapperFactoryInterface $typeMapperFactory): self
{
$this->typeMapperFactories[] = $typeMapperFactory;
return $this;
}
/**
* Registers a parameter middleware.
*/
public function addParameterMiddleware(ParameterMiddlewareInterface $parameterMiddleware): self
{
$this->parameterMiddlewares[] = $parameterMiddleware;
return $this;
}
public function setDoctrineAnnotationReader(Reader $annotationReader): self
{
$this->doctrineAnnotationReader = $annotationReader;
return $this;
}
/**
* 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 getDoctrineAnnotationReader(): Reader
{
if ($this->doctrineAnnotationReader === null) {
AnnotationRegistry::registerLoader('class_exists');
$doctrineAnnotationReader = new DoctrineAnnotationReader();
$cache = function_exists('apcu_fetch') ? new ApcuCache() : new PhpFileCache(sys_get_temp_dir() . '/graphqlite.' . crc32(__DIR__));
$cache->setNamespace($this->cacheNamespace);
$doctrineAnnotationReader = new CachedReader($doctrineAnnotationReader, $cache, true);
return $doctrineAnnotationReader;
}
return $this->doctrineAnnotationReader;
}
public function setAuthenticationService(AuthenticationServiceInterface $authenticationService): self
{
$this->authenticationService = $authenticationService;
return $this;
}
public function setAuthorizationService(AuthorizationServiceInterface $authorizationService): self
{
$this->authorizationService = $authorizationService;
return $this;
}
public function setNamingStrategy(NamingStrategyInterface $namingStrategy): self
{
$this->namingStrategy = $namingStrategy;
return $this;
}
public function setSchemaConfig(SchemaConfig $schemaConfig): self
{
$this->schemaConfig = $schemaConfig;
return $this;
}
public function setClassNameMapper(ClassNameMapper $classNameMapper): self
{
$this->classNameMapper = $classNameMapper;
return $this;
}
/**
* Sets the time to live time of the cache for annotations in files.
* By default this is set to 2 seconds which is ok for development environments.
* Set this to "null" (i.e. infinity) for production environments.
*/
public function setGlobTTL(?int $globTTL): self
{
$this->globTTL = $globTTL;
return $this;
}
/**
* Sets GraphQLite in "prod" mode (cache settings optimized for best performance).
*
* This is a shortcut for `$schemaFactory->setGlobTTL(null)`
*/
public function prodMode(): self
{
return $this->setGlobTTL(null);
}
/**
* Sets GraphQLite in "dev" mode (this is the default mode: cache settings optimized for best developer experience).
*
* This is a shortcut for `$schemaFactory->setGlobTTL(2)`
*/
public function devMode(): self
{
return $this->setGlobTTL(self::GLOB_CACHE_SECONDS);
}
/**
* Registers a field middleware (used to parse custom annotations that modify the GraphQLite behaviour in Fields/Queries/Mutations.
*/
public function addFieldMiddleware(FieldMiddlewareInterface $fieldMiddleware): self
{
$this->fieldMiddlewares[] = $fieldMiddleware;
return $this;
}
/**
* Sets a custom expression language to use.
* ExpressionLanguage is used to evaluate expressions in the "Security" tag.
*/
public function setExpressionLanguage(ExpressionLanguage $expressionLanguage): self
{
$this->expressionLanguage = $expressionLanguage;
return $this;
}
public function createSchema(): Schema
{
$annotationReader = new AnnotationReader($this->getDoctrineAnnotationReader(), AnnotationReader::LAX_MODE);
$authenticationService = $this->authenticationService ?: new FailAuthenticationService();
$authorizationService = $this->authorizationService ?: new FailAuthorizationService();
$typeResolver = new TypeResolver();
$namespacedCache = new NamespacedCache($this->cache);
$cachedDocBlockFactory = new CachedDocBlockFactory($namespacedCache);
$namingStrategy = $this->namingStrategy ?: new NamingStrategy();
$typeRegistry = new TypeRegistry();
$symfonyCache = new Psr16Adapter($this->cache, $this->cacheNamespace);
$namespaceFactory = new NamespaceFactory($namespacedCache, $this->classNameMapper, $this->globTTL);
$nsList = array_map(static function (string $namespace) use ($namespaceFactory) {
return $namespaceFactory->createNamespace($namespace);
}, $this->typeNamespaces);
$expressionLanguage = $this->expressionLanguage ?: new ExpressionLanguage($symfonyCache);
$expressionLanguage->registerProvider(new SecurityExpressionLanguageProvider());
$fieldMiddlewarePipe = new FieldMiddlewarePipe();
foreach ($this->fieldMiddlewares as $fieldMiddleware) {
$fieldMiddlewarePipe->pipe($fieldMiddleware);
}
// TODO: add a logger to the SchemaFactory and make use of it everywhere (and most particularly in SecurityFieldMiddleware)
$fieldMiddlewarePipe->pipe(new SecurityFieldMiddleware($expressionLanguage, $authenticationService, $authorizationService));
$fieldMiddlewarePipe->pipe(new AuthorizationFieldMiddleware($authenticationService, $authorizationService));
$compositeTypeMapper = new CompositeTypeMapper();
$recursiveTypeMapper = new RecursiveTypeMapper($compositeTypeMapper, $namingStrategy, $namespacedCache, $typeRegistry);
$topRootTypeMapper = new NullableTypeMapperAdapter();
$errorRootTypeMapper = new FinalRootTypeMapper($recursiveTypeMapper);
$rootTypeMapper = new BaseTypeMapper($errorRootTypeMapper, $recursiveTypeMapper, $topRootTypeMapper);
$rootTypeMapper = new MyCLabsEnumTypeMapper($rootTypeMapper, $annotationReader, $symfonyCache, $nsList);
if (! empty($this->rootTypeMapperFactories)) {
$rootSchemaFactoryContext = new RootTypeMapperFactoryContext(
$annotationReader,
$typeResolver,
$namingStrategy,
$typeRegistry,
$recursiveTypeMapper,
$this->container,
$namespacedCache,
$this->globTTL
);
$reversedRootTypeMapperFactories = array_reverse($this->rootTypeMapperFactories);
foreach ($reversedRootTypeMapperFactories as $rootTypeMapperFactory) {
$rootTypeMapper = $rootTypeMapperFactory->create($rootTypeMapper, $rootSchemaFactoryContext);
}
}
$rootTypeMapper = new CompoundTypeMapper($rootTypeMapper, $topRootTypeMapper, $typeRegistry, $recursiveTypeMapper);
$rootTypeMapper = new IteratorTypeMapper($rootTypeMapper, $topRootTypeMapper);
$topRootTypeMapper->setNext($rootTypeMapper);
$argumentResolver = new ArgumentResolver();
$parameterMiddlewarePipe = new ParameterMiddlewarePipe();
foreach ($this->parameterMiddlewares as $parameterMapper) {
$parameterMiddlewarePipe->pipe($parameterMapper);
}
$parameterMiddlewarePipe->pipe(new ResolveInfoParameterHandler());
$parameterMiddlewarePipe->pipe(new ContainerParameterHandler($this->container));
$parameterMiddlewarePipe->pipe(new InjectUserParameterHandler($authenticationService));
$fieldsBuilder = new FieldsBuilder(
$annotationReader,
$recursiveTypeMapper,
$argumentResolver,
$typeResolver,
$cachedDocBlockFactory,
$namingStrategy,
$topRootTypeMapper,
$parameterMiddlewarePipe,
$fieldMiddlewarePipe
);
$typeGenerator = new TypeGenerator($annotationReader, $namingStrategy, $typeRegistry, $this->container, $recursiveTypeMapper, $fieldsBuilder);
$inputTypeUtils = new InputTypeUtils($annotationReader, $namingStrategy);
$inputTypeGenerator = new InputTypeGenerator($inputTypeUtils, $fieldsBuilder);
if (empty($this->typeNamespaces) && empty($this->typeMappers)) {
throw new GraphQLRuntimeException('Cannot create schema: no namespace for types found (You must call the SchemaFactory::addTypeNamespace() at least once).');
}
foreach ($nsList as $ns) {
$compositeTypeMapper->addTypeMapper(new GlobTypeMapper(
$ns,
$typeGenerator,
$inputTypeGenerator,
$inputTypeUtils,
$this->container,
$annotationReader,
$namingStrategy,
$recursiveTypeMapper,
$namespacedCache,
$this->globTTL
));
}
foreach ($this->typeMappers as $typeMapper) {
$compositeTypeMapper->addTypeMapper($typeMapper);
}
if (! empty($this->typeMapperFactories) || ! empty($this->queryProviderFactories)) {
$context = new FactoryContext(
$annotationReader,
$typeResolver,
$namingStrategy,
$typeRegistry,
$fieldsBuilder,
$typeGenerator,
$inputTypeGenerator,
$recursiveTypeMapper,
$this->container,
$namespacedCache,
$this->globTTL
);
}
foreach ($this->typeMapperFactories as $typeMapperFactory) {
$compositeTypeMapper->addTypeMapper($typeMapperFactory->create($context));
}
$compositeTypeMapper->addTypeMapper(new PorpaginasTypeMapper($recursiveTypeMapper));
$queryProviders = [];
foreach ($this->controllerNamespaces as $controllerNamespace) {
$queryProviders[] = new GlobControllerQueryProvider(
$controllerNamespace,
$fieldsBuilder,
$this->container,
$annotationReader,
$namespacedCache,
$this->classNameMapper,
$this->globTTL
);
}
foreach ($this->queryProviders as $queryProvider) {
$queryProviders[] = $queryProvider;
}
foreach ($this->queryProviderFactories as $queryProviderFactory) {
$queryProviders[] = $queryProviderFactory->create($context);
}
if ($queryProviders === []) {
throw new GraphQLRuntimeException('Cannot create schema: no namespace for controllers found (You must call the SchemaFactory::addControllerNamespace() at least once).');
}
$aggregateQueryProvider = new AggregateQueryProvider($queryProviders);
return new Schema($aggregateQueryProvider, $recursiveTypeMapper, $typeResolver, $topRootTypeMapper, $this->schemaConfig);
}
}