-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathWP_Post_IDs_Iterator.php
More file actions
110 lines (95 loc) · 2.09 KB
/
WP_Post_IDs_Iterator.php
File metadata and controls
110 lines (95 loc) · 2.09 KB
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
<?php
/**
* @implements \Iterator<int, object{}>
*/
class WP_Post_IDs_Iterator implements Iterator {
/**
* @var \wpdb
*/
private $db;
/**
* @var int
*/
private $limit = 100;
/**
* @var int[]
*/
private $post_ids;
/**
* @var int[]
*/
private $ids_left;
/**
* @var object[]
*/
private $results = array();
/**
* @var int
*/
private $index_in_results;
/**
* @var int
*/
private $global_index;
public function __construct( $post_ids, $limit = null ) {
/**
* @var \wpdb $wpdb
*/
global $wpdb;
$this->db = $wpdb;
$this->post_ids = $post_ids;
$this->ids_left = $post_ids;
if ( ! is_null( $limit ) ) {
$this->limit = $limit;
}
}
#[\ReturnTypeWillChange]
public function current() {
return $this->results[ $this->index_in_results ];
}
#[\ReturnTypeWillChange]
public function key() {
return $this->global_index;
}
#[\ReturnTypeWillChange]
public function next() {
++$this->index_in_results;
++$this->global_index;
}
#[\ReturnTypeWillChange]
public function rewind() {
$this->results = array();
$this->global_index = 0;
$this->index_in_results = 0;
$this->ids_left = $this->post_ids;
}
#[\ReturnTypeWillChange]
public function valid() {
if ( isset( $this->results[ $this->index_in_results ] ) ) {
return true;
}
if ( empty( $this->ids_left ) ) {
return false;
}
$has_posts = $this->load_next_posts_from_db();
if ( ! $has_posts ) {
return false;
}
$this->index_in_results = 0;
return true;
}
private function load_next_posts_from_db() {
$next_batch_post_ids = array_splice( $this->ids_left, 0, $this->limit );
$in_post_ids_sql = _wp_export_build_IN_condition( 'ID', $next_batch_post_ids );
$results = $this->db->get_results( "SELECT * FROM {$this->db->posts} WHERE {$in_post_ids_sql}" );
$this->results = is_array( $results ) ? $results : array();
if ( ! $this->results ) {
if ( $this->db->last_error ) {
throw new WP_Iterator_Exception( "Database error: {$this->db->last_error}" );
} else {
return false;
}
}
return true;
}
}