| 1 |
<?php |
| 2 |
/** |
| 3 |
* Content |
| 4 |
* |
| 5 |
* @package Wp_Graphql_Smart_Cache |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WPGraphQL\SmartCache; |
| 9 |
|
| 10 |
class Utils { |
| 11 |
|
| 12 |
/** |
| 13 |
* @param string $query_id Query ID |
| 14 |
* @param string|array $type |
| 15 |
* @param string $taxonomy |
| 16 |
* |
| 17 |
* @return \WP_Post|false false when not exist |
| 18 |
*/ |
| 19 |
public static function getPostByTermName( $query_id, $type, $taxonomy ) { |
| 20 |
$wp_query = new \WP_Query( |
| 21 |
[ |
| 22 |
'post_type' => $type, |
| 23 |
'post_status' => 'any', |
| 24 |
'posts_per_page' => 1, |
| 25 |
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query |
| 26 |
'tax_query' => [ |
| 27 |
[ |
| 28 |
'taxonomy' => $taxonomy, |
| 29 |
'field' => 'name', |
| 30 |
'terms' => $query_id, |
| 31 |
], |
| 32 |
], |
| 33 |
] |
| 34 |
); |
| 35 |
// returns an array of post objects. |
| 36 |
$posts = $wp_query->get_posts(); |
| 37 |
if ( empty( $posts ) ) { |
| 38 |
return false; |
| 39 |
} |
| 40 |
|
| 41 |
$post = array_pop( $posts ); |
| 42 |
if ( ! ( $post instanceof \WP_Post ) || ! $post->ID ) { |
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
return $post; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Generate query hash for graphql query string |
| 51 |
* |
| 52 |
* @param string|\GraphQL\Language\AST\DocumentNode $query string or document node |
| 53 |
* |
| 54 |
* @return string $query_id Query string str256 hash |
| 55 |
* |
| 56 |
* @throws \GraphQL\Error\SyntaxError |
| 57 |
*/ |
| 58 |
public static function generateHash( $query ) { |
| 59 |
if ( is_string( $query ) ) { |
| 60 |
$query = \GraphQL\Language\Parser::parse( $query ); |
| 61 |
} |
| 62 |
$printed = \GraphQL\Language\Printer::doPrint( $query ); |
| 63 |
|
| 64 |
return self::getHashFromFormattedString( $printed ); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Generate query hash for graphql query string |
| 69 |
* |
| 70 |
* @param string $query Formatted, normalized query string |
| 71 |
* |
| 72 |
* @return string $query_id Query string str256 hash |
| 73 |
* |
| 74 |
* @throws \GraphQL\Error\SyntaxError |
| 75 |
*/ |
| 76 |
public static function getHashFromFormattedString( $query ) { |
| 77 |
return hash( 'sha256', $query ); |
| 78 |
} |
| 79 |
} |
| 80 |
|