Completed
Push — update/sync-psr4-modules-meta ( b9e4dc )
by Marin
09:21
created

Meta::get_objects_by_id()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 2
dl 0
loc 40
rs 8.6577
c 0
b 0
f 0
1
<?php
2
3
namespace Automattic\Jetpack\Sync\Modules;
4
5
class Meta extends \Jetpack_Sync_Module {
6
	public function name() {
7
		return 'meta';
8
	}
9
10
	/**
11
	 * This implementation of get_objects_by_id() is a bit hacky since we're not passing in an array of meta IDs,
12
	 * but instead an array of post or comment IDs for which to retrieve meta for. On top of that,
13
	 * we also pass in an associative array where we expect there to be 'meta_key' and 'ids' keys present.
14
	 *
15
	 * This seemed to be required since if we have missing meta on WP.com and need to fetch it, we don't know what
16
	 * the meta key is, but we do know that we have missing meta for a given post or comment.
17
	 *
18
	 * @param string $object_type The type of object for which we retrieve meta. Either 'post' or 'comment'
19
	 * @param array  $config Must include 'meta_key' and 'ids' keys
20
	 *
21
	 * @return array
22
	 */
23
	public function get_objects_by_id( $object_type, $config ) {
24
		global $wpdb;
25
26
		$table = _get_meta_table( $object_type );
27
28
		if ( ! $table ) {
29
			return array();
30
		}
31
32
		if ( ! isset( $config['meta_key'] ) || ! isset( $config['ids'] ) || ! is_array( $config['ids'] ) ) {
33
			return array();
34
		}
35
36
		$meta_key         = $config['meta_key'];
37
		$ids              = $config['ids'];
38
		$object_id_column = $object_type . '_id';
39
40
		// Sanitize so that the array only has integer values
41
		$ids_string = implode( ', ', array_map( 'intval', $ids ) );
42
		$metas      = $wpdb->get_results(
43
			$wpdb->prepare(
44
				"SELECT * FROM {$table} WHERE {$object_id_column} IN ( {$ids_string} ) AND meta_key = %s",
45
				$meta_key
46
			)
47
		);
48
49
		$meta_objects = array();
50
		foreach ( (array) $metas as $meta_object ) {
51
			$meta_object                                       = (array) $meta_object;
52
			$meta_objects[ $meta_object[ $object_id_column ] ] = array(
53
				'meta_type'  => $object_type,
54
				'meta_id'    => $meta_object['meta_id'],
55
				'meta_key'   => $meta_key,
56
				'meta_value' => $meta_object['meta_value'],
57
				'object_id'  => $meta_object[ $object_id_column ],
58
			);
59
		}
60
61
		return $meta_objects;
62
	}
63
}
64