Completed
Pull Request — master (#323)
by Jonathan
06:30 queued 03:08
created

Object_Sync_Sf_Mapping::get_fieldmaps()   C

Complexity

Conditions 12
Paths 13

Size

Total Lines 53
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 12
eloc 39
c 2
b 1
f 0
nc 13
nop 3
dl 0
loc 53
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Class file for the Object_Sync_Sf_Mapping class.
4
 *
5
 * @file
6
 */
7
8
if ( ! class_exists( 'Object_Sync_Salesforce' ) ) {
9
	die();
10
}
11
12
/**
13
 * Map objects and records between WordPress and Salesforce
14
 */
15
class Object_Sync_Sf_Mapping {
16
17
	protected $wpdb;
18
	protected $version;
19
	protected $slug;
20
	protected $logging;
21
	protected $option_prefix;
22
23
	protected $fieldmap_table;
24
	protected $object_map_table;
25
26
	public $sync_off;
27
	public $sync_wordpress_create;
28
	public $sync_wordpress_update;
29
	public $sync_wordpress_delete;
30
	public $sync_sf_create;
31
	public $sync_sf_update;
32
	public $sync_sf_delete;
33
	public $wordpress_events;
34
	public $salesforce_events;
35
36
	public $direction_wordpress_sf;
37
	public $direction_sf_wordpress;
38
	public $direction_sync;
39
40
	public $direction_wordpress;
41
	public $direction_salesforce;
42
43
	public $salesforce_default_record_type;
44
45
	public $array_delimiter;
46
	public $array_types_from_salesforce;
47
	public $date_types_from_salesforce;
48
	public $int_types_from_salesforce;
49
50
	public $name_length;
51
52
	public $status_success;
53
	public $status_error;
54
55
	public $debug;
56
57
	/**
58
	 * Constructor which sets up links between the systems
59
	 *
60
	 * @param object $wpdb A WPDB object.
61
	 * @param string $version The plugin version.
62
	 * @param string $slug The plugin slug.
63
	 * @param object $logging Object_Sync_Sf_Logging.
64
	 * @param string $option_prefix The plugin option prefix
65
	 * @throws \Exception
66
	 */
67
	public function __construct( $wpdb, $version, $slug, $logging, $option_prefix = '' ) {
68
		$this->wpdb          = $wpdb;
69
		$this->version       = $version;
70
		$this->slug          = $slug;
71
		$this->option_prefix = isset( $option_prefix ) ? $option_prefix : 'object_sync_for_salesforce_';
72
		$this->logging       = $logging;
73
74
		$this->fieldmap_table   = $this->wpdb->prefix . 'object_sync_sf_field_map';
75
		$this->object_map_table = $this->wpdb->prefix . 'object_sync_sf_object_map';
76
77
		/*
78
		 * These parameters are how we define when syncing should occur on each field map.
79
		 * They get used in the admin settings, as well as the push/pull methods to see if something should happen.
80
		 * It is unclear why the Drupal module used bit flags, but it seems reasonable to keep the convention.
81
		*/
82
		$this->sync_off              = 0x0000;
83
		$this->sync_wordpress_create = 0x0001;
84
		$this->sync_wordpress_update = 0x0002;
85
		$this->sync_wordpress_delete = 0x0004;
86
		$this->sync_sf_create        = 0x0008;
87
		$this->sync_sf_update        = 0x0010;
88
		$this->sync_sf_delete        = 0x0020;
89
90
		// Define which events are initialized by which system.
91
		$this->wordpress_events  = array( $this->sync_wordpress_create, $this->sync_wordpress_update, $this->sync_wordpress_delete );
92
		$this->salesforce_events = array( $this->sync_sf_create, $this->sync_sf_update, $this->sync_sf_delete );
93
94
		// Constants for the directions to map things.
95
		$this->direction_wordpress_sf = 'wp_sf';
96
		$this->direction_sf_wordpress = 'sf_wp';
97
		$this->direction_sync         = 'sync';
98
99
		$this->direction_wordpress  = array( $this->direction_wordpress_sf, $this->direction_sync );
100
		$this->direction_salesforce = array( $this->direction_sf_wordpress, $this->direction_sync );
101
102
		// This is used when we map a record with default or Master.
103
		$this->salesforce_default_record_type = 'default';
104
105
		// Salesforce has multipicklists and they have a delimiter.
106
		$this->array_delimiter = ';';
107
		// What data types in Salesforce should be an array?
108
		$this->array_types_from_salesforce = array( 'multipicklist' );
109
		// What data types in Salesforce should be a date field?
110
		$this->date_types_from_salesforce = array( 'date', 'datetime' );
111
		// What data types in Salesforce should be an integer?
112
		$this->int_types_from_salesforce = array( 'integer', 'boolean' );
113
114
		// Max length for a mapping field.
115
		$this->name_length = 128;
116
117
		// Statuses for object sync.
118
		$this->status_success = 1;
119
		$this->status_error   = 0;
120
121
		$this->debug = get_option( $this->option_prefix . 'debug_mode', false );
122
123
	}
124
125
	/**
126
	 * Create a fieldmap row between a WordPress and Salesforce object
127
	 *
128
	 * @param array $posted The results of $_POST.
129
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
130
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
131
	 * @throws \Exception
132
	 */
133
	public function create_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
134
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
135
		if ( version_compare( $this->version, '1.2.5', '>=' ) ) {
136
			$data['version'] = $this->version;
137
		}
138
		$insert = $this->wpdb->insert( $this->fieldmap_table, $data );
139
		if ( 1 === $insert ) {
140
			return $this->wpdb->insert_id;
141
		} else {
142
			return false;
143
		}
144
	}
145
146
	/**
147
	 * Get one or more fieldmap rows between a WordPress and Salesforce object
148
	 *
149
	 * @param int   $id The ID of a desired mapping.
150
	 * @param array $conditions Array of key=>value to match the mapping by.
151
	 * @param bool  $reset Unused parameter.
152
	 * @return array $map a single mapping or $mappings, an array of mappings.
153
	 * @throws \Exception
154
	 */
155
	public function get_fieldmaps( $id = null, $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

155
	public function get_fieldmaps( $id = null, $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
156
		$table = $this->fieldmap_table;
157
		if ( null !== $id ) { // get one fieldmap.
158
			$map                                    = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = ' . $id, ARRAY_A );
159
			$map['salesforce_record_types_allowed'] = maybe_unserialize( $map['salesforce_record_types_allowed'] );
160
161
			$map['fields']        = maybe_unserialize( $map['fields'] );
162
			$map['sync_triggers'] = maybe_unserialize( $map['sync_triggers'] );
163
			return $map;
164
		} elseif ( ! empty( $conditions ) ) { // get multiple but with a limitation.
165
			$mappings    = array();
166
			$record_type = '';
167
			// Assemble the SQL.
168
			if ( ! empty( $conditions ) ) {
169
				$where = ' WHERE ';
170
				$i     = 0;
171
				foreach ( $conditions as $key => $value ) {
172
					if ( 'salesforce_record_type' === $key ) {
173
						$record_type = sanitize_text_field( $value );
174
					} else {
175
						$i++;
176
						if ( $i > 1 ) {
177
							$where .= ' AND ';
178
						}
179
						$where .= '`' . $key . '` = "' . $value . '"';
180
					}
181
				}
182
			} else {
183
				$where = '';
184
			}
185
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . ' ORDER BY `weight`', ARRAY_A );
186
			if ( ! empty( $mappings ) ) {
187
				$mappings = $this->prepare_fieldmap_data( $mappings, $record_type );
188
			}
189
			return $mappings;
190
		} else {
191
			// get all of the mappings. ALL THE MAPPINGS.
192
			if ( version_compare( $this->version, '1.9.0', '>=' ) ) {
193
				// if the version is greater than or equal to 1.9.0, the fieldmap table has a wordpress_object_default_status column
194
				$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `wordpress_object_default_status`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `pull_to_drafts`, `weight`, `version` FROM $table", ARRAY_A ); // WPCS: unprepared SQL OK.
195
			} elseif ( version_compare( $this->version, '1.5.0', '>=' ) ) {
196
				// if the version is greater than or equal to 1.5.0, the fieldmap table has a pull_to_drafts column
197
				$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `pull_to_drafts`, `weight`, `version` FROM $table", ARRAY_A ); // WPCS: unprepared SQL OK.
198
			} elseif ( version_compare( $this->version, '1.2.5', '>=' ) ) {
199
				// if the version is greater than or equal to 1.2.5, the fieldmap table has a version column
200
				$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `weight`, `version` FROM $table", ARRAY_A ); // WPCS: unprepared SQL OK.
201
			} else {
202
				$mappings = $this->wpdb->get_results( "SELECT `id`, `label`, `wordpress_object`, `salesforce_object`, `salesforce_record_types_allowed`, `salesforce_record_type_default`, `fields`, `pull_trigger_field`, `sync_triggers`, `push_async`, `push_drafts`, `weight` FROM $table", ARRAY_A ); // WPCS: unprepared SQL OK.
203
			}
204
			if ( ! empty( $mappings ) ) {
205
				$mappings = $this->prepare_fieldmap_data( $mappings );
206
			}
207
			return $mappings;
208
		} // End if().
209
	}
210
211
	/**
212
	 * For a mapping, get the fieldmaps associated with it.
213
	 *
214
	 * @param Array $mapping The mapping for which we are getting the fieldmaps.
215
	 * @param Array $directions The direction of the mapping: from WP to SF or vice-versa.
216
	 * @see Object_Sync_Sf_Salesforce_Pull::get_pull_query()
217
	 *
218
	 * @return Array of mapped fields
219
	 */
220
	public function get_mapped_fields( $mapping, $directions = array() ) {
221
		$mapped_fields = array();
222
		foreach ( $mapping['fields'] as $fields ) {
223
			if ( empty( $directions ) || in_array( $fields['direction'], $directions, true ) ) {
224
225
				// in version 1.2.0, we provided an option for API name vs label for Salesforce fields
226
				if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fields['salesforce_field']['name'] ) ) {
227
					$array_key = 'name';
228
				} else {
229
					$array_key = 'label';
230
				}
231
232
				// Some field map types (Relation) store a collection of SF objects.
233
				if ( is_array( $fields['salesforce_field'] ) && ! isset( $fields['salesforce_field'][ $array_key ] ) ) {
234
					foreach ( $fields['salesforce_field'] as $sf_field ) {
235
						$mapped_fields[ $sf_field[ $array_key ] ] = $sf_field[ $array_key ];
236
					}
237
				} else { // The rest are just a name/value pair.
238
					$mapped_fields[ $fields['salesforce_field'][ $array_key ] ] = $fields['salesforce_field'][ $array_key ];
239
				}
240
			}
241
		}
242
243
		if ( ! empty( $this->get_mapped_record_types ) ) {
244
			$mapped_fields['RecordTypeId'] = 'RecordTypeId';
245
		}
246
247
		return $mapped_fields;
248
	}
249
250
	/**
251
	 * Get the mapped record types for a given mapping.
252
	 *
253
	 * @param Array $mapping A mapping from which we wish to estract the record type.
254
	 * @return Array of mappings. Empty if the mapping's record type is default, else full of the record types.
255
	 */
256
	public function get_mapped_record_types( $mapping ) {
257
		return $mapping['salesforce_record_type_default'] === $this->salesforce_default_record_type ? array() : array_filter( maybe_unserialize( $mapping['salesforce_record_types_allowed'] ) );
258
	}
259
260
	/**
261
	 * Update a fieldmap row between a WordPress and Salesforce object
262
	 *
263
	 * @param array $posted It's $_POST.
264
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
265
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
266
	 * @param int   $id The ID of the mapping.
267
	 * @return boolean
268
	 * @throws \Exception
269
	 */
270
	public function update_fieldmap( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array(), $id = '' ) {
271
		$data = $this->setup_fieldmap_data( $posted, $wordpress_fields, $salesforce_fields );
272
		if ( version_compare( $this->version, '1.2.5', '>=' ) && ! isset( $data['updated'] ) ) {
273
			$data['version'] = $this->version;
274
		}
275
		$update = $this->wpdb->update(
276
			$this->fieldmap_table,
277
			$data,
278
			array(
279
				'id' => $id,
280
			)
281
		);
282
		if ( false === $update ) {
283
			return false;
284
		} else {
285
			return true;
286
		}
287
	}
288
289
	/**
290
	 * Setup fieldmap data
291
	 * Sets up the database entry for mapping the object types between Salesforce and WordPress
292
	 *
293
	 * @param array $posted It's $_POST.
294
	 * @param array $wordpress_fields The fields for the WordPress side of the mapping.
295
	 * @param array $salesforce_fields The fields for the Salesforce side of the mapping.
296
	 * @return array $data the fieldmap's data for the database
297
	 */
298
	private function setup_fieldmap_data( $posted = array(), $wordpress_fields = array(), $salesforce_fields = array() ) {
299
		$data = array(
300
			'label'             => $posted['label'],
301
			'name'              => sanitize_title( $posted['label'] ),
302
			'salesforce_object' => $posted['salesforce_object'],
303
			'wordpress_object'  => $posted['wordpress_object'],
304
		);
305
		// added in version 1.9.0.
306
		$data['wordpress_object_default_status'] = isset( $posted['wordpress_object_default_status'] ) ? sanitize_text_field( $posted['wordpress_object_default_status'] ) : '';
307
		if ( isset( $posted['wordpress_field'] ) && is_array( $posted['wordpress_field'] ) && isset( $posted['salesforce_field'] ) && is_array( $posted['salesforce_field'] ) ) {
308
			$setup['fields'] = array();
309
			foreach ( $posted['wordpress_field'] as $key => $value ) {
310
				$method_key = array_search( $value, array_column( $wordpress_fields, 'key' ), true );
311
				if ( ! isset( $posted['direction'][ $key ] ) ) {
312
					$posted['direction'][ $key ] = 'sync';
313
				}
314
				if ( ! isset( $posted['is_prematch'][ $key ] ) ) {
315
					$posted['is_prematch'][ $key ] = false;
316
				}
317
				if ( ! isset( $posted['is_key'][ $key ] ) ) {
318
					$posted['is_key'][ $key ] = false;
319
				}
320
				if ( ! isset( $posted['is_delete'][ $key ] ) ) {
321
					$posted['is_delete'][ $key ] = false;
322
				}
323
				if ( false === $posted['is_delete'][ $key ] ) {
324
					// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
325
					$updateable_key = array_search( $posted['salesforce_field'][ $key ], array_column( $salesforce_fields, 'name' ), true );
326
327
					$salesforce_field_attributes = array();
328
					foreach ( $salesforce_fields[ $updateable_key ] as $sf_key => $sf_value ) {
329
						if ( isset( $sf_value ) && ! is_array( $sf_value ) ) {
330
							$salesforce_field_attributes[ $sf_key ] = esc_attr( $sf_value );
331
						} elseif ( ! empty( $sf_value ) && is_array( $sf_value ) ) {
332
							$salesforce_field_attributes[ $sf_key ] = maybe_unserialize( $sf_value );
0 ignored issues
show
Bug introduced by
$sf_value of type array is incompatible with the type string expected by parameter $original of maybe_unserialize(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

332
							$salesforce_field_attributes[ $sf_key ] = maybe_unserialize( /** @scrutinizer ignore-type */ $sf_value );
Loading history...
333
						} else {
334
							$salesforce_field_attributes[ $sf_key ] = '';
335
						}
336
					}
337
338
					$setup['fields'][ $key ] = array(
339
						'wordpress_field'  => array(
340
							'label'   => sanitize_text_field( $posted['wordpress_field'][ $key ] ),
341
							'methods' => maybe_unserialize( $wordpress_fields[ $method_key ]['methods'] ),
342
							'type'    => isset( $wordpress_fields[ $method_key ]['type'] ) ? sanitize_text_field( $wordpress_fields[ $method_key ]['type'] ) : 'text',
343
						),
344
						'salesforce_field' => $salesforce_field_attributes,
345
						'is_prematch'      => sanitize_text_field( $posted['is_prematch'][ $key ] ),
346
						'is_key'           => sanitize_text_field( $posted['is_key'][ $key ] ),
347
						'direction'        => sanitize_text_field( $posted['direction'][ $key ] ),
348
						'is_delete'        => sanitize_text_field( $posted['is_delete'][ $key ] ),
349
					);
350
351
					// If the WordPress key or the Salesforce key are blank, remove this incomplete mapping.
352
					// This prevents https://github.com/MinnPost/object-sync-for-salesforce/issues/82 .
353
					if (
354
						empty( $setup['fields'][ $key ]['wordpress_field']['label'] )
355
						||
356
						empty( $setup['fields'][ $key ]['salesforce_field']['name'] )
357
					) {
358
						unset( $setup['fields'][ $key ] );
359
					}
360
				}
361
			} // End foreach() on WordPress fields.
362
			$data['fields'] = maybe_serialize( $setup['fields'] );
363
		} elseif ( isset( $posted['fields'] ) && is_array( $posted['fields'] ) ) {
364
			// if $posted['fields'] is already set, use that
365
			$data['fields'] = maybe_serialize( $posted['fields'] );
366
		} // End if() WordPress fields are present.
367
368
		if ( isset( $posted['salesforce_record_types_allowed'] ) ) {
369
			$data['salesforce_record_types_allowed'] = maybe_serialize( $posted['salesforce_record_types_allowed'] );
370
		} else {
371
			$data['salesforce_record_types_allowed'] = maybe_serialize(
372
				array(
373
					$this->salesforce_default_record_type => $this->salesforce_default_record_type,
374
				)
375
			);
376
		}
377
		if ( isset( $posted['salesforce_record_type_default'] ) ) {
378
			$data['salesforce_record_type_default'] = $posted['salesforce_record_type_default'];
379
		} else {
380
			$data['salesforce_record_type_default'] = maybe_serialize( $this->salesforce_default_record_type );
381
		}
382
		if ( isset( $posted['pull_trigger_field'] ) ) {
383
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
384
		}
385
		if ( isset( $posted['sync_triggers'] ) && is_array( $posted['sync_triggers'] ) ) {
386
			$setup['sync_triggers'] = array();
387
			foreach ( $posted['sync_triggers'] as $key => $value ) {
388
				$setup['sync_triggers'][ $key ] = esc_html( $posted['sync_triggers'][ $key ] );
389
			}
390
		} else {
391
			$setup['sync_triggers'] = array();
392
		}
393
		$data['sync_triggers'] = maybe_serialize( $setup['sync_triggers'] );
394
		if ( isset( $posted['pull_trigger_field'] ) ) {
395
			$data['pull_trigger_field'] = $posted['pull_trigger_field'];
396
		}
397
		$data['push_async']     = isset( $posted['push_async'] ) ? $posted['push_async'] : '';
398
		$data['push_drafts']    = isset( $posted['push_drafts'] ) ? $posted['push_drafts'] : '';
399
		$data['pull_to_drafts'] = isset( $posted['pull_to_drafts'] ) ? $posted['pull_to_drafts'] : '';
400
		$data['weight']         = isset( $posted['weight'] ) ? $posted['weight'] : '';
401
		return $data;
402
	}
403
404
	/**
405
	 * Delete a fieldmap row between a WordPress and Salesforce object
406
	 *
407
	 * @param int $id The ID of a field mapping.
408
	 * @return Boolean
409
	 * @throws \Exception
410
	 */
411
	public function delete_fieldmap( $id = '' ) {
412
		$data   = array(
413
			'id' => $id,
414
		);
415
		$delete = $this->wpdb->delete( $this->fieldmap_table, $data );
416
		if ( 1 === $delete ) {
417
			return true;
418
		} else {
419
			return false;
420
		}
421
	}
422
423
	/**
424
	 * Create an object map row between a WordPress and Salesforce object
425
	 *
426
	 * @param array $posted It's $_POST.
427
	 * @return false|Int of field mapping between WordPress and Salesforce objects
428
	 * @throws \Exception
429
	 */
430
	public function create_object_map( $posted = array() ) {
431
		$data            = $this->setup_object_map_data( $posted );
432
		$data['created'] = current_time( 'mysql' );
433
		// Check to see if we don't know the salesforce id and it is not a temporary id, or if this is pending.
434
		// If it is using a temporary id, the map will get updated after it finishes running; it won't call this method unless there's an error, which we should log.
435
		if ( substr( $data['salesforce_id'], 0, 7 ) !== 'tmp_sf_' || ( isset( $data['action'] ) && 'pending' === $data['action'] ) ) {
436
			unset( $data['action'] );
437
			$insert = $this->wpdb->insert( $this->object_map_table, $data );
438
		} else {
439
			$status = 'error';
440
			if ( isset( $this->logging ) ) {
441
				$logging = $this->logging;
442
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
443
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
444
			}
445
			$logging->setup(
446
				sprintf(
447
					// translators: %1$s is the log status, %2$s is the name of a WordPress object. %3$s is the id of that object.
448
					esc_html__( '%1$s Mapping: error caused by trying to map the WordPress %2$s with ID of %3$s to Salesforce ID starting with "tmp_sf_", which is invalid.', 'object-sync-for-salesforce' ),
449
					ucfirst( esc_attr( $status ) ),
450
					esc_attr( $data['wordpress_object'] ),
451
					absint( $data['wordpress_id'] )
452
				),
453
				'',
454
				0,
455
				0,
456
				$status
457
			);
458
			return false;
459
		}
460
		if ( 1 === $insert ) {
461
			return $this->wpdb->insert_id;
462
		} elseif ( false !== strpos( $this->wpdb->last_error, 'Duplicate entry' ) ) {
463
			// this error should never happen now, I think. But let's watch and see.
464
			$mapping = $this->load_all_by_salesforce( $data['salesforce_id'] )[0];
465
			$id      = $mapping['id'];
466
			$status  = 'error';
467
			if ( isset( $this->logging ) ) {
468
				$logging = $this->logging;
469
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
470
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
471
			}
472
			$logging->setup(
473
				sprintf(
474
					// translators: %1$s is the status word "Error". %2$s is the Id of a Salesforce object. %3$s is the ID of a mapping object.
475
					esc_html__( '%1$s: Mapping: there is already a WordPress object mapped to the Salesforce object %2$s and the mapping object ID is %3$s', 'object-sync-for-salesforce' ),
476
					ucfirst( esc_attr( $status ) ),
477
					esc_attr( $data['salesforce_id'] ),
478
					absint( $id )
479
				),
480
				print_r( $mapping, true ), // log whatever we have for the mapping object, so print the array
481
				0,
482
				0,
483
				$status
484
			);
485
			return $id;
486
		} else {
487
			return false;
488
		}
489
	}
490
491
	/**
492
	 * Get all object map rows between WordPress and Salesforce objects.
493
	 *
494
	 * This replaces previous functionality that would return a single object map if there was only one, rather than a multi-dimensional array.
495
	 *
496
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
497
	 * @param bool $reset Unused parameter.
498
	 * @return $mappings
0 ignored issues
show
Documentation Bug introduced by
The doc comment $mappings at position 0 could not be parsed: Unknown type name '$mappings' at position 0 in $mappings.
Loading history...
499
	 */
500
	public function get_all_object_maps( $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

500
	public function get_all_object_maps( $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
501
		$table = $this->object_map_table;
502
		$order = ' ORDER BY object_updated, created';
503
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
504
			$mappings = array();
505
506
			if ( ! empty( $conditions ) ) {
507
				$where = ' WHERE ';
508
				$i     = 0;
509
				foreach ( $conditions as $key => $value ) {
510
					$i++;
511
					if ( $i > 1 ) {
512
						$where .= ' AND ';
513
					}
514
					$where .= '`' . $key . '` = "' . $value . '"';
515
				}
516
			} else {
517
				$where = '';
518
			}
519
520
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
521
		} else { // get all of the mappings. ALL THE MAPPINGS.
522
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
523
		}
524
525
		return $mappings;
526
527
	}
528
529
	/**
530
	 * Get one or more object map rows between WordPress and Salesforce objects
531
	 *
532
	 * @deprecated since 1.8.0
533
	 * @param array $conditions Limitations on the SQL query for object mapping rows.
534
	 * @param bool  $reset Unused parameter.
535
	 * @return array $map or $mappings
536
	 * @throws \Exception
537
	 */
538
	public function get_object_maps( $conditions = array(), $reset = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $reset is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

538
	public function get_object_maps( $conditions = array(), /** @scrutinizer ignore-unused */ $reset = false ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
539
		$table = $this->object_map_table;
540
		$order = ' ORDER BY object_updated, created';
541
		if ( ! empty( $conditions ) ) { // get multiple but with a limitation.
542
			$mappings = array();
543
544
			if ( ! empty( $conditions ) ) {
545
				$where = ' WHERE ';
546
				$i     = 0;
547
				foreach ( $conditions as $key => $value ) {
548
					$i++;
549
					if ( $i > 1 ) {
550
						$where .= ' AND ';
551
					}
552
					$where .= '`' . $key . '` = "' . $value . '"';
553
				}
554
			} else {
555
				$where = '';
556
			}
557
558
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $where . $order, ARRAY_A );
559
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
560
				$mappings = $mappings[0];
561
			}
562
		} else { // get all of the mappings. ALL THE MAPPINGS.
563
			$mappings = $this->wpdb->get_results( 'SELECT * FROM ' . $table . $order, ARRAY_A );
564
			if ( ! empty( $mappings ) && 1 === $this->wpdb->num_rows ) {
565
				$mappings = $mappings[0];
566
			}
567
		}
568
569
		return $mappings;
570
571
	}
572
573
	/**
574
	 * Update an object map row between a WordPress and Salesforce object
575
	 *
576
	 * @param array $posted It's $_POST.
577
	 * @param array $id The ID of the object map row.
578
	 * @return boolean
579
	 * @throws \Exception
580
	 */
581
	public function update_object_map( $posted = array(), $id = '' ) {
582
		$data = $this->setup_object_map_data( $posted );
583
		if ( ! isset( $data['object_updated'] ) ) {
584
			$data['object_updated'] = current_time( 'mysql' );
585
		}
586
		$update = $this->wpdb->update(
587
			$this->object_map_table,
588
			$data,
589
			array(
590
				'id' => $id,
591
			)
592
		);
593
		if ( false === $update ) {
594
			return false;
595
		} else {
596
			return true;
597
		}
598
	}
599
600
	/**
601
	 * Setup the data for the object map
602
	 *
603
	 * @param array $posted It's $_POST.
604
	 * @return array $data Filtered array with only the keys that are in the object map database table. Strips out things from WordPress form if they're present.
605
	 */
606
	private function setup_object_map_data( $posted = array() ) {
607
		$allowed_fields   = $this->wpdb->get_col( "DESC {$this->object_map_table}", 0 );
608
		$allowed_fields[] = 'action'; // we use this in both directions even though it isn't in the database; we remove it from the array later if it is present
609
610
		$data = array_intersect_key( $posted, array_flip( $allowed_fields ) );
611
		return $data;
612
	}
613
614
	/**
615
	 * Delete an object map row between a WordPress and Salesforce object
616
	 *
617
	 * @param int|array $id The ID or IDs of the object map row(s).
618
	 * @return boolean
619
	 * @throws \Exception
620
	 */
621
	public function delete_object_map( $id = '' ) {
622
		if ( is_string( $id ) || is_int( $id ) ) {
623
			$data   = array(
624
				'id' => $id,
625
			);
626
			$delete = $this->wpdb->delete( $this->object_map_table, $data );
627
			if ( 1 === $delete ) {
628
				return true;
629
			} else {
630
				return false;
631
			}
632
		} elseif ( is_array( $id ) ) {
0 ignored issues
show
introduced by
The condition is_array($id) is always true.
Loading history...
633
			$ids    = implode( ',', array_map( 'absint', $id ) );
634
			$delete = $this->wpdb->query( "DELETE FROM $this->object_map_table WHERE ID IN ($ids)" );
635
			if ( false !== $delete ) {
636
				return true;
637
			} else {
638
				return false;
639
			}
640
		}
641
	}
642
643
	/**
644
	 * Generate a temporary ID to store while waiting for a push or pull to complete, before the record has been assigned a new ID
645
	 *
646
	 * @param string $direction Whether this is part of a push or pull action
647
	 * @return string $id is a temporary string that will be replaced if the modification is successful
648
	 */
649
	public function generate_temporary_id( $direction ) {
650
		if ( 'push' === $direction ) {
651
			$prefix = 'tmp_sf_';
652
		} elseif ( 'pull' === $direction ) {
653
			$prefix = 'tmp_wp_';
654
		}
655
		$id = uniqid( $prefix, true );
656
		return $id;
657
	}
658
659
	/**
660
	 * Returns Salesforce object mappings for a given WordPress object.
661
	 *
662
	 * @param string $object_type Type of object to load.
663
	 * @param int    $object_id Unique identifier of the target object to load.
664
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
665
	 *
666
	 * @return SalesforceMappingObject
0 ignored issues
show
Bug introduced by
The type SalesforceMappingObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
667
	 *   The requested SalesforceMappingObject or FALSE if none was found.
668
	 */
669
	public function load_all_by_wordpress( $object_type, $object_id, $reset = false ) {
670
		$conditions = array(
671
			'wordpress_id'     => $object_id,
672
			'wordpress_object' => $object_type,
673
		);
674
		return $this->get_all_object_maps( $conditions, $reset );
675
	}
676
677
	/**
678
	 * Returns one or more Salesforce object mappings for a given WordPress object.
679
	 *
680
	 * @deprecated since 1.8.0
681
	 * @param string $object_type Type of object to load.
682
	 * @param int    $object_id Unique identifier of the target object to load.
683
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
684
	 *
685
	 * @return SalesforceMappingObject
686
	 *   The requested SalesforceMappingObject or FALSE if none was found.
687
	 */
688
	public function load_by_wordpress( $object_type, $object_id, $reset = false ) {
689
		$conditions = array(
690
			'wordpress_id'     => $object_id,
691
			'wordpress_object' => $object_type,
692
		);
693
		return $this->get_object_maps( $conditions, $reset );
0 ignored issues
show
Deprecated Code introduced by
The function Object_Sync_Sf_Mapping::get_object_maps() has been deprecated: since 1.8.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

693
		return /** @scrutinizer ignore-deprecated */ $this->get_object_maps( $conditions, $reset );

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
694
	}
695
696
	/**
697
	 * Returns Salesforce object mappings for a given Salesforce object.
698
	 *
699
	 * @param string $salesforce_id Type of object to load.
700
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
701
	 *
702
	 * @return array $maps all the object maps that match the Salesforce Id
703
	 */
704
	public function load_all_by_salesforce( $salesforce_id, $reset = false ) {
705
		$conditions = array(
706
			'salesforce_id' => $salesforce_id,
707
		);
708
709
		$maps = $this->get_all_object_maps( $conditions, $reset );
710
711
		return $maps;
712
	}
713
714
	/**
715
	 * Returns one or more Salesforce object mappings for a given Salesforce object.
716
	 *
717
	 * @deprecated since 1.8.0
718
	 * @param string $salesforce_id Type of object to load.
719
	 * @param bool   $reset Whether or not the cache should be cleared and fetch from current data.
720
	 *
721
	 * @return array $map
722
	 *   The most recent fieldmap
723
	 */
724
	public function load_by_salesforce( $salesforce_id, $reset = false ) {
725
		$conditions = array(
726
			'salesforce_id' => $salesforce_id,
727
		);
728
729
		$map = $this->get_object_maps( $conditions, $reset );
0 ignored issues
show
Deprecated Code introduced by
The function Object_Sync_Sf_Mapping::get_object_maps() has been deprecated: since 1.8.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

729
		$map = /** @scrutinizer ignore-deprecated */ $this->get_object_maps( $conditions, $reset );

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
730
731
		if ( isset( $map[0] ) && is_array( $map[0] ) && count( $map ) > 1 ) {
732
			$status = 'notice';
733
			$log    = '';
734
			$log   .= 'Mapping: there is more than one mapped WordPress object for the Salesforce object ' . $salesforce_id . '. These WordPress IDs are: ';
735
			$i      = 0;
736
			foreach ( $map as $mapping ) {
737
				$i++;
738
				if ( isset( $mapping['wordpress_id'] ) ) {
739
					$log .= 'object type: ' . $mapping['wordpress_object'] . ', id: ' . $mapping['wordpress_id'];
740
				}
741
				if ( count( $map ) !== $i ) {
742
					$log .= '; ';
743
				} else {
744
					$log .= '.';
745
				}
746
			}
747
			$map = $map[0];
748
			// Create log entry for multiple maps.
749
			if ( isset( $this->logging ) ) {
750
				$logging = $this->logging;
751
			} elseif ( class_exists( 'Object_Sync_Sf_Logging' ) ) {
752
				$logging = new Object_Sync_Sf_Logging( $this->wpdb, $this->version );
753
			}
754
			$logging->setup(
755
				sprintf(
756
					// translators: %1$s is the Id of a Salesforce object.
757
					esc_html__( 'Notice: Mapping: there is more than one mapped WordPress object for the Salesforce object %2$s', 'object-sync-for-salesforce' ),
758
					esc_attr( $salesforce_id )
759
				),
760
				$log,
761
				0,
762
				0,
763
				$status
764
			);
765
		} // End if().
766
767
		return $map;
768
	}
769
770
	/**
771
	 * Map values between WordPress and Salesforce objects.
772
	 *
773
	 * @param array  $mapping The fieldmap that maps these types together.
774
	 * @param array  $object WordPress or Salesforce object data.
775
	 * @param array  $trigger The thing that triggered this mapping.
776
	 * @param bool   $use_soap Flag to enforce use of the SOAP API.
777
	 * @param bool   $is_new Indicates whether a mapping object for this entity already exists.
778
	 * @param string $object_id_field optionally pass the object id field name
779
	 *
780
	 * @return array Associative array of key value pairs.
781
	 */
782
	public function map_params( $mapping, $object, $trigger, $use_soap = false, $is_new = true, $object_id_field = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $is_new is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

782
	public function map_params( $mapping, $object, $trigger, $use_soap = false, /** @scrutinizer ignore-unused */ $is_new = true, $object_id_field = '' ) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
783
784
		$params = array();
785
786
		// these are the triggers that define whether the action was from WordPress or Salesforce.
787
		$wordpress_haystack  = array_values( $this->wordpress_events );
788
		$salesforce_haystack = array_values( $this->salesforce_events );
789
790
		$has_missing_required_salesforce_field = false;
791
		foreach ( $mapping['fields'] as $fieldmap ) {
792
793
			$fieldmap['wordpress_field']['methods'] = maybe_unserialize( $fieldmap['wordpress_field']['methods'] );
794
795
			$wordpress_field = $fieldmap['wordpress_field']['label'];
796
797
			if ( version_compare( $this->version, '1.2.0', '>=' ) && isset( $fieldmap['salesforce_field']['name'] ) ) {
798
				$salesforce_field = $fieldmap['salesforce_field']['name'];
799
				// Load the type of the Salesforce field. We can use this to handle Salesforce field value issues that come up based on what the field sends into WordPress or expects from WordPress.
800
				$salesforce_field_type = $fieldmap['salesforce_field']['type'];
801
			} else {
802
				$salesforce_field = $fieldmap['salesforce_field']['label'];
803
			}
804
805
			// A WordPress event caused this.
806
			if ( in_array( $trigger, array_values( $wordpress_haystack ), true ) ) {
807
808
				// Is the field in WordPress an array, if we unserialize it? Salesforce wants it to be an imploded string.
809
				if ( is_array( maybe_unserialize( $object[ $wordpress_field ] ) ) ) {
810
					// if the WordPress field is a list of capabilities (the source field is wp_capabilities), we need to get the array keys from WordPress to send them to Salesforce.
811
					if ( 'wp_capabilities' === $wordpress_field ) {
812
						$object[ $wordpress_field ] = implode( $this->array_delimiter, array_keys( $object[ $wordpress_field ] ) );
813
					} else {
814
						$object[ $wordpress_field ] = implode( $this->array_delimiter, $object[ $wordpress_field ] );
815
					}
816
				}
817
818
				if ( isset( $salesforce_field_type ) ) {
819
					// Is the Salesforce field a date, and is the WordPress value a valid date?
820
					// According to https://salesforce.stackexchange.com/questions/57032/date-format-with-salesforce-rest-api
821
					if ( in_array( $salesforce_field_type, $this->date_types_from_salesforce ) ) {
822
						if ( '' === $object[ $wordpress_field ] ) {
823
							$object[ $wordpress_field ] = null;
824
						} else {
825
							if ( false !== strtotime( $object[ $wordpress_field ] ) ) {
826
								$timestamp = strtotime( $object[ $wordpress_field ] );
827
							} else {
828
								$timestamp = $object[ $wordpress_field ];
829
							}
830
							if ( 'datetime' === $salesforce_field_type ) {
831
								$object[ $wordpress_field ] = date_i18n( 'c', $timestamp );
832
							} else {
833
								$object[ $wordpress_field ] = date_i18n( 'Y-m-d', $timestamp );
834
							}
835
						}
836
					}
837
838
					// Boolean SF fields only want real boolean values. NULL is also not allowed.
839
					if ( 'boolean' === $salesforce_field_type ) {
840
						$object[ $wordpress_field ] = (bool) $object[ $wordpress_field ];
841
					}
842
				}
843
844
				$params[ $salesforce_field ] = $object[ $wordpress_field ];
845
846
				// If the field is a key in Salesforce, remove it from $params to avoid upsert errors from Salesforce,
847
				// but still put its name in the params array so we can check for it later.
848
				if ( '1' === $fieldmap['is_key'] ) {
849
					if ( ! $use_soap ) {
850
						unset( $params[ $salesforce_field ] );
851
					}
852
					$params['key'] = array(
853
						'salesforce_field' => $salesforce_field,
854
						'wordpress_field'  => $wordpress_field,
855
						'value'            => $object[ $wordpress_field ],
856
					);
857
				}
858
859
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
860
				if ( '1' === $fieldmap['is_prematch'] ) {
861
					$params['prematch'] = array(
862
						'salesforce_field' => $salesforce_field,
863
						'wordpress_field'  => $wordpress_field,
864
						'value'            => $object[ $wordpress_field ],
865
					);
866
				}
867
868
				// Skip fields that aren't being pushed to Salesforce.
869
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_wordpress ), true ) ) {
870
					// The trigger is a WordPress trigger, but the fieldmap direction is not a WordPress direction.
871
					unset( $params[ $salesforce_field ] );
872
				}
873
874
				// I think it's good to over-mention that updateable is really how the Salesforce api spells it.
875
				// Skip fields that aren't updateable when mapping params because Salesforce will error otherwise.
876
				// This happens after dealing with the field types because key and prematch should still be available to the plugin, even if the values are not updateable in Salesforce.
877
				if ( 1 !== (int) $fieldmap['salesforce_field']['updateable'] ) {
878
					unset( $params[ $salesforce_field ] );
879
				}
880
881
				// This case means the following:
882
				//    this field is expected by the fieldmap
883
				//    Salesforce's api reports that this field is required
884
				//    we do not have a WordPress value for this field, or it's empty
885
				//    it also means the field has not been unset by prematch, updateable, key, or directional flags prior to this check.
886
				// When this happens, we should flag that we're missing a required Salesforce field
887
				if ( in_array( $salesforce_field, $params ) && false === filter_var( $fieldmap['salesforce_field']['nillable'], FILTER_VALIDATE_BOOLEAN ) && ( ! isset( $object[ $wordpress_field ] ) || '' === $object[ $wordpress_field ] ) ) {
888
					$has_missing_required_salesforce_field = true;
889
				}
890
891
				// we don't need a continue with the unset methods because there's no array being created down here
892
			} elseif ( in_array( $trigger, $salesforce_haystack, true ) ) {
893
894
				// A Salesforce event caused this.
895
896
				if ( isset( $salesforce_field_type ) && isset( $object[ $salesforce_field ] ) && ! is_null( $object[ $salesforce_field ] ) ) {
897
					// Salesforce provides multipicklist values as a delimited string. If the
898
					// destination field in WordPress accepts multiple values, explode the string into an array and then serialize it.
899
					if ( in_array( $salesforce_field_type, $this->array_types_from_salesforce ) ) {
900
						$object[ $salesforce_field ] = explode( $this->array_delimiter, $object[ $salesforce_field ] );
901
						// if the WordPress field is a list of capabilities (the destination field is wp_capabilities), we need to set the array for WordPress to save it.
902
						if ( 'wp_capabilities' === $wordpress_field ) {
903
							$capabilities = array();
904
							foreach ( $object[ $salesforce_field ] as $capability ) {
905
								$capabilities[ $capability ] = true;
906
							}
907
							$object[ $salesforce_field ] = $capabilities;
908
						}
909
					}
910
911
					// Handle specific data types from Salesforce.
912
					switch ( $salesforce_field_type ) {
913
						case ( in_array( $salesforce_field_type, $this->date_types_from_salesforce ) ):
914
							$format = get_option( 'date_format', 'U' );
915
							if ( isset( $fieldmap['wordpress_field']['type'] ) && 'datetime' === $fieldmap['wordpress_field']['type'] ) {
916
								$format = 'Y-m-d H:i:s';
917
							}
918
							if ( 'tribe_events' === $mapping['wordpress_object'] && class_exists( 'Tribe__Events__Main' ) ) {
919
								$format = 'Y-m-d H:i:s';
920
							}
921
							if ( 'datetime' === $salesforce_field_type ) {
922
								// Note: the Salesforce REST API appears to always return datetimes as GMT values. We should retrieve them that way, then format them to deal with them in WordPress appropriately.
923
								// We should not do any converting unless it's a datetime, because if it's a date, Salesforce stores it as midnight. We don't want to convert that.
924
								$object[ $salesforce_field ] = get_date_from_gmt( $object[ $salesforce_field ], 'Y-m-d\TH:i:s\Z' ); // convert from GMT to local date/time based on WordPress time zone setting.
925
							}
926
							$object[ $salesforce_field ] = date_i18n( $format, strtotime( $object[ $salesforce_field ] ) );
927
							break;
928
						case ( in_array( $salesforce_field_type, $this->int_types_from_salesforce ) ):
929
							$object[ $salesforce_field ] = isset( $object[ $salesforce_field ] ) ? (int) $object[ $salesforce_field ] : 0;
930
							break;
931
						case 'text':
932
							$object[ $salesforce_field ] = (string) $object[ $salesforce_field ];
933
							break;
934
						case 'url':
935
							$object[ $salesforce_field ] = esc_url_raw( $object[ $salesforce_field ] );
936
							break;
937
					}
938
				}
939
940
				// Make an array because we need to store the methods for each field as well.
941
				if ( isset( $object[ $salesforce_field ] ) && '' !== $object[ $salesforce_field ] ) {
942
					$params[ $wordpress_field ]          = array();
943
					$params[ $wordpress_field ]['value'] = $object[ $salesforce_field ];
944
				} else {
945
					// If we try to save certain fields with empty values, WordPress will silently start skipping stuff. This keeps that from happening.
946
					continue;
947
				}
948
949
				// If the field is a key in Salesforce, disregard since this is caused by a Salesforce event. We're setting up data to be stored in WordPress here, and WordPress is not concerned with external key designations in Salesforce.
950
951
				// If the field is a prematch in Salesforce, put its name in the params array so we can check for it later.
952
				if ( '1' === $fieldmap['is_prematch'] ) {
953
					$params['prematch'] = array(
954
						'salesforce_field' => $salesforce_field,
955
						'wordpress_field'  => $wordpress_field,
956
						'value'            => $object[ $salesforce_field ],
957
						'method_match'     => isset( $fieldmap['wordpress_field']['methods']['match'] ) ? $fieldmap['wordpress_field']['methods']['match'] : $fieldmap['wordpress_field']['methods']['read'],
958
						'method_read'      => $fieldmap['wordpress_field']['methods']['read'],
959
						'method_create'    => $fieldmap['wordpress_field']['methods']['create'],
960
						'method_update'    => $fieldmap['wordpress_field']['methods']['update'],
961
					);
962
				}
963
964
				// Skip fields that aren't being pulled from Salesforce.
965
				if ( ! in_array( $fieldmap['direction'], array_values( $this->direction_salesforce ), true ) ) {
966
					// The trigger is a Salesforce trigger, but the fieldmap direction is not a Salesforce direction.
967
					unset( $params[ $wordpress_field ] );
968
					// we also need to continue here, so it doesn't create an empty array below for fields that are WordPress -> Salesforce only
969
					continue;
970
				}
971
972
				switch ( $trigger ) {
973
					case $this->sync_sf_create:
974
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['create'];
975
						break;
976
					case $this->sync_sf_update:
977
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['update'];
978
						break;
979
					case $this->sync_sf_delete:
980
						$params[ $wordpress_field ]['method_modify'] = $fieldmap['wordpress_field']['methods']['delete'];
981
						break;
982
				}
983
984
				$params[ $wordpress_field ]['method_read'] = $fieldmap['wordpress_field']['methods']['read'];
985
986
			} // End if().
987
		} // End foreach().
988
989
		if ( true === $has_missing_required_salesforce_field ) {
990
			update_option( $this->option_prefix . 'missing_required_data_id_' . $object[ $object_id_field ], true, false );
991
			return array();
992
		}
993
994
		return $params;
995
996
	}
997
998
	/**
999
	 * Prepare field map data for use
1000
	 *
1001
	 * @param array  $mappings Array of fieldmaps.
1002
	 * @param string $record_type Optional Salesforce record type to see if it is allowed or not.
1003
	 *
1004
	 * @return array $mappings Associative array of field maps ready to use
1005
	 */
1006
	private function prepare_fieldmap_data( $mappings, $record_type = '' ) {
1007
1008
		foreach ( $mappings as $id => $mapping ) {
1009
			$mappings[ $id ]['salesforce_record_types_allowed'] = maybe_unserialize( $mapping['salesforce_record_types_allowed'] );
1010
			$mappings[ $id ]['fields']                          = maybe_unserialize( $mapping['fields'] );
1011
			$mappings[ $id ]['sync_triggers']                   = maybe_unserialize( $mapping['sync_triggers'] );
1012
			if ( '' !== $record_type && ! in_array( $record_type, $mappings[ $id ]['salesforce_record_types_allowed'], true ) ) {
1013
				unset( $mappings[ $id ] );
1014
			}
1015
		}
1016
1017
		return $mappings;
1018
1019
	}
1020
1021
	/**
1022
	 * Check object map table to see if there have been any failed object map create attempts
1023
	 *
1024
	 * @return array $errors Associative array of rows that failed to finish from either system
1025
	 */
1026
	public function get_failed_object_maps() {
1027
		$table       = $this->object_map_table;
1028
		$errors      = array();
1029
		$push_errors = $this->wpdb->get_results( 'SELECT * FROM ' . $table . ' WHERE salesforce_id LIKE "tmp_sf_%"', ARRAY_A );
1030
		$pull_errors = $this->wpdb->get_results( 'SELECT * FROM ' . $table . ' WHERE wordpress_id LIKE "tmp_wp_%"', ARRAY_A );
1031
		if ( ! empty( $push_errors ) ) {
1032
			$errors['push_errors'] = $push_errors;
1033
		}
1034
		if ( ! empty( $pull_errors ) ) {
1035
			$errors['pull_errors'] = $pull_errors;
1036
		}
1037
		return $errors;
1038
	}
1039
1040
	/**
1041
	 * Check object map table to see if there have been any failed object map create attempts
1042
	 *
1043
	 * @param int   $id The ID of a desired mapping.
1044
	 *
1045
	 * @return array $error Associative array of single row that failed to finish based on id
1046
	 */
1047
	public function get_failed_object_map( $id ) {
1048
		$table     = $this->object_map_table;
1049
		$error     = array();
1050
		$error_row = $this->wpdb->get_row( 'SELECT * FROM ' . $table . ' WHERE id = "' . $id . '"', ARRAY_A );
1051
		if ( ! empty( $error_row ) ) {
1052
			$error = $error_row;
1053
		}
1054
		return $error;
1055
	}
1056
1057
}
1058