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 
<?php

namespace WPGraphQL\Type\PostObject\Connection;

use GraphQL\Type\Definition\ResolveInfo;
use GraphQLRelay\Connection\ArrayConnection;
use WPGraphQL\AppContext;
use WPGraphQL\Data\ConnectionResolver;
use WPGraphQL\Data\DataSource;
use WPGraphQL\Types;

/**
 * Class PostObjectConnection - connects posts to other types
 *
 * @package WPGraphQL\Data\Resolvers
 * @since   0.0.5
 */
class PostObjectConnectionResolver extends ConnectionResolver {

    /**
     * Stores the name of the $post_type being resolved
     *
     * @var $post_type
     */
    public static $post_type;

    /**
     * Holds the maximum number of items that can be queried per request
     *
     * @var int $max_query_amount
     */
    public static $max_query_amount = 100;

    /**
     * PostObjectConnectionResolver constructor.
     *
     * @param $post_type
     */
    public function __construct( $post_type ) {
        self::$post_type = $post_type;
    }

    /**
     * This returns the $query_args that should be used when querying for posts in the postObjectConnectionResolver.
     * This checks what input $args are part of the query, combines them with various filters, etc and returns an
     * array of $query_args to be used in the \WP_Query call
     *
     * @param mixed       $source  The query source being passed down to the resolver
     * @param array       $args    The arguments that were provided to the query
     * @param AppContext  $context Object containing app context that gets passed down the resolve tree
     * @param ResolveInfo $info    Info about fields passed down the resolve tree
     *
     * @return array
     */
    public static function get_query_args( $source, array $args, AppContext $context, ResolveInfo $info ) {

        /**
         * Prepare for later use
         */
        $last  = ! empty( $args['last'] ) ? $args['last'] : null;
        $first = ! empty( $args['first'] ) ? $args['first'] : null;

        /**
         * Set the post_type for the query based on the type of post being queried
         */
        $query_args['post_type'] = ! empty( self::$post_type ) ? self::$post_type : 'post';

        /**
         * Don't calculate the total rows, it's not needed and can be expensive
         */
        $query_args['no_found_rows'] = true;

        /**
         * Set the post_status to "publish" by default
         */
        $query_args['post_status'] = 'publish';

        /**
         * Set posts_per_page the highest value of $first and $last, with a (filterable) max of 100
         */
        $query_args['posts_per_page'] = min( max( absint( $first ), absint( $last ), 10 ), self::get_query_amount( $source, $args, $context, $info ) ) + 1;

        /**
         * Set the default to only query posts with no post_parent set
         */
        $query_args['post_parent'] = 0;

        /**
         * Set the graphql_cursor_offset which is used by Config::graphql_wp_query_cursor_pagination_support
         * to filter the WP_Query to support cursor pagination
         */
        $query_args['graphql_cursor_offset']  = self::get_offset( $args );
        $query_args['graphql_cursor_compare'] = ( ! empty( $last ) ) ? '>' : '<';

        /**
         * Pass the graphql $args to the WP_Query
         */
        $query_args['graphql_args'] = $args;

        /**
         * Collect the input_fields and sanitize them to prepare them for sending to the WP_Query
         */
        $input_fields = [];
        if ( ! empty( $args['where'] ) ) {
            $input_fields = self::sanitize_input_fields( $args['where'], $source, $args, $context, $info );
        }

        /**
         * If the post_type is "attachment" set the default "post_status" $query_arg to "inherit"
         */
        if ( 'attachment' === self::$post_type ) {
            $query_args['post_status'] = 'inherit';

            /**
             * Unset the "post_parent" for attachments, as we don't really care if they
             * have a post_parent set by default
             */
            unset( $query_args['post_parent'] );
        }

        /**
         * Determine where we're at in the Graph and adjust the query context appropriately.
         *
         * For example, if we're querying for posts as a field of termObject query, this will automatically
         * set the query to pull posts that belong to that term.
         */
        if ( true === is_object( $source ) ) :
            switch ( true ) {
                case $source instanceof \WP_Post:
                    $query_args['post_parent'] = $source->ID;
                    break;
                case $source instanceof \WP_Post_Type:
                    $query_args['post_type'] = $source->name;
                    break;
                case $source instanceof \WP_Term:
                    $query_args['tax_query'] = [
                        [
                            'taxonomy' => $source->taxonomy,
                            'terms'    => [ $source->term_id ],
                            'field'    => 'term_id',
                        ],
                    ];
                    break;
                case $source instanceof \WP_User:
                    $query_args['author'] = $source->ID;
                    break;
            }
        endif;

        /**
         * Merge the input_fields with the default query_args
         */
        if ( ! empty( $input_fields ) ) {
            $query_args = array_merge( $query_args, $input_fields );
        }

        /**
         * Map the orderby inputArgs to the WP_Query
         */
        if ( ! empty( $args['where']['orderby'] ) && is_array( $args['where']['orderby'] ) ) {
            $query_args['orderby'] = [];
            foreach ( $args['where']['orderby'] as $orderby_input ) {
                if ( ! empty( $orderby_input['field'] ) ) {
                    $query_args['orderby'] = [
                        esc_sql( $orderby_input['field'] ) => esc_sql( $orderby_input['order'] ),
                    ];
                }
            }
        }

        /**
         * If there's no orderby params in the inputArgs, set order based on the first/last argument
         */
        if ( empty( $query_args['orderby'] ) ) {
            $query_args['order'] = ! empty( $last ) ? 'ASC' : 'DESC';
        }

        /**
         * Filter the $query args to allow folks to customize queries programmatically
         *
         * @param array       $query_args The args that will be passed to the WP_Query
         * @param mixed       $source     The source that's passed down the GraphQL queries
         * @param array       $args       The inputArgs on the field
         * @param AppContext  $context    The AppContext passed down the GraphQL tree
         * @param ResolveInfo $info       The ResolveInfo passed down the GraphQL tree
         */
        $query_args = apply_filters( 'graphql_post_object_connection_query_args', $query_args, $source, $args, $context, $info );
        return $query_args;

    }

    /**
     * This runs the query and returns the response
     *
     * @param $query_args
     *
     * @return \WP_Query
     */
    public static function get_query( $query_args ) {
        $query = new \WP_Query( $query_args );

        return $query;
    }

    /**
     * This takes an array of items, the $args and the $query and returns the connection including
     * the edges and page info
     *
     * @param mixed       $query   The Query that was processed to get the connection data
     * @param array       $items   The array of items being connected
     * @param array       $args    The $args that were passed to the query
     * @param mixed       $source  The source being passed down the resolve tree
     * @param AppContext  $context The AppContext being passed down the resolve tree
     * @param ResolveInfo $info    the ResolveInfo passed down the resolve tree
     *
     * @return array
     */
    public static function get_connection( $query, array $items, $source, array $args, AppContext $context, ResolveInfo $info ) {

        /**
         * Get the $posts from the query
         */
        $items = ! empty( $items ) && is_array( $items ) ? $items : [];

        $info = self::get_query_info( $query );

        /**
         * Set whether there is or is not another page
         */
        $has_previous_page = ( ! empty( $args['last'] ) && ( $info['total_items'] >= self::get_query_amount( $source, $args, $context, $info ) ) ) ? true : false;
        $has_next_page     = ( ! empty( $args['first'] ) && ( $info['total_items'] >= self::get_query_amount( $source, $args, $context, $info ) ) ) ? true : false;

        /**
         * Slice the array to the amount of items that were requested
         */
        $items = array_slice( $items, 0, self::get_query_amount( $source, $args, $query, $info ) );

        /**
         * Get the edges from the $items
         */
        $edges = self::get_edges( $items, $source, $args, $context, $info );

        /**
         * Find the first_edge and last_edge
         */
        $first_edge      = $edges ? $edges[0] : null;
        $last_edge       = $edges ? $edges[ count( $edges ) - 1 ] : null;
        $edges_to_return = $edges;

        /**
         * Create the connection to return
         */
        $connection = [
            'edges'    => $edges_to_return,
            'pageInfo' => [
                'hasPreviousPage' => $has_previous_page,
                'hasNextPage'     => $has_next_page,
                'startCursor'     => ! empty( $first_edge['cursor'] ) ? $first_edge['cursor'] : null,
                'endCursor'       => ! empty( $last_edge['cursor'] ) ? $last_edge['cursor'] : null,
            ],
            'nodes'    => $items,
        ];

        return $connection;

    }

    /**
     * Takes an array of items and returns the edges
     *
     * @param $items
     *
     * @return array
     */
    public static function get_edges( $items, $source, $args, $context, $info ) {
        $edges = [];

        /**
         * If we're doing backward pagination we want to reverse the array before
         * returning it to the edges
         */
        if ( ! empty( $args['last'] ) ) {
            $items = array_reverse( $items );
        }

        if ( ! empty( $items ) && is_array( $items ) ) {
            foreach ( $items as $item ) {
                $edges[] = [
                    'cursor' => ArrayConnection::offsetToCursor( $item->ID ),
                    'node'   => DataSource::resolve_post_object( $item->ID, $item->post_type ),
                ];
            }
        }

        return $edges;
    }

    /**
     * This sets up the "allowed" args, and translates the GraphQL-friendly keys to WP_Query
     * friendly keys. There's probably a cleaner/more dynamic way to approach this, but
     * this was quick. I'd be down to explore more dynamic ways to map this, but for
     * now this gets the job done.
     *
     * @param array       $args     Query "where" args
     * @param mixed       $source   The query results for a query calling this
     * @param array       $all_args All of the arguments for the query (not just the "where" args)
     * @param AppContext  $context  The AppContext object
     * @param ResolveInfo $info     The ResolveInfo object
     *
     * @since  0.0.5
     * @access public
     * @return array
     */
    public static function sanitize_input_fields( array $args, $source, array $all_args, AppContext $context, ResolveInfo $info ) {

        $arg_mapping = [
            'authorName'   => 'author_name',
            'authorIn'     => 'author__in',
            'authorNotIn'  => 'author__not_in',
            'categoryId'   => 'cat',
            'categoryName' => 'category_name',
            'categoryIn'   => 'category__in',
            'tagId'        => 'tag_id',
            'tagIds'       => 'tag__and',
            'tagSlugAnd'   => 'tag_slug__and',
            'tagSlugIn'    => 'tag_slug__in',
            'search'       => 's',
            'id'           => 'p',
            'parent'       => 'post_parent',
            'parentIn'     => 'post_parent__in',
            'parentNotIn'  => 'post_parent__not_in',
            'in'           => 'post__in',
            'notIn'        => 'post__not_in',
            'nameIn'       => 'post_name__in',
            'hasPassword'  => 'has_password',
            'password'     => 'post_password',
            'status'       => 'post_status',
            'dateQuery'    => 'date_query',
        ];

        /**
         * Map and sanitize the input args to the WP_Query compatible args
         */
        $query_args = Types::map_input( $args, $arg_mapping );

        /**
         * Filter the input fields
         * This allows plugins/themes to hook in and alter what $args should be allowed to be passed
         * from a GraphQL Query to the WP_Query
         *
         * @param array       $query_args The mapped query arguments
         * @param array       $args       Query "where" args
         * @param string      $post_type  The post type for the query
         * @param mixed       $source     The query results for a query calling this
         * @param array       $all_args   All of the arguments for the query (not just the "where" args)
         * @param AppContext  $context    The AppContext object
         * @param ResolveInfo $info       The ResolveInfo object
         *
         * @since 0.0.5
         * @return array
         */
        $query_args = apply_filters( 'graphql_map_input_fields_to_wp_query', $query_args, $args, $source, $all_args, $context, $info );

        /**
         * Return the Query Args
         */
        return ! empty( $query_args ) && is_array( $query_args ) ? $query_args : [];

    }

}
API documentation generated by ApiGen