Overview
  • Namespace
  • Class

Namespaces

  • WPGraphQL
    • Data
    • Type
      • Avatar
      • Comment
        • Connection
      • CommentAuthor
      • EditLock
      • Enum
      • MediaItem
        • Mutation
      • Plugin
        • Connection
      • PostObject
        • Connection
        • Mutation
      • PostType
      • Setting
      • Taxonomy
      • TermObject
        • Connection
        • Mutation
      • Theme
        • Connection
      • Union
      • User
        • Connection
        • Mutation
    • Utils

Classes

  • WPGraphQL\AppContext
  • WPGraphQL\Data\Config
  • WPGraphQL\Data\ConnectionResolver
  • WPGraphQL\Data\DataSource
  • WPGraphQL\Data\Loader
  • WPGraphQL\Router
  • WPGraphQL\Type\Avatar\AvatarType
  • WPGraphQL\Type\Comment\CommentQuery
  • WPGraphQL\Type\Comment\CommentType
  • WPGraphQL\Type\Comment\Connection\CommentConnectionArgs
  • WPGraphQL\Type\Comment\Connection\CommentConnectionDefinition
  • WPGraphQL\Type\Comment\Connection\CommentConnectionResolver
  • WPGraphQL\Type\CommentAuthor\CommentAuthorQuery
  • WPGraphQL\Type\CommentAuthor\CommentAuthorType
  • WPGraphQL\Type\EditLock\EditLockType
  • WPGraphQL\Type\Enum\MediaItemStatusEnumType
  • WPGraphQL\Type\Enum\MimeTypeEnumType
  • WPGraphQL\Type\Enum\PostObjectFieldFormatEnumType
  • WPGraphQL\Type\Enum\PostStatusEnumType
  • WPGraphQL\Type\Enum\PostTypeEnumType
  • WPGraphQL\Type\Enum\RelationEnumType
  • WPGraphQL\Type\Enum\TaxonomyEnumType
  • WPGraphQL\Type\MediaItem\MediaItemType
  • WPGraphQL\Type\MediaItem\Mutation\MediaItemCreate
  • WPGraphQL\Type\MediaItem\Mutation\MediaItemDelete
  • WPGraphQL\Type\MediaItem\Mutation\MediaItemMutation
  • WPGraphQL\Type\MediaItem\Mutation\MediaItemUpdate
  • WPGraphQL\Type\Plugin\Connection\PluginConnectionDefinition
  • WPGraphQL\Type\Plugin\Connection\PluginConnectionResolver
  • WPGraphQL\Type\Plugin\PluginQuery
  • WPGraphQL\Type\Plugin\PluginType
  • WPGraphQL\Type\PostObject\Connection\PostObjectConnectionArgs
  • WPGraphQL\Type\PostObject\Connection\PostObjectConnectionArgsDateQuery
  • WPGraphQL\Type\PostObject\Connection\PostObjectConnectionDefinition
  • WPGraphQL\Type\PostObject\Connection\PostObjectConnectionResolver
  • WPGraphQL\Type\PostObject\Mutation\PostObjectCreate
  • WPGraphQL\Type\PostObject\Mutation\PostObjectDelete
  • WPGraphQL\Type\PostObject\Mutation\PostObjectMutation
  • WPGraphQL\Type\PostObject\Mutation\PostObjectUpdate
  • WPGraphQL\Type\PostObject\Mutation\TermObjectDelete
  • WPGraphQL\Type\PostObject\PostObjectQuery
  • WPGraphQL\Type\PostObject\PostObjectType
  • WPGraphQL\Type\PostType\PostTypeType
  • WPGraphQL\Type\RootMutationType
  • WPGraphQL\Type\RootQueryType
  • WPGraphQL\Type\Setting\SettingQuery
  • WPGraphQL\Type\Setting\SettingType
  • WPGraphQL\Type\Taxonomy\TaxonomyType
  • WPGraphQL\Type\TermObject\Connection\TermObjectConnectionArgs
  • WPGraphQL\Type\TermObject\Connection\TermObjectConnectionDefinition
  • WPGraphQL\Type\TermObject\Connection\TermObjectConnectionResolver
  • WPGraphQL\Type\TermObject\Mutation\TermObjectCreate
  • WPGraphQL\Type\TermObject\Mutation\TermObjectMutation
  • WPGraphQL\Type\TermObject\Mutation\TermObjectUpdate
  • WPGraphQL\Type\TermObject\TermObjectQuery
  • WPGraphQL\Type\TermObject\TermObjectType
  • WPGraphQL\Type\Theme\Connection\ThemeConnectionDefinition
  • WPGraphQL\Type\Theme\Connection\ThemeConnectionResolver
  • WPGraphQL\Type\Theme\ThemeType
  • WPGraphQL\Type\Union\CommentAuthorUnionType
  • WPGraphQL\Type\Union\PostObjectUnionType
  • WPGraphQL\Type\Union\TermObjectUnionType
  • WPGraphQL\Type\User\Connection\UserConnectionArgs
  • WPGraphQL\Type\User\Connection\UserConnectionDefinition
  • WPGraphQL\Type\User\Connection\UserConnectionResolver
  • WPGraphQL\Type\User\Mutation\UserCreate
  • WPGraphQL\Type\User\Mutation\UserDelete
  • WPGraphQL\Type\User\Mutation\UserMutation
  • WPGraphQL\Type\User\Mutation\UserUpdate
  • WPGraphQL\Type\User\UserQuery
  • WPGraphQL\Type\User\UserType
  • WPGraphQL\Type\WPEnumType
  • WPGraphQL\Type\WPInputObjectType
  • WPGraphQL\Type\WPObjectType
  • WPGraphQL\Types
  • WPGraphQL\Utils\InstrumentSchema
  • WPGraphQL\WPSchema

Interfaces

  • WPGraphQL\Data\ConnectionResolverInterface
  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 
<?php

namespace WPGraphQL;

use GraphQL\Error\FormattedError;
use GraphQL\Error\UserError;

/**
 * Class Router
 * This sets up the /graphql endpoint
 *
 * @package WPGraphQL
 * @since   0.0.1
 */
class Router {

    /**
     * Sets the route to use as the endpoint
     *
     * @var string $route
     * @access public
     */
    public static $route = 'graphql';

    /**
     * Set the default status code to 403 to represent unauthenticated requests. Authenticated requests
     * should set the status code to 200.
     *
     * @var int
     */
    public static $http_status_code = 403;

    /**
     * Router constructor.
     *
     * @since  0.0.1
     * @access public
     */
    public function __construct() {

        /**
         * Pass the route through a filter in case the endpoint /graphql should need to be changed
         *
         * @since 0.0.1
         * @return string
         */
        self::$route = apply_filters( 'graphql_endpoint', 'graphql' );

        /**
         * Create the rewrite rule for the route
         *
         * @since 0.0.1
         */
        add_action( 'init', [ $this, 'add_rewrite_rule' ], 10 );

        /**
         * Add the query var for the route
         *
         * @since 0.0.1
         */
        add_filter( 'query_vars', [ $this, 'add_query_var' ], 1, 1 );

        /**
         * Redirects the route to the graphql processor
         *
         * @since 0.0.1
         */
        add_action( 'parse_request', [ $this, 'resolve_http_request' ], 10 );

    }

    /**
     * Adds rewrite rule for the route endpoint
     *
     * @uses   add_rewrite_rule()
     * @since  0.0.1
     * @access public
     * @return void
     */
    public static function add_rewrite_rule() {

        add_rewrite_rule(
            self::$route . '/?$',
            'index.php?' . self::$route . '=true',
            'top'
        );

    }

    /**
     * Adds the query_var for the route
     *
     * @param array $query_vars The array of whitelisted query variables
     *
     * @access public
     * @since  0.0.1
     * @return array
     */
    public static function add_query_var( $query_vars ) {

        $query_vars[] = self::$route;

        return $query_vars;

    }

    /**
     * This resolves the http request and ensures that WordPress can respond with the appropriate
     * JSON response instead of responding with a template from the standard WordPress Template
     * Loading process
     *
     * @since  0.0.1
     * @access public
     * @return void
     */
    public static function resolve_http_request() {

        /**
         * Access the $wp_query object
         */
        global $wp_query;

        /**
         * Ensure we're on the registered route for graphql route
         */
        if ( empty( $GLOBALS['wp']->query_vars ) || ! is_array( $GLOBALS['wp']->query_vars ) || ! array_key_exists( self::$route, $GLOBALS['wp']->query_vars ) ) {
            return;
        }

        /**
         * Set is_home to false
         */
        $wp_query->is_home = false;

        /**
         * Whether it's a GraphQL HTTP Request
         *
         * @since 0.0.5
         */
        if ( ! defined( 'GRAPHQL_HTTP_REQUEST' ) ) {
            define( 'GRAPHQL_HTTP_REQUEST', true );
        }

        /**
         * Process the GraphQL query Request
         */
        self::process_http_request();

        return;

    }

    /**
     * Sends an HTTP header.
     *
     * @since  0.0.5
     * @access public
     *
     * @param string $key   Header key.
     * @param string $value Header value.
     */
    public static function send_header( $key, $value ) {

        /**
         * Sanitize as per RFC2616 (Section 4.2):
         *
         * Any LWS that occurs between field-content MAY be replaced with a
         * single SP before interpreting the field value or forwarding the
         * message downstream.
         */
        $value = preg_replace( '/\s+/', ' ', $value );
        header( apply_filters( 'graphql_send_header', sprintf( '%s: %s', $key, $value ), $key, $value ) );
    }

    /**
     * Sends an HTTP status code.
     *
     * @since  0.0.5
     * @access protected
     *
     * @param int $code HTTP status.
     */
    protected static function set_status( $code ) {
        status_header( $code );
    }

    /**
     * Set the response headers
     *
     * @param int $http_status The status code to send as a header
     *
     * @since  0.0.1
     * @access public
     * @return void
     */
    public static function set_headers( $http_status ) {

        if ( false === headers_sent() ) {

            self::set_status( $http_status );
            self::send_header( 'Access-Control-Allow-Origin', '*' );
            self::send_header( 'Access-Control-Allow-Headers', 'content-type' );
            self::send_header( 'Content-Type', 'application/json ; charset=' . get_option( 'blog_charset' ) );
            self::send_header( 'X-Robots-Tag', 'noindex' );
            self::send_header( 'X-Content-Type-Options', 'nosniff' );
            self::send_header( 'Access-Control-Allow-Headers', 'Authorization, Content-Type' );
            self::send_header( 'X-hacker', __( 'If you\'re reading this, you should visit github.com/wp-graphql and contribute!', 'wp-graphql' ) );

            /**
             * Send nocache headers on authenticated requests.
             *
             * @since 0.0.5
             *
             * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
             */
            $send_no_cache_headers = apply_filters( 'graphql_send_nocache_headers', is_user_logged_in() );
            if ( $send_no_cache_headers ) {
                foreach ( wp_get_nocache_headers() as $header => $header_value ) {
                    self::send_header( $header, $header_value );
                }
            }
        }
    }

    /**
     * Retrieves the raw request entity (body).
     *
     * @since  0.0.5
     * @access public
     * @global string $HTTP_RAW_POST_DATA Raw post data.
     * @return string Raw request data.
     */
    public static function get_raw_data() {

        global $HTTP_RAW_POST_DATA;

        /*
         * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
         * but we can do it ourself.
         */
        if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
            $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
        }

        return $HTTP_RAW_POST_DATA;

    }

    /**
     * This processes the graphql requests that come into the /graphql endpoint via an HTTP request
     *
     * @since  0.0.1
     * @access public
     * @return mixed
     */
    public static function process_http_request() {

        /**
         * This action can be hooked to to enable various debug tools,
         * such as enableValidation from the GraphQL Config.
         *
         * @since 0.0.4
         */
        do_action( 'graphql_process_http_request' );

        /**
         * Start the $response array to return for the response content
         *
         * @since 0.0.5
         */
        $response        = [];
        $graphql_results = [];
        $request         = '';
        $operation_name  = '';
        $variables       = [];
        $user            = null;

        try {

            /**
             * Respond to pre-flight requests.
             *
             * @see: https://apollographql.slack.com/archives/C10HTKHPC/p1507649812000123
             * @see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
             */
            if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {

                self::$http_status_code = 200;
                self::set_headers( self::$http_status_code );
                exit;

            } else if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'GET' ) {

                $data = [
                    'query'         => isset( $_GET['query'] ) ? sanitize_text_field( $_GET['query'] ) : '',
                    'operationName' => isset( $_GET['operationName'] ) ? sanitize_text_field( $_GET['operationName'] ) : '',
                    'variables'     => isset( $_GET['variables'] ) ? $_GET['variables'] : '',
                ];

                /**
                 * Allow the data to be filtered
                 *
                 * @param array $data An array containing the pieces of the data of the GraphQL request
                 */
                $data = apply_filters( 'graphql_request_data', $data );

                /**
                 * If the variables are already formatted as an array use them.
                 *
                 * Example:
                 * ?query=query getPosts($first:Int){posts(first:$first){edges{node{id}}}}&variables[first]=1
                 */
                if ( is_array( $data['variables'] ) ) {
                    $sanitized_variables = [];
                    foreach ( $data['variables'] as $key => $value ) {
                        $sanitized_variables[ $key ] = sanitize_text_field( $value );
                    }
                    $decoded_variables = $sanitized_variables;

                    /**
                     * If the variables are not an array, let's attempt to decode them and convert them to an array for
                     * use in the executor.
                     */
                } else {
                    $decoded_variables = json_decode( $data['variables'] );
                }

                $data['variables'] = ! empty( $decoded_variables ) && is_array( $decoded_variables ) ? $decoded_variables : null;

            } else {

                if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
                    $response['errors'] = __( 'WPGraphQL requires POST requests', 'wp-graphql' );
                }

                if ( ! isset( $_SERVER['CONTENT_TYPE'] ) || false === strpos( $_SERVER['CONTENT_TYPE'], 'application/json' ) ) {
                    $response['errors'] = __( 'The Content-Type for the request must be set to "application/json"', 'wp-graphql' );
                }

                /**
                 * Retrieve the raw data from the request and encode it to JSON
                 *
                 * @since 0.0.5
                 */
                $data = json_decode( self::get_raw_data(), true );
            }// End if().

            /**
             * If the $data is empty, catch an error.
             */
            if ( empty( $data ) || ( empty( $data['query'] ) ) ) {
                throw new UserError( __( 'GraphQL requests must be a POST or GET Request with a valid query', 'wp-graphql' ), 10 );
            }

            /**
             * Allow the data to be filtered
             *
             * @param array $data An array containing the pieces of the data of the GraphQL request
             */
            $data = apply_filters( 'graphql_request_data', $data );

            /**
             * Get the pieces of the request from the data
             */
            $request        = isset( $data['query'] ) ? $data['query'] : '';
            $operation_name = isset( $data['operationName'] ) ? $data['operationName'] : '';
            $variables      = isset( $data['variables'] ) ? $data['variables'] : '';

            /**
             * Process the GraphQL request
             *
             * @since 0.0.5
             */
            $graphql_results = do_graphql_request( $request, $operation_name, $variables );

            /**
             * Ensure the $graphql_request is returned as a proper, populated array,
             * otherwise add an error to the result
             */
            if ( ! empty( $graphql_results ) && is_array( $graphql_results ) ) {
                $response = $graphql_results;
            } else {
                $response['errors'] = __( 'The GraphQL request returned an invalid response', 'wp-graphql' );
            }

            /**
             * If the request is properly authenticated (a user has been set by some authentication mechanism),
             * set the status code to 200.
             */
            $user = wp_get_current_user();
            if ( $user && 0 !== $user->ID ) {
                self::$http_status_code = 200;
            }

        } catch ( \Exception $error ) {

            /**
             * If there are errors, set the status to 500
             * and format the captured errors to be output properly
             *
             * @since 0.0.4
             */
            self::$http_status_code = 500;
            $response['errors'] = [ FormattedError::createFromException( $error ) ];
        } // End try().

        /**
         * Run an action after the HTTP Response is ready to be sent back. This might be a good place for tools
         * to hook in to track metrics, such as how long the process took from `graphql_process_http_request`
         * to here, etc.
         *
         * @param array $response
         * @param array $graphql_results
         *
         * @since 0.0.5
         */
        do_action( 'graphql_process_http_request_response', $response, $graphql_results );

        /**
         * If headers haven't been sent already, let's set the headers and return the JSON response
         */
        if ( false === headers_sent() ) {

            /**
             * Filter the $status_code before setting the headers
             *
             * @param int      $status_code     The status code to apply to the headers
             * @param array    $response        The response of the GraphQL Request
             * @param array    $graphql_results The results of the GraphQL execution
             * @param string   $request         The GraphQL Request
             * @param string   $operation_name  The operation name of the GraphQL Request
             * @param array    $variables       The variables applied to the GraphQL Request
             * @param \WP_User $user            The current user object
             */
            $status_code = apply_filters( 'graphql_response_status_code', self::$http_status_code, $response, $graphql_results, $request, $operation_name, $variables, $user );

            /**
             * Set the response headers
             */
            self::set_headers( $status_code );

            /**
             * Send the JSON response
             */
            wp_send_json( $response );
        } elseif ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
            /**
             * Headers will already be set if this function is called within AJAX.
             */
            wp_send_json( $response );
        }

    }

}
API documentation generated by ApiGen