| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPGraphQL\Data\Loader; |
| 4 |
|
| 5 |
use WPGraphQL\Model\Menu; |
| 6 |
use WPGraphQL\Model\Term; |
| 7 |
|
| 8 |
/** |
| 9 |
* Class TermObjectLoader |
| 10 |
* |
| 11 |
* @package WPGraphQL\Data\Loader |
| 12 |
*/ |
| 13 |
class TermObjectLoader extends AbstractDataLoader { |
| 14 |
|
| 15 |
/** |
| 16 |
* {@inheritDoc} |
| 17 |
* |
| 18 |
* @param mixed|\WP_Term $entry The Term Object |
| 19 |
* |
| 20 |
* @return \WPGraphQL\Model\Term|\WPGraphQL\Model\Menu|null |
| 21 |
* @throws \Exception |
| 22 |
*/ |
| 23 |
protected function get_model( $entry, $key ) { |
| 24 |
if ( is_a( $entry, 'WP_Term' ) ) { |
| 25 |
|
| 26 |
/** |
| 27 |
* For nav_menu terms, we want to pass through a different model |
| 28 |
*/ |
| 29 |
if ( 'nav_menu' === $entry->taxonomy ) { |
| 30 |
$menu = new Menu( $entry ); |
| 31 |
if ( empty( $menu->fields ) ) { |
| 32 |
return null; |
| 33 |
} else { |
| 34 |
return $menu; |
| 35 |
} |
| 36 |
} else { |
| 37 |
$term = new Term( $entry ); |
| 38 |
if ( empty( $term->fields ) ) { |
| 39 |
return null; |
| 40 |
} else { |
| 41 |
return $term; |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
return null; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* {@inheritDoc} |
| 50 |
* |
| 51 |
* @param int[] $keys |
| 52 |
* |
| 53 |
* @return array<int,\WP_Term|\WP_Error|null> |
| 54 |
*/ |
| 55 |
public function loadKeys( array $keys ) { |
| 56 |
if ( empty( $keys ) ) { |
| 57 |
return $keys; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Prepare the args for the query. We're provided a specific set of IDs for terms, |
| 62 |
* so we want to query as efficiently as possible with as little overhead as possible. |
| 63 |
*/ |
| 64 |
$args = [ |
| 65 |
'include' => $keys, |
| 66 |
'number' => count( $keys ), |
| 67 |
'orderby' => 'include', |
| 68 |
'hide_empty' => false, |
| 69 |
]; |
| 70 |
|
| 71 |
/** |
| 72 |
* Execute the query. This adds the terms to the cache |
| 73 |
*/ |
| 74 |
$query = new \WP_Term_Query( $args ); |
| 75 |
$terms = $query->get_terms(); |
| 76 |
|
| 77 |
if ( empty( $terms ) || ! is_array( $terms ) ) { |
| 78 |
return []; |
| 79 |
} |
| 80 |
|
| 81 |
$loaded = []; |
| 82 |
|
| 83 |
/** |
| 84 |
* Loop over the keys and return an array of loaded_terms, where the key is the ID and the value is |
| 85 |
* the Term passed through the Model layer |
| 86 |
*/ |
| 87 |
foreach ( $keys as $key ) { |
| 88 |
|
| 89 |
/** |
| 90 |
* The query above has added our objects to the cache, so now we can pluck |
| 91 |
* them from the cache to pass through the model layer, or return null if the |
| 92 |
* object isn't in the cache, meaning it didn't come back when queried. |
| 93 |
*/ |
| 94 |
$loaded[ $key ] = get_term( (int) $key ); |
| 95 |
} |
| 96 |
|
| 97 |
return $loaded; |
| 98 |
} |
| 99 |
} |
| 100 |
|