graphql-php/src/Server/OperationParams.php

139 lines
3.0 KiB
PHP
Raw Normal View History

<?php
2018-07-10 01:19:15 +03:00
declare(strict_types=1);
namespace GraphQL\Server;
2018-07-10 01:19:15 +03:00
use function array_change_key_case;
use function is_string;
use function json_decode;
use function json_last_error;
2018-09-02 10:17:27 +02:00
use const CASE_LOWER;
2018-07-10 01:19:15 +03:00
/**
* Structure representing parsed HTTP parameters for GraphQL operation
*/
class OperationParams
{
/**
* Id of the query (when using persistent queries).
*
* Valid aliases (case-insensitive):
* - id
* - queryId
* - documentId
*
* @api
* @var string
*/
public $queryId;
/**
* @api
* @var string
*/
public $query;
/**
* @api
* @var string
*/
public $operation;
/**
* @api
2018-07-10 01:19:15 +03:00
* @var mixed[]|null
*/
public $variables;
/**
* @api
* @var mixed[]|null
*/
public $extensions;
2018-07-10 01:19:15 +03:00
/** @var mixed[] */
private $originalInput;
2018-07-10 01:19:15 +03:00
/** @var bool */
private $readOnly;
/**
* Creates an instance from given array
*
2018-07-10 01:19:15 +03:00
* @param mixed[] $params
* @param bool $readonly
2018-09-26 10:35:23 +02:00
*
* @return OperationParams
2018-09-26 10:35:23 +02:00
*
* @api
*/
public static function create(array $params, $readonly = false)
{
$instance = new static();
2018-07-10 01:19:15 +03:00
$params = array_change_key_case($params, CASE_LOWER);
$instance->originalInput = $params;
$params += [
'query' => null,
'queryid' => null,
'documentid' => null, // alias to queryid
2017-08-18 02:54:35 +07:00
'id' => null, // alias to queryid
'operationname' => null,
2018-07-10 01:19:15 +03:00
'variables' => null,
'extensions' => null,
];
2018-07-10 01:19:15 +03:00
if ($params['variables'] === '') {
$params['variables'] = null;
}
if (is_string($params['variables'])) {
$tmp = json_decode($params['variables'], true);
2018-07-10 01:19:15 +03:00
if (! json_last_error()) {
$params['variables'] = $tmp;
}
}
$instance->query = $params['query'];
$instance->queryId = $params['queryid'] ?: $params['documentid'] ?: $params['id'];
$instance->operation = $params['operationname'];
$instance->variables = $params['variables'];
$instance->extensions = $params['extensions'];
$instance->readOnly = (bool) $readonly;
// Apollo server/client compatibility: look for the queryid in extensions
if (isset($instance->extensions['persistedQuery']['sha256Hash']) && empty($instance->query) && empty($instance->queryId)) {
$instance->queryId = $instance->extensions['persistedQuery']['sha256Hash'];
}
return $instance;
}
/**
* @param string $key
2018-09-26 10:35:23 +02:00
*
* @return mixed
2018-09-26 10:35:23 +02:00
*
* @api
*/
public function getOriginalInput($key)
{
2018-07-10 01:19:15 +03:00
return $this->originalInput[$key] ?? null;
}
/**
* Indicates that operation is executed in read-only context
* (e.g. via HTTP GET request)
*
* @return bool
2018-09-26 10:35:23 +02:00
*
* @api
*/
public function isReadOnly()
{
return $this->readOnly;
}
}