-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathTypeGenerator.php
277 lines (223 loc) · 8.7 KB
/
TypeGenerator.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
<?php
namespace Overblog\GraphQLBundle\Generator;
use Composer\Autoload\ClassLoader;
use GraphQL\Type\Definition\ResolveInfo;
use Overblog\GraphQLBundle\Definition\Argument;
use Overblog\GraphQLBundle\Error\UserWarning;
use Overblog\GraphQLGenerator\Generator\TypeGenerator as BaseTypeGenerator;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Filesystem\Filesystem;
class TypeGenerator extends BaseTypeGenerator
{
const USE_FOR_CLOSURES = '$container, $request, $user, $token';
private $cacheDir;
private $defaultResolver;
private $configs;
private $useClassMap = true;
private $baseCacheDir;
private static $classMapLoaded = false;
public function __construct($classNamespace, array $skeletonDirs, $cacheDir, callable $defaultResolver, array $configs, $useClassMap = true, $baseCacheDir = null)
{
$this->setCacheDir($cacheDir);
$this->defaultResolver = $defaultResolver;
$this->configs = $this->processConfigs($configs);
$this->useClassMap = $useClassMap;
$this->baseCacheDir = $baseCacheDir;
parent::__construct($classNamespace, $skeletonDirs);
}
/**
* @return string|null
*/
public function getBaseCacheDir()
{
return $this->baseCacheDir;
}
/**
* @param string|null $baseCacheDir
*/
public function setBaseCacheDir($baseCacheDir)
{
$this->baseCacheDir = $baseCacheDir;
}
/**
* @return string|null
*/
public function getCacheDir(/*bool $useDefault = true*/)
{
$useDefault = func_num_args() > 0 ? func_get_arg(0) : true;
if ($useDefault) {
return $this->cacheDir ?: $this->baseCacheDir.'/overblog/graphql-bundle/__definitions__';
} else {
return $this->cacheDir;
}
}
/**
* @param string|null $cacheDir
*
* @return $this
*/
public function setCacheDir($cacheDir)
{
$this->cacheDir = $cacheDir;
return $this;
}
protected function generateClassDocBlock(array $value)
{
return <<<'EOF'
/**
* THIS FILE WAS GENERATED AND SHOULD NOT BE MODIFIED!
*/
EOF;
}
protected function generateOutputFields(array $config)
{
$outputFieldsCode = sprintf(
'self::applyPublicFilters(%s)',
$this->processFromArray($config['fields'], 'OutputField')
);
return sprintf(static::$closureTemplate, '', $outputFieldsCode);
}
protected function generateClosureUseStatements(array $config)
{
return 'use ('.static::USE_FOR_CLOSURES.') ';
}
protected function resolveTypeCode($alias)
{
return sprintf('$container->get(\'%s\')->resolve(%s)', 'overblog_graphql.type_resolver', var_export($alias, true));
}
protected function generatePublic(array $value)
{
if (!$this->arrayKeyExistsAndIsNotNull($value, 'public')) {
return 'null';
}
$publicCallback = $this->callableCallbackFromArrayValue($value, 'public', '$typeName, $fieldName');
if ('null' === $publicCallback) {
return $publicCallback;
}
$code = <<<'CODE'
function ($fieldName) <closureUseStatements> {
<spaces><spaces>$publicCallback = %s;
<spaces><spaces>return call_user_func($publicCallback, $this->name, $fieldName);
<spaces>}
CODE;
$code = sprintf($code, $publicCallback);
return $code;
}
protected function generateResolve(array $value)
{
$accessIsSet = $this->arrayKeyExistsAndIsNotNull($value, 'access');
$fieldOptions = $value;
if (!$this->arrayKeyExistsAndIsNotNull($fieldOptions, 'resolve')) {
$fieldOptions['resolve'] = $this->defaultResolver;
}
$resolveCallback = parent::generateResolve($fieldOptions);
$resolveCallback = ltrim($this->prefixCodeWithSpaces($resolveCallback));
if (!$accessIsSet || true === $fieldOptions['access']) { // access granted to this field
if ('null' === $resolveCallback) {
return $resolveCallback;
}
$argumentClass = $this->shortenClassName(Argument::class);
$resolveInfoClass = $this->shortenClassName(ResolveInfo::class);
$code = <<<'CODE'
function ($value, $args, $context, %s $info) <closureUseStatements>{
<spaces><spaces>$resolverCallback = %s;
<spaces><spaces>return call_user_func_array($resolverCallback, [$value, new %s($args), $context, $info]);
<spaces>}
CODE;
return sprintf($code, $resolveInfoClass, $resolveCallback, $argumentClass);
} elseif ($accessIsSet && false === $fieldOptions['access']) { // access deny to this field
$exceptionClass = $this->shortenClassName(UserWarning::class);
return sprintf('function () { throw new %s(\'Access denied to this field.\'); }', $exceptionClass);
} else { // wrap resolver with access
$accessChecker = $this->callableCallbackFromArrayValue($fieldOptions, 'access', '$value, $args, $context, '.ResolveInfo::class.' $info, $object');
$resolveInfoClass = $this->shortenClassName(ResolveInfo::class);
$argumentClass = $this->shortenClassName(Argument::class);
$code = <<<'CODE'
function ($value, $args, $context, %s $info) <closureUseStatements> {
<spaces><spaces>$resolverCallback = %s;
<spaces><spaces>$accessChecker = %s;
<spaces><spaces>$isMutation = $info instanceof ResolveInfo && 'mutation' === $info->operation->operation && $info->parentType === $info->schema->getMutationType();
<spaces><spaces>return $container->get('overblog_graphql.access_resolver')->resolve($accessChecker, $resolverCallback, [$value, new %s($args), $context, $info], $isMutation);
<spaces>}
CODE;
$code = sprintf($code, $resolveInfoClass, $resolveCallback, $accessChecker, $argumentClass);
return $code;
}
}
/**
* @param array $value
*
* @return string
*/
protected function generateComplexity(array $value)
{
$resolveComplexity = parent::generateComplexity($value);
$resolveComplexity = ltrim($this->prefixCodeWithSpaces($resolveComplexity));
if ('null' === $resolveComplexity) {
return $resolveComplexity;
}
$argumentClass = $this->shortenClassName(Argument::class);
$code = <<<'CODE'
function ($childrenComplexity, $args = []) <closureUseStatements>{
<spaces><spaces>$resolveComplexity = %s;
<spaces><spaces>return call_user_func_array($resolveComplexity, [$childrenComplexity, new %s($args)]);
<spaces>}
CODE;
$code = sprintf($code, $resolveComplexity, $argumentClass);
return $code;
}
public function compile($mode)
{
$cacheDir = $this->getCacheDir();
$writeMode = $mode & self::MODE_WRITE;
if ($writeMode && file_exists($cacheDir)) {
$fs = new Filesystem();
$fs->remove($cacheDir);
}
$classes = $this->generateClasses($this->configs, $cacheDir, $mode);
if ($writeMode && $this->useClassMap) {
$content = "<?php\nreturn ".var_export($classes, true).';';
// replaced hard-coding absolute path by __DIR__ (see https://github.com/overblog/GraphQLBundle/issues/167)
$content = str_replace(' => \''.$cacheDir, ' => __DIR__ . \'', $content);
file_put_contents($this->getClassesMap(), $content);
$this->loadClasses(true);
}
return $classes;
}
public function loadClasses($forceReload = false)
{
if ($this->useClassMap && (!self::$classMapLoaded || $forceReload)) {
$classMapFile = $this->getClassesMap();
$classes = file_exists($classMapFile) ? require $classMapFile : [];
/** @var ClassLoader $mapClassLoader */
static $mapClassLoader = null;
if (null === $mapClassLoader) {
$mapClassLoader = new ClassLoader();
$mapClassLoader->setClassMapAuthoritative(true);
} else {
$mapClassLoader->unregister();
}
$mapClassLoader->addClassMap($classes);
$mapClassLoader->register();
self::$classMapLoaded = true;
}
}
private function getClassesMap()
{
return $this->getCacheDir().'/__classes.map';
}
private function processConfigs(array $configs)
{
return array_map(
function ($v) {
if (is_array($v)) {
return call_user_func([$this, 'processConfigs'], $v);
} elseif (is_string($v) && 0 === strpos($v, '@=')) {
return new Expression(substr($v, 2));
}
return $v;
},
$configs
);
}
}