generated from spawnia/php-package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Generator.php
231 lines (186 loc) · 6.7 KB
/
Generator.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
<?php declare(strict_types=1);
namespace Spawnia\Sailor\Codegen;
use GraphQL\Error\Error;
use GraphQL\Error\SyntaxError;
use GraphQL\Language\AST\OperationDefinitionNode;
use GraphQL\Language\Parser;
use GraphQL\Type\Schema;
use GraphQL\Utils\BuildSchema;
use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\PhpNamespace;
use Nette\PhpGenerator\PsrPrinter;
use Spawnia\Sailor\EndpointConfig;
class Generator
{
protected EndpointConfig $endpointConfig;
protected string $configFile;
protected string $endpointName;
public function __construct(EndpointConfig $endpointConfig, string $configFile, string $endpointName)
{
$this->endpointConfig = $endpointConfig;
$this->configFile = $configFile;
$this->endpointName = $endpointName;
}
/**
* Generate a list of files to write.
*
* @return iterable<File>
*/
public function generate(): iterable
{
$parsedDocuments = $this->parsedDocuments();
if ([] === $parsedDocuments) {
return [];
}
$schema = $this->schema();
$document = Merger::combine($parsedDocuments);
// Validate the document as defined by the user to give them an error
// message that is more closely related to their source code
Validator::validate($schema, $document);
$document = (new FoldFragments($document))->modify();
AddTypename::modify($document);
// Validate again to ensure the modifications we made were safe
Validator::validate($schema, $document);
foreach ((new OperationGenerator($schema, $document, $this->endpointConfig))->generate() as $class) {
yield $this->makeFile($class);
}
foreach ($this->endpointConfig->configureTypes($schema) as $typeConfig) {
foreach ($typeConfig->generateClasses() as $class) {
yield $this->makeFile($class);
}
}
foreach ($this->endpointConfig->generateClasses($schema, $document) as $class) {
yield $this->makeFile($class);
}
}
protected function makeFile(ClassType $classType): File
{
$endpoint = $classType->addMethod('endpoint');
$endpoint->setStatic();
$endpoint->setReturnType('string');
$endpoint->setBody(<<<PHP
return '{$this->endpointName}';
PHP);
$file = new File();
$phpNamespace = $classType->getNamespace();
if (null === $phpNamespace) {
throw new \Exception('Generated classes must have a namespace.');
}
$namespace = $phpNamespace->getName();
$targetDirectory = $this->targetDirectory($namespace);
$file->directory = $targetDirectory;
$config = $classType->addMethod('config');
$config->setStatic();
$config->setReturnType('string');
$config->setBody(<<<PHP
return {$this->configPath($targetDirectory)};
PHP);
$file->name = $classType->getName() . '.php';
$file->content = self::asPhpFile($classType, $phpNamespace);
return $file;
}
protected function targetDirectory(string $namespace): string
{
$pathInTarget = self::after($namespace, $this->endpointConfig->namespace());
$pathInTarget = str_replace('\\', '/', $pathInTarget);
return $this->endpointConfig->targetPath() . $pathInTarget;
}
/**
* @see https://stackoverflow.com/a/2638272
*/
protected function configPath(string $directory): string
{
$from = explode('/', $directory);
$to = explode('/', $this->configFile);
$relativeParts = $to;
foreach ($from as $depth => $dir) {
if ($dir === $to[$depth]) {
array_shift($relativeParts);
} else {
$upwards = count($relativeParts) + count($from) - $depth;
$relativeParts = array_pad($relativeParts, -$upwards, '..');
break;
}
}
$relative = implode('/', $relativeParts);
return "\\Safe\\realpath(__DIR__ . '/{$relative}')";
}
public static function after(string $subject, string $search): string
{
if ('' === $search) {
return $subject;
}
$parts = explode($search, $subject, 2);
return array_reverse($parts)[0];
}
protected static function asPhpFile(ClassType $classType, PhpNamespace $namespace): string
{
$printer = new PsrPrinter();
return <<<PHP
<?php declare(strict_types=1);
namespace {$namespace->getName()};
{$printer->printClass($classType, $namespace)}
PHP;
}
/**
* Parse the raw document contents.
*
* @param array<string, string> $documents
*
* @throws \GraphQL\Error\SyntaxError
*
* @return array<string, \GraphQL\Language\AST\DocumentNode>
*/
public static function parseDocuments(array $documents): array
{
$parsed = [];
foreach ($documents as $path => $content) {
try {
$parsed[$path] = Parser::parse($content);
} catch (SyntaxError $error) {
throw new Error(
// Inform the user which file the error occurred in.
"Failed to parse {$path}: {$error->getMessage()}.",
null,
$error->getSource(),
$error->getPositions()
);
}
}
return $parsed;
}
/**
* @param array<string, \GraphQL\Language\AST\DocumentNode> $parsed
*/
public static function validateDocuments(array $parsed): void
{
foreach ($parsed as $path => $documentNode) {
foreach ($documentNode->definitions as $definition) {
if ($definition instanceof OperationDefinitionNode && null === $definition->name) {
throw new Error("Found unnamed operation definition in {$path}.", $definition);
}
}
}
}
protected function schema(): Schema
{
$schemaString = \Safe\file_get_contents(
$this->endpointConfig->schemaPath()
);
return BuildSchema::build($schemaString);
}
/**
* @return array<string, \GraphQL\Language\AST\DocumentNode>
*/
protected function parsedDocuments(): array
{
$documents = $this->endpointConfig
->finder()
->documents();
// Ignore the schema itself, it never contains operation definitions
unset($documents[$this->endpointConfig->schemaPath()]);
$parsed = static::parseDocuments($documents);
static::validateDocuments($parsed);
return $parsed;
}
}