Completed
Push — fix/12791-track-upgrade ( 62035b...97a755 )
by
unknown
26:48 queued 17:41
created

Module::enqueue_full_sync_actions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 4
c 0
b 0
f 0
cc 1
nop 3
rs 10
1
<?php
2
3
namespace Automattic\Jetpack\Sync\Modules;
4
5
use Automattic\Jetpack\Sync\Listener;
6
7
/**
8
 * Basic methods implemented by Jetpack Sync extensions
9
 */
10
abstract class Module {
11
	const ARRAY_CHUNK_SIZE = 10;
12
13
	abstract public function name();
14
15
	public function get_object_by_id( $object_type, $id ) {
16
		return false;
17
	}
18
19
	// override these to set up listeners and set/reset data/defaults
20
	public function init_listeners( $callable ) {
21
	}
22
23
	public function init_full_sync_listeners( $callable ) {
24
	}
25
26
	public function init_before_send() {
27
	}
28
29
	public function set_defaults() {
30
	}
31
32
	public function reset_data() {
33
	}
34
35
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
36
		// in subclasses, return the number of actions enqueued, and next module state (true == done)
37
		return array( null, true );
38
	}
39
40
	public function estimate_full_sync_actions( $config ) {
41
		// in subclasses, return the number of items yet to be enqueued
42
		return null;
43
	}
44
45
	public function get_full_sync_actions() {
46
		return array();
47
	}
48
49
	protected function count_actions( $action_names, $actions_to_count ) {
50
		return count( array_intersect( $action_names, $actions_to_count ) );
51
	}
52
53
	protected function get_check_sum( $values ) {
54
		return crc32( wp_json_encode( jetpack_json_wrap( $values ) ) );
55
	}
56
57
	protected function still_valid_checksum( $sums_to_check, $name, $new_sum ) {
58
		if ( isset( $sums_to_check[ $name ] ) && $sums_to_check[ $name ] === $new_sum ) {
59
			return true;
60
		}
61
62
		return false;
63
	}
64
65
	protected function enqueue_all_ids_as_action( $action_name, $table_name, $id_field, $where_sql, $max_items_to_enqueue, $state ) {
66
		global $wpdb;
67
68
		if ( ! $where_sql ) {
69
			$where_sql = '1 = 1';
70
		}
71
72
		$items_per_page        = 1000;
73
		$page                  = 1;
74
		$chunk_count           = 0;
75
		$previous_interval_end = $state ? $state : '~0';
76
		$listener              = Listener::get_instance();
77
78
		// count down from max_id to min_id so we get newest posts/comments/etc first
79
		while ( $ids = $wpdb->get_col( "SELECT {$id_field} FROM {$table_name} WHERE {$where_sql} AND {$id_field} < {$previous_interval_end} ORDER BY {$id_field} DESC LIMIT {$items_per_page}" ) ) {
80
			// Request posts in groups of N for efficiency
81
			$chunked_ids = array_chunk( $ids, self::ARRAY_CHUNK_SIZE );
82
83
			// if we hit our row limit, process and return
84
			if ( $chunk_count + count( $chunked_ids ) >= $max_items_to_enqueue ) {
85
				$remaining_items_count                      = $max_items_to_enqueue - $chunk_count;
86
				$remaining_items                            = array_slice( $chunked_ids, 0, $remaining_items_count );
87
				$remaining_items_with_previous_interval_end = $this->get_chunks_with_preceding_end( $remaining_items, $previous_interval_end );
88
				$listener->bulk_enqueue_full_sync_actions( $action_name, $remaining_items_with_previous_interval_end );
89
90
				$last_chunk = end( $remaining_items );
91
				return array( $remaining_items_count + $chunk_count, end( $last_chunk ) );
92
			}
93
			$chunked_ids_with_previous_end = $this->get_chunks_with_preceding_end( $chunked_ids, $previous_interval_end );
94
95
			$listener->bulk_enqueue_full_sync_actions( $action_name, $chunked_ids_with_previous_end );
96
97
			$chunk_count += count( $chunked_ids );
98
			$page        += 1;
99
			// $ids are ordered in descending order
100
			$previous_interval_end = end( $ids );
101
		}
102
103
		return array( $chunk_count, true );
104
	}
105
106
	private function get_chunks_with_preceding_end( $chunks, $previous_interval_end ) {
107
		foreach ( $chunks as $chunk ) {
108
			$chunks_with_ends[] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$chunks_with_ends was never initialized. Although not strictly required by PHP, it is generally a good practice to add $chunks_with_ends = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
109
				'ids'          => $chunk,
110
				'previous_end' => $previous_interval_end,
111
			);
112
			// Chunks are ordered in descending order
113
			$previous_interval_end = end( $chunk );
114
		}
115
		return $chunks_with_ends;
0 ignored issues
show
Bug introduced by
The variable $chunks_with_ends does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
116
	}
117
118
	protected function get_metadata( $ids, $meta_type, $meta_key_whitelist ) {
119
		global $wpdb;
120
		$table = _get_meta_table( $meta_type );
121
		$id    = $meta_type . '_id';
122
		if ( ! $table ) {
123
			return array();
124
		}
125
126
		$private_meta_whitelist_sql = "'" . implode( "','", array_map( 'esc_sql', $meta_key_whitelist ) ) . "'";
127
128
		return array_map(
129
			array( $this, 'unserialize_meta' ),
130
			$wpdb->get_results(
131
				"SELECT $id, meta_key, meta_value, meta_id FROM $table WHERE $id IN ( " . implode( ',', wp_parse_id_list( $ids ) ) . ' )' .
132
				" AND meta_key IN ( $private_meta_whitelist_sql ) ",
133
				OBJECT
134
			)
135
		);
136
	}
137
138
	public function init_listeners_for_meta_type( $meta_type, $callable ) {
139
		add_action( "added_{$meta_type}_meta", $callable, 10, 4 );
140
		add_action( "updated_{$meta_type}_meta", $callable, 10, 4 );
141
		add_action( "deleted_{$meta_type}_meta", $callable, 10, 4 );
142
	}
143
144
	public function init_meta_whitelist_handler( $meta_type, $whitelist_handler ) {
145
		add_filter( "jetpack_sync_before_enqueue_added_{$meta_type}_meta", $whitelist_handler );
146
		add_filter( "jetpack_sync_before_enqueue_updated_{$meta_type}_meta", $whitelist_handler );
147
		add_filter( "jetpack_sync_before_enqueue_deleted_{$meta_type}_meta", $whitelist_handler );
148
	}
149
150
	protected function get_term_relationships( $ids ) {
151
		global $wpdb;
152
153
		return $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id IN ( " . implode( ',', wp_parse_id_list( $ids ) ) . ' )', OBJECT );
154
	}
155
156
	public function unserialize_meta( $meta ) {
157
		$meta->meta_value = maybe_unserialize( $meta->meta_value );
158
		return $meta;
159
	}
160
161
	public function get_objects_by_id( $object_type, $ids ) {
162
		if ( empty( $ids ) || empty( $object_type ) ) {
163
			return array();
164
		}
165
166
		$objects = array();
167
		foreach ( (array) $ids as $id ) {
168
			$object = $this->get_object_by_id( $object_type, $id );
169
170
			// Only add object if we have the object.
171
			if ( $object ) {
172
				$objects[ $id ] = $object;
173
			}
174
		}
175
176
		return $objects;
177
	}
178
}
179