GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — ProcessGraphQL/ProcessGraphQL.module at main · tiefenb/ProcessGraphQL Expand file tree/ Copy pathProcessGraphQL.moduleMore file actions 400 lines (357 loc) · 12.8 KB / Copy pathProcessGraphQL.moduleFile metadata and controls400 lines (357 loc) · 12.8 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 <?php namespace ProcessWire; use GraphQL\Error\DebugFlag; use GraphQL\Error\Error; use GraphQL\Executor\ExecutionResult; use GraphQL\Server\Helper; use GraphQL\Server\OperationParams; use GraphQL\Server\RequestError; use GraphQL\Server\ServerConfig; use GraphQL\Server\StandardServer; use GraphQL\Type\Schema as GraphQLSchema; use GraphQL\Validator\Rules\QueryDepth; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\DocumentValidator; use ProcessWire\GraphQL\Context; use ProcessWire\GraphQL\Schema; use ProcessWire\HookEvent; class ProcessGraphQL extends Process implements Module { const pageName = 'graphql'; public static function getModuleInfo() { return array( 'title' => 'GraphQL', 'version' => '2.0.0', 'summary' => 'GraphQL for ProcessWire.', 'href' => 'https://github.com/dadish/ProcessGraphql', 'singular' => true, 'autoload' => 'process=ProcessTemplate', 'icon' => 'object-group', 'requires' => array("PHP>=8.4", "ProcessWire>=3.0.210"), ); } /** * Bootstrap the module */ public function init() { $autoload = $this->config->paths->site . 'modules/ProcessGraphQL/vendor/autoload.php'; if (file_exists($autoload)) require_once $autoload; $this->addHookAfter('Template::changed', $this, 'hookTemplateNameChange'); } /** * The hook for modifying the GraphQL schema types by the user. * The schema is an array of types that will be set to GraphQL types. * Custom types could be added bu just appending them into an array. * See the documentation of the library used by this module to learn more * @see The GraphQL lib https://github.com/webonyx/graphql-php * @param array $schema Schema config (`query`, `mutation`, ...) * @param Context|null $context Context the schema is built for * @return array */ public function ___modifySchema($schema, ?Context $context = null) { return $schema; } /** * Updates the legalTemplates on name change. Template names for ProcessWire * are not necessarily valid for GraphQL field naming. Those names that are * not compatible are removed from legalFields, those that are compatible * are updated when changed. * @param HookEvent $event ProcessWire hook $event object. */ public function hookTemplateNameChange(HookEvent $event) { $whatChanged = $event->arguments[0]; $oldName = $event->arguments[1]; $newName = $event->arguments[2]; // do nothing if name has not changed if ($whatChanged !== 'name') return; // do nothing if template is not in legalTemplates if (!in_array($oldName, $this->legalTemplates)) return; // remove the oldName from the legalTemplates $index = array_search($oldName, $this->legalTemplates); $legalTemplates = array_slice($this->legalTemplates, 0); array_splice($legalTemplates, $index, 1); $this->message("Removed `$oldName` from the legalTemplates."); // if newName is compatible with the module then add it into legalTemplates if (ProcessGraphQLConfig::isLegalTemplateName($newName)) { $legalTemplates[] = $newName; $this->message("Added `$newName` into legalTemplates."); } // make sure to remember changes! $this->modules->saveConfig($this, 'legalTemplates', $legalTemplates); } /** * Returns the GraphiQL GUI for ProcessWire admin when request's header is not * set to AJAX. Executes GraphQL api if it is AJAX. * @return string The rendered string of either GraphiQL GUI or GraphQL json * response */ public function ___execute() { if ($this->config->ajax) { $this->pages->setOutputFormatting(true); return json_encode($this->executeGraphQL()); } return $this->executeGraphiQLPartial(); } /** * Returns a GraphiQL page. * @return string An HTML string. */ public function executeGraphiQL() { $this->setupGraphiQLAssets(); $fullFilename = $this->config->paths->site . 'modules/ProcessGraphQL/graphiql/full.php'; return wireRenderFile($fullFilename, [ 'fullGraphiQL' => true, ]); } /** * Returns only the necessary parts for the GraphiQL GUI. * @return string An HTML strin. */ public function executeGraphiQLPartial() { $this->setupGraphiQLAssets(); $partialFilename = $this->config->paths->site . 'modules/ProcessGraphQL/graphiql/partial.php'; return wireRenderFile($partialFilename, [ 'fullGraphiQL' => false, ]); } /** * Setups the GraphiQL js/css assets for ProcessWire to handle in the admin. */ public function setupGraphiQLAssets() { $this->config->scripts->add("https://unpkg.com/[email protected]/umd/react.production.min.js"); $this->config->scripts->add("https://unpkg.com/[email protected]/umd/react-dom.production.min.js"); $this->config->scripts->add('https://unpkg.com/[email protected]/graphiql.min.js'); $this->config->styles->add('https://unpkg.com/[email protected]/graphiql.css'); $this->config->js($this->className, [ 'GraphQLServerUrl' => $this->getGraphQLServerUrl(), ]); } /** * Returns the server url from where the GraphiQL GUI will fetch the api. * @return string Url of the GraphQL server. */ public function getGraphQLServerUrl() { $url = $this->GraphQLServerUrl; if (!$url) $url = $this->pages->get('template=admin, name=' . self::pageName)->url; return $url; } /** * Parses the GraphQL request of the current HTTP request. * * Supports: * - GET with `query`, `variables`, `operationName` (queries only, no mutations) * - POST `application/json`, also batched as a JSON list (if enabled) * - POST `application/graphql` (the body is the query) * - POST form data (`application/x-www-form-urlencoded`, `multipart/form-data`) * * For backwards compatibility `payload` is accepted as alias of `query`. * * @param callable|null $readRawBody Returns the raw request body (default: php://input) * @return OperationParams|OperationParams[] * @throws RequestError */ public function getRequest(?callable $readRawBody = null): OperationParams|array { $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET'); $contentType = strtolower((string) ($_SERVER['CONTENT_TYPE'] ?? '')); $readRawBody ??= fn() => (string) file_get_contents('php://input'); $bodyParams = []; if ($method === 'POST') { if (str_contains($contentType, 'application/json')) { $rawBody = $readRawBody(); try { $bodyParams = $rawBody === '' ? [] : json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR); } catch (\JsonException $e) { throw new RequestError('Could not parse JSON body: ' . $e->getMessage()); } if (!is_array($bodyParams)) { throw new RequestError('GraphQL server expects a JSON object or array as request body.'); } } elseif (str_contains($contentType, 'application/graphql')) { $bodyParams = ['query' => $readRawBody()]; } else { $bodyParams = $_POST; } } $queryParams = self::withQueryAlias($_GET); $bodyParams = array_is_list($bodyParams) && $bodyParams ? array_map(fn($op) => is_array($op) ? self::withQueryAlias($op) : $op, $bodyParams) : self::withQueryAlias($bodyParams); return (new Helper())->parseRequestParams($method, $bodyParams, $queryParams); } /** * Maps the legacy `payload` parameter to `query`. */ private static function withQueryAlias(array $params): array { if (empty($params['query']) && !empty($params['payload'])) { $params['query'] = $params['payload']; } unset($params['payload']); return $params; } /** * Executes the GraphQL request. * * With a $payload the given query is executed. Without it, the request is * read from the current HTTP request (see getRequest()). Batched requests * return a list of results. * * @param string $payload GraphQL query * @param array|null $variables * @param string|null $operationName * @return array GraphQL response (`data`, `errors`), or a list of them for batches */ public function ___executeGraphQL($payload = "", $variables = null, $operationName = null) { // every execution gets its own context and schema $context = $this->createContext(); try { $operations = $payload ? OperationParams::create([ 'query' => $payload, 'variables' => $variables, 'operationName' => $operationName, ]) : $this->getRequest(); $context->permissions->turnOnApiAccess(); $result = $this->createServer($context)->executeRequest($operations); } catch (RequestError $e) { $result = new ExecutionResult(null, [Error::createLocatedError($e)]); } // the server already formats errors with the debug flag return is_array($result) ? array_map(fn(ExecutionResult $r) => $r->toArray(), $result) : $result->toArray(); } /** * The graphql-php server for the given context: schema, root value (the * $pages API variable), context value, validation rules, debug flag and * query batching setting. */ public function ___createServer(Context $context): StandardServer { $config = ServerConfig::create() ->setSchema($this->getSchema($context)) // $pages is callable (Pages::__invoke), which the server would treat as a // root value factory, so it is wrapped in a real factory ->setRootValue(fn() => $context->pages()) ->setContext($context) ->setDebugFlag($this->getDebugFlag()) ->setQueryBatching((bool) $this->queryBatching); $validationRules = $this->getValidationRules(); if ($validationRules !== null) { $config->setValidationRules($validationRules); } return new StandardServer($config); } /** * Creates the state of one GraphQL execution, bound to this module's * ProcessWire instance. Passed to every resolver as third argument. */ public function createContext(): Context { return new Context($this->wire(), $this); } /** * Builds the GraphQL schema for the given context (its user's permissions). */ public function getSchema(?Context $context = null): GraphQLSchema { return Schema::build($context ?? $this->createContext()); } /** * Validation rules incl. the configured query depth and complexity limits. * * @return array|null Null for the graphql-php defaults */ public function getValidationRules(): ?array { $maxQueryDepth = (int) $this->maxQueryDepth; $maxQueryComplexity = (int) $this->maxQueryComplexity; if (!$maxQueryDepth && !$maxQueryComplexity) { return null; } $validationRules = DocumentValidator::allRules(); if ($maxQueryDepth) $validationRules[] = new QueryDepth($maxQueryDepth); if ($maxQueryComplexity) $validationRules[] = new QueryComplexity($maxQueryComplexity); return $validationRules; } /** * Debug details (message and trace) in errors only in debug mode. */ public function getDebugFlag(): int { return $this->wire()->config->debug ? DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE : DebugFlag::NONE; } /** * The hook for modifying the GraphQL query operation fields by the user. * The queryFields is an array of fields that will be set to Query operation. * Custom fields could be added bu just appending them into an array. * See the documentation of the library used by this module to learn more * @see The GraphQL lib https://github.com/webonyx/graphql-php * @param array $queryFields * @param Context|null $context Context the schema is built for * @return array */ public function ___getQueryFields($queryFields, ?Context $context = null) { return $queryFields; } /** * The hook for modifying the GraphQL mutation operation fields by the user. * The mutationFields is an array of fields that will be set to Mutation operation. * Custom fields could be added bu just appending them into an array. * See the documentation of the library used by this module to learn more * @see The GraphQL lib https://github.com/webonyx/graphql-php * @param array $mutationFields * @param Context|null $context Context the schema is built for * @return array */ public function ___getMutationFields($mutationFields, ?Context $context = null) { return $mutationFields; } /** * Install the module page under setup */ public function ___install() { // create the page $page = new Page(); $page->template = 'admin'; $page->name = self::pageName; // set parent to the home->admin->setup $parent = $this->pages->get($this->config->adminRootPageID)->child("name=setup, include=all"); $page->parent = $parent; $page->process = $this->className; // set the page title as module title $info = self::getModuleInfo(); $page->title = $info['title']; // save the page and tell the user about it $page->save(); $this->message("Created page at: {$page->path}"); } /** * Delete the module page */ public function ___uninstall() { // find page by process field $moduleID = $this->modules->getModuleID($this); $page = $this->pages->get("process=$moduleID, name=" . self::pageName); // if the page exists then delete it and tell the user about it if ($page->id) { $this->message("Deleting page: {$page->path}"); $page->delete(); } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |