Completed
Branch BETA-4.9-message-activity (c2a8e0)
by
unknown
18:28 queued 10s
created

EEM_Base::ensure_is_obj()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 41
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
dl 0
loc 41
rs 4.909
c 3
b 2
f 0
cc 9
eloc 28
nc 7
nop 2
1
<?php
2
/**
3
 *
4
 * Class EEM_Base
5
 *
6
 * Multi-table model. Especially handles joins when querying.
7
 * An important note about values dealt with in models and model objects:
8
 * values used by models exist in basically 3 different domains, which the EE_Model_Fields help convert between:
9
 * 1. Client-code values (eg, controller code may refer to a date as "March 21, 2013")
10
 * 2. Model object values (eg, after the model object has called set() on the value and saves it onto the model object, it may become a unix timestamp, eg 12312412412)
11
 * 3. Database values (eg, we may later decide to store dates as mysql dates, in which case they'd be stored as '2013-03-21 00:00:00')
12
 * Sometimes these values are the same, but often they are not. When your client code is using a model's functions, you need to be aware
13
 * which domain your data exists in. If it is client-code values (ie, it hasn't had a EE_Model_Field call prepare_for_set on it) then use the
14
 * model functions as normal. However, if you are calling the model functions with values from the model object domain (ie, the code your writing is
15
 * probably within a model object, and all the values you're dealing with have had an EE_Model_Field call prepare_for_set on them), then you'll want
16
 * to set $values_already_prepared_by_model_object to FALSE within the argument-list of the functions you call (in order to avoid re-processing those values).
17
 * If your values are already in the database values domain, you'll either way to convert them into the model object domain by creating model objects
18
 * from those raw db values (ie,using EEM_Base::_create_objects), or just use $wpdb directly.
19
 *
20
 * @package 			Event Espresso
21
 * @subpackage 	core
22
 * @author 				Michael Nelson
23
 * @since 				EE4
24
 *
25
 */
26
abstract class EEM_Base extends EE_Base{
27
28
	//admin posty
29
	//basic -> grants access to mine -> if they don't have it, select none
30
	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
31
	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
32
	//*_published -> grants access to published -> if they dont have it, select non-published
33
	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
34
	//publish_{thing} -> can change status TO publish; SPECIAL CASE
35
36
37
	//frontend posty
38
	//by default has access to published
39
	//basic -> grants access to mine that arent published, and all published
40
	//*_others ->grants access to others that arent private, all mine
41
	//*_private -> grants full access
42
43
	//frontend non-posty
44
	//like admin posty
45
46
	//category-y
47
	//assign -> grants access to join-table
48
	//(delete, edit)
49
50
	//payment-method-y
51
	//for each registered payment method,
52
	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
53
54
	/**
55
	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
56
	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
57
	 * They almost always WILL NOT, but it's not necessarily a requirement.
58
	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
59
	 * @var boolean
60
	 */
61
	private $_values_already_prepared_by_model_object = 0;
62
63
	/**
64
	 * when $_values_already_prepared_by_model_object equals this, we assume
65
	 * the data is just like form input that needs to have the model fields'
66
	 * prepare_for_set and prepare_for_use_in_db called on it
67
	 */
68
	const not_prepared_by_model_object = 0;
69
	/**
70
	 * when $_values_already_prepared_by_model_object equals this, we
71
	 * assume this value is coming from a model object and doesn't need to have
72
	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
	 */
74
	const prepared_by_model_object = 1;
75
	/**
76
	 * when $_values_already_prepared_by_model_object equals this, we assume
77
	 * the values are already to be used in the database (ie no processing is done
78
	 * on them by the model's fields)
79
	 */
80
	const prepared_for_use_in_db = 2;
81
82
83
	protected $singular_item = 'Item';
84
	protected $plural_item = 'Items';
85
86
	/**
87
	 * @type \EE_Table_Base[] $_tables  array of EE_Table objects for defining which tables comprise this model.
88
	 */
89
	protected $_tables;
90
91
	/**
92
	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
93
	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be variable names
94
	 * on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
95
	 *
96
	 * @var \EE_Model_Field_Base[] $_fields
97
	 */
98
	protected $_fields;
99
100
	/**
101
	 * array of different kinds of relations
102
	 *
103
	 * @var \EE_Model_Relation_Base[] $_model_relations
104
	 */
105
	protected $_model_relations;
106
107
	/**
108
	 *
109
	 * @var \EE_Index[] $_indexes
110
	 */
111
	protected $_indexes = array();
112
113
	/**
114
	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
	 * by setting the same columns as used in these queries in the query yourself.
117
	 *
118
	 * @var EE_Default_Where_Conditions
119
	 */
120
	protected $_default_where_conditions_strategy;
121
122
	/**
123
	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
	 * This is particularly useful when you want something between 'none' and 'default'
125
	 * @var EE_Default_Where_Conditions
126
	 */
127
	protected $_minimum_where_conditions_strategy;
128
129
	/**
130
	 * String describing how to find the "owner" of this model's objects.
131
	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
132
	 * But when there isn't, this indicates which related model, or transiently-related model,
133
	 * has the foreign key to the wp_users table.
134
	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
135
	 * related to events, and events have a foreign key to wp_users.
136
	 * On EEM_Transaction, this would be 'Transaction.Event'
137
	 * @var string
138
	 */
139
	protected $_model_chain_to_wp_user = '';
140
	/**
141
	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates don't need it (particularly CPT models)
142
	 * @var bool
143
	 */
144
	protected $_ignore_where_strategy = FALSE;
145
146
	/**
147
	 * String used in caps relating to this model. Eg, if the caps relating to this
148
	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
149
	 * @var string. If null it hasn't been initialized yet. If false then we
150
	 * have indicated capabilities don't apply to this
151
	 */
152
	protected $_caps_slug = null;
153
154
	/**
155
	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
156
	 * and next-level keys are capability names, and each's value is a
157
	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
158
	 * they specify which context to use (ie, frontend, backend, edit or delete)
159
	 * and then each capability in the corresponding sub-array that they're missing
160
	 * adds the where conditions onto the query.
161
	 * @var array
162
	 */
163
	protected $_cap_restrictions = array(
164
		self::caps_read => array(),
165
		self::caps_read_admin => array(),
166
		self::caps_edit => array(),
167
		self::caps_delete => array()
168
	);
169
170
	/**
171
	 * Array defining which cap restriction generators to use to create default
172
	 * cap restrictions to put in EEM_Base::_cap_restrictions.
173
	 *
174
	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
175
	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
176
	 * automatically set this to false (not just null).
177
	 * @var EE_Restriction_Generator_Base[]
178
	 */
179
	protected $_cap_restriction_generators = array();
180
181
	/**
182
	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
183
	 */
184
	const caps_read = 'read';
185
	const caps_read_admin = 'read_admin';
186
	const caps_edit = 'edit';
187
	const caps_delete = 'delete';
188
189
	/**
190
	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
191
	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
192
	 * maps to 'read' because when looking for relevant permissions we're going to use
193
	 * 'read' in teh capabilities names like 'ee_read_events' etc.
194
	 * @var array
195
	 */
196
	protected $_cap_contexts_to_cap_action_map = array(
197
		self::caps_read => 'read',
198
		self::caps_read_admin => 'read',
199
		self::caps_edit => 'edit',
200
		self::caps_delete => 'delete' );
201
202
	/**
203
	 * Timezone
204
	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming out of the created objects.  NOT all EEM_Base child classes use this property but any that use a EE_Datetime_Field data type will have access to it.
205
	 * @var string
206
	 */
207
	protected $_timezone;
208
209
	/**
210
	 * A copy of _fields, except the array keys are the model names pointed to by
211
	 * the field
212
	 * @var EE_Model_Field_Base[]
213
	 */
214
	private $_cache_foreign_key_to_fields = array();
215
216
	/**
217
	 * Cached list of all the fields on the model, indexed by their name
218
	 * @var EE_Model_Field_Base[]
219
	 */
220
	private $_cached_fields = NULL;
221
222
	/**
223
	 * Cached list of all the fields on the model, except those that are
224
	 * marked as only pertinent to the database
225
	 * @var EE_Model_Field_Base[]
226
	 */
227
	private $_cached_fields_non_db_only = NULL;
228
229
	/**
230
	 * A cached reference to the primary key for quick lookup
231
	 * @var EE_Model_Field_Base
232
	 */
233
	private $_primary_key_field = NULL;
234
235
	/**
236
	 * Flag indicating whether this model has a primary key or not
237
	 * @var boolean
238
	 */
239
	protected $_has_primary_key_field=null;
240
241
	/**
242
	 * Whether or not this model is based off a table in WP core only (CPTs should set
243
	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
244
	 * @var boolean
245
	 */
246
	protected $_wp_core_model = false;
247
248
	/**
249
	 *	List of valid operators that can be used for querying.
250
	 * The keys are all operators we'll accept, the values are the real SQL
251
	 * operators used
252
	 * @var array
253
	 */
254
	protected $_valid_operators = array(
255
		'='=>'=',
256
		'<='=>'<=',
257
		'<'=>'<',
258
		'>='=>'>=',
259
		'>'=>'>',
260
		'!='=>'!=',
261
		'LIKE'=>'LIKE',
262
		'like'=>'LIKE',
263
		'NOT_LIKE'=>'NOT LIKE',
264
		'not_like'=>'NOT LIKE',
265
		'NOT LIKE'=>'NOT LIKE',
266
		'not like'=>'NOT LIKE',
267
		'IN'=>'IN',
268
		'in'=>'IN',
269
		'NOT_IN'=>'NOT IN',
270
		'not_in'=>'NOT IN',
271
		'NOT IN'=>'NOT IN',
272
		'not in'=>'NOT IN',
273
		'between' => 'BETWEEN',
274
		'BETWEEN' => 'BETWEEN',
275
		'IS_NOT_NULL' => 'IS NOT NULL',
276
		'is_not_null' =>'IS NOT NULL',
277
		'IS NOT NULL' => 'IS NOT NULL',
278
		'is not null' => 'IS NOT NULL',
279
		'IS_NULL' => 'IS NULL',
280
		'is_null' => 'IS NULL',
281
		'IS NULL' => 'IS NULL',
282
		'is null' => 'IS NULL',
283
		'REGEXP' => 'REGEXP',
284
		'regexp' => 'REGEXP',
285
		'NOT_REGEXP' => 'NOT REGEXP',
286
		'not_regexp' => 'NOT REGEXP',
287
		'NOT REGEXP' => 'NOT REGEXP',
288
		'not regexp' => 'NOT REGEXP',
289
	);
290
291
	/**
292
	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
293
	 * @var array
294
	 */
295
	protected $_in_style_operators = array('IN', 'NOT IN');
296
297
	/**
298
	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND '12-31-2012'"
299
	 * @var array
300
	 */
301
	protected $_between_style_operators = array( 'BETWEEN' );
302
303
	/**
304
	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists on a join table.
305
	 * @var array
306
	 */
307
	protected $_null_style_operators = array( 'IS NOT NULL', 'IS NULL');
308
309
	/**
310
	 * Allowed values for $query_params['order'] for ordering in queries
311
	 * @var array
312
	 */
313
	protected $_allowed_order_values = array('asc','desc','ASC','DESC');
314
315
	/**
316
	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
317
	 * than regular field names. It is assumed that their values are an array of WHERE conditions
318
	 * @var array
319
	 */
320
	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
321
322
	/**
323
	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
324
	 * 'where', but 'where' clauses are so common that we thought we'd omit it
325
	 * @var array
326
	 */
327
	private $_allowed_query_params = array(0, 'limit','order_by','group_by','having','force_join','order','on_join_limit','default_where_conditions', 'caps');
328
329
	/**
330
	 * All the data types that can be used in $wpdb->prepare statements.
331
	 * @var array
332
	 */
333
	private $_valid_wpdb_data_types = array('%d','%s','%f');
334
335
	/**
336
	 * 	EE_Registry Object
337
	 *	@var 	object
338
	 * 	@access 	protected
339
	 */
340
	protected $EE = NULL;
341
342
343
	/**
344
	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
345
	 * @var int
346
	 */
347
	protected $_show_next_x_db_queries = 0;
348
349
	/**
350
	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
351
	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
352
	 * @var array
353
	 */
354
	protected $_custom_selections = array();
355
356
	/**
357
	 * key => value Entity Map using  ID => model object
358
	 * caches every model object we've fetched from the DB on this request
359
	 * @var EE_Base_Class[]
360
	 */
361
	protected $_entity_map;
362
363
	/**
364
	 * constant used to show EEM_Base has not yet verified the db on this http request
365
	 */
366
	const db_verified_none 		= 0;
367
	/**
368
	 * constant used to show EEM_Base has verified the EE core db on this http request,
369
	 * but not the addons' dbs
370
	 */
371
	const db_verified_core 		= 1;
372
	/**
373
	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
374
	 * the EE core db too)
375
	 */
376
	const db_verified_addons 	= 2;
377
378
	/**
379
	 * indicates whether an EEM_Base child has already re-verified the DB
380
	 * is ok (we don't want to do it repetitively). Should be set to one the constants
381
	 * looking like EEM_Base::db_verified_*
382
	 * @var int - 0 = none, 1 = core, 2 = addons
383
	 */
384
	protected static $_db_verification_level = EEM_Base::db_verified_none;
385
386
387
388
389
	/**
390
	 * About all child constructors:
391
	 * they should define the _tables, _fields and _model_relations arrays.
392
	 * Should ALWAYS be called after child constructor.
393
	 * In order to make the child constructors to be as simple as possible, this parent constructor
394
	 * finalizes constructing all the object's attributes.
395
	 * Generally, rather than requiring a child to code
396
	 * $this->_tables = array(
397
	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
398
	 *        ...);
399
	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
400
	 * each EE_Table has a function to set the table's alias after the constructor, using
401
	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
402
	 * do something similar.
403
	 *
404
	 * @param null $timezone
405
	 * @throws \EE_Error
406
	 */
407
	protected function __construct( $timezone = NULL ){
408
		// check that the model has not been loaded too soon
409
		if ( ! did_action( 'AHEE__EE_System__load_espresso_addons' )) {
410
			throw new EE_Error (
411
				sprintf(
412
					__( 'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.', 'event_espresso' ),
413
					get_class( $this )
414
				)
415
			);
416
		}
417
418
		/**
419
		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
420
		 * just use EE_Register_Model_Extension
421
		 * @var EE_Table_Base[] $_tables
422
		 */
423
		$this->_tables = apply_filters( 'FHEE__'.get_class($this).'__construct__tables', $this->_tables );
424
		foreach($this->_tables as $table_alias => $table_obj){
425
			/** @var $table_obj EE_Table_Base */
426
			$table_obj->_construct_finalize_with_alias($table_alias);
427
			if( $table_obj instanceof EE_Secondary_Table ){
428
				/** @var $table_obj EE_Secondary_Table */
429
				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
430
			}
431
		}
432
		/**
433
		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
434
		 * EE_Register_Model_Extension
435
		 * @param EE_Model_Field_Base[] $_fields
436
		 */
437
		$this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields',$this->_fields);
438
		$this->_invalidate_field_caches();
439
		foreach($this->_fields as $table_alias => $fields_for_table){
440
			if ( ! array_key_exists( $table_alias, $this->_tables )){
441
				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",'event_espresso'),$table_alias,implode(",",$this->_fields)));
442
			}
443
			foreach($fields_for_table as $field_name => $field_obj){
444
				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
445
				//primary key field base has a slightly different _construct_finalize
446
				/** @var $field_obj EE_Model_Field_Base */
447
				$field_obj->_construct_finalize( $table_alias, $field_name, $this->get_this_model_name() );
448
			}
449
		}
450
451
		// everything is related to Extra_Meta
452
		if( get_class($this) !== 'EEM_Extra_Meta'){
453
			//make extra meta related to everything, but don't block deleting things just
454
			//because they have related extra meta info. For now just orphan those extra meta
455
			//in the future we should automatically delete them
456
			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation( FALSE );
457
		}
458
		//and change logs
459
		if( get_class( $this) !==  'EEM_Change_Log' ) {
460
			$this->_model_relations[ 'Change_Log' ] = new EE_Has_Many_Any_Relation( FALSE );
461
		}
462
		/**
463
		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
464
		 * EE_Register_Model_Extension
465
		 * @param EE_Model_Relation_Base[] $_model_relations
466
		 */
467
		$this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',$this->_model_relations);
468
		foreach($this->_model_relations as $model_name => $relation_obj){
469
			/** @var $relation_obj EE_Model_Relation_Base */
470
			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
471
		}
472
		foreach($this->_indexes as $index_name => $index_obj){
473
			/** @var $index_obj EE_Index */
474
			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
475
		}
476
477
		$this->set_timezone($timezone);
478
		//finalize default where condition strategy, or set default
479
		if( ! $this->_default_where_conditions_strategy){
480
			//nothing was set during child constructor, so set default
481
			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
482
		}
483
		$this->_default_where_conditions_strategy->_finalize_construct($this);
484
		if( ! $this->_minimum_where_conditions_strategy){
485
			//nothing was set during child constructor, so set default
486
			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
487
		}
488
		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
489
490
		//if the cap slug hasn't been set, and we haven't set it to false on purpose
491
		//to indicate to NOT set it, set it to the logical default
492
		if( $this->_caps_slug === null ) {
493
			$this->_caps_slug = EEH_Inflector::pluralize_and_lower( $this->get_this_model_name() );
494
		}
495
		//initialize the standard cap restriction generators if none were specified by the child constructor
496
		if( $this->_cap_restriction_generators !== false ){
497
			foreach( $this->cap_contexts_to_cap_action_map() as $cap_context => $action ){
498
				if( ! isset( $this->_cap_restriction_generators[ $cap_context ] ) ) {
499
					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
500
						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
501
						new EE_Restriction_Generator_Protected(),
502
						$cap_context,
503
						$this
504
					);
505
				}
506
			}
507
		}
508
		//if there are cap restriction generators, use them to make the default cap restrictions
509
		if( $this->_cap_restriction_generators !== false ){
510
			foreach( $this->_cap_restriction_generators as $context => $generator_object ) {
511
				if( ! $generator_object ){
512
					continue;
513
				}
514 View Code Duplication
				if( ! $generator_object instanceof EE_Restriction_Generator_Base ){
515
					throw new EE_Error(
516
						sprintf(
517
							__( 'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.', 'event_espresso' ),
518
							$context,
519
							$this->get_this_model_name()
520
						)
521
					);
522
				}
523
				$action = $this->cap_action_for_context( $context );
524
				if( ! $generator_object->construction_finalized() ){
525
					$generator_object->_construct_finalize( $this, $action );
526
				}
527
528
			}
529
		}
530
		do_action('AHEE__'.get_class($this).'__construct__end');
531
	}
532
533
	/**
534
	 * Generates the cap restrictions for the given context, or if they were
535
	 * already generated just gets what's cached
536
	 * @param string $context one of EEM_Base::valid_cap_contexts()
537
	 * @return EE_Default_Where_Conditions[]
538
	 */
539
	protected function _generate_cap_restrictions( $context ){
540
		if( isset( $this->_cap_restriction_generators[ $context ] ) &&
541
				$this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base ) {
542
			return $this->_cap_restriction_generators[ $context ]->generate_restrictions();
543
		}else{
544
			return array();
545
		}
546
}
547
548
549
	/**
550
	 *		This function is a singleton method used to instantiate the Espresso_model object
551
	 *
552
	 *		@access public
553
	 *		@param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
554
	 *		@return static (as in the concrete child class)
555
	 */
556 View Code Duplication
	public static function instance( $timezone = NULL ){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
557
558
		// check if instance of Espresso_model already exists
559
		if ( ! static::$_instance instanceof static) {
560
			// instantiate Espresso_model
561
			static::$_instance = new static( $timezone );
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 556 can also be of type string; however, EEM_Base::__construct() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
562
		}
563
564
		//we might have a timezone set, let set_timezone decide what to do with it
565
		static::$_instance->set_timezone( $timezone );
566
567
		// Espresso_model object
568
		return static::$_instance;
569
	}
570
571
572
573
	/**
574
	 * resets the model and returns it
575
	 * @param null | string $timezone
576
	 * @return static
577
	 */
578
	public static function reset(  $timezone = NULL ){
579
		if ( ! is_null( static::$_instance ) ) {
580
			static::$_instance = null;
581
582
			return self::instance( $timezone );
583
		}
584
		return null;
585
	}
586
587
588
589
	/**
590
	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
591
	 *
592
	 * @param  boolean $translated return localized strings or JUST the array.
593
	 * @return array
594
	 * @throws \EE_Error
595
	 */
596
	 public function status_array( $translated = FALSE ) {
597
		 if ( ! array_key_exists( 'Status', $this->_model_relations ) ) {
598
			 return array();
599
		 }
600
		 $model_name = $this->get_this_model_name();
601
		 $status_type = str_replace( ' ', '_', strtolower( str_replace( '_', ' ', $model_name ) ) );
602
		 $stati = EEM_Status::instance()->get_all( array( array( 'STS_type' => $status_type ) ) );
603
		 $status_array = array();
604
		 foreach ( $stati as $status ) {
605
			 $status_array[ $status->ID() ] = $status->get( 'STS_code' );
606
		 }
607
		 return $translated
608
			 ? EEM_Status::instance()->localized_status( $status_array, false, 'sentence' )
609
			 : $status_array;
610
	 }
611
612
613
614
	/**
615
	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
616
	 *
617
	 * @param array $query_params {
618
     *	@var array $0 (where) array {
619
	 *		eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine if user is bob')
620
			* becomes
621
	 *		SQL >> "...WHERE QST_display_text = 'Are you bob?' AND QST_admin_text = 'Determine if user is bob'...")
622
     *		To add WHERE conditions based on related models (and even models-related-to-related-models) prepend the model's name
623
	 *		onto the field name. Eg, EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12)));
624
	 *		becomes
625
	 *		SQL >> "SELECT * FROM wp_posts AS Event_CPT
626
	 *						LEFT JOIN wp_esp_event_meta AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID
627
	 *						LEFT JOIN wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID
628
	 *						LEFT JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID
629
	 *						LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID
630
	 *						WHERE Venue_CPT.ID = 12
631
	 *		Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables).
632
	 * 	 	Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have
633
	 *		"Registration.Attendee.ATT_ID" as a field on a query for events (because events are related to Registrations, which are related to Attendees).
634
	 *		You can take it even further with "Registration.Transaction.Payment.PAY_amount" etc.
635
	 *		To change the operator (from the default of '='), change the value to an numerically-indexed array, where the
636
	 *		first item in the list is the operator.
637
	 *		eg: array( 'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34), 'QST_wp_user' => array('in',array(1,2,7,23)))
638
	 *		becomes
639
	 *		SQL >> "...WHERE QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN (1,2,7,23)...".
640
	 *        Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT LIKE, IN (followed by numeric-indexed array),
641
	 *          NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL
642
     *		Values can be a string, int, or float. They can also be arrays IFF the operator is IN.
643
	 *        Also, values can actually be field names. To indicate the value is a field,
644
	 *          simply provide a third array item (true) to the operator-value array like so:
645
	 *		eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) )
646
	 *		becomes
647
	 *		SQL >> "...WHERE DTT_reg_limit > DTT_sold"
648
	 *		Note: you can also use related model field names like you would any other field name.
649
	 *		eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE)
650
	 *		could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets)
651
     *		Also, by default all the where conditions are AND'd together.
652
	 *		To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together
653
	 *		eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' => 345678912))
654
	 *		becomes
655
	 *		SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...".
656
	 * 		Also, to negate an entire set of conditions, use 'NOT' as an array key.
657
	 *		eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)
658
	 *		becomes
659
	 *		SQL >> "...where ! (TXN_total =50 AND TXN_paid =23)
660
	 *		Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
661
	 *		but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR"
662
	 *		to join conditions, it will continue to "stick" until you specify an AND.
663
	 *		eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN')
664
	 *		becomes
665
	 *		SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'"
666
     *		They can be nested indefinitely.
667
	 *		eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN'))))
668
	 *		becomes
669
	 *		SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..."
670
     *		GOTCHA:
671
	 *		because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field.
672
	 *		eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)),
673
	 *		as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'.
674
	 *		becomes
675
	 *		SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions).
676
     *		To overcome this, you can add a '*' character to the end of the field's name, followed by anything.
677
	 *		These will be removed when generating the SQL string, but allow for the array keys to be unique.
678
	 *		eg: you could rewrite the previous query as:
679
	 *		array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date))
680
	 *		which correctly becomes
681
	 *		SQL >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123"
682
	 *		This can be applied to condition operators too,
683
	 *		eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
684
	 *	@var mixed $limit int|array	adds a limit to the query just like the SQL limit clause, so limits of "23", "25,50", and array(23,42) are all valid would become
685
	 *		SQL "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
686
	 *		Remember when you provide two numbers for the limit, the 1st number is the OFFSET, the 2nd is the LIMIT
687
	 *	@var array $on_join_limit allows the setting of a special select join with a internal limit so you can do paging on one-to-many multi-table-joins.
688
	 *		Send an array in the following format array('on_join_limit' => array( 'table_alias', array(1,2) ) ).
689
	 *	@var mixed $order_by name of a column to order by, or an array where keys are field names and values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'),
690
	 *		which would becomes SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively.
691
	 *		Like the 'where' conditions, these fields can be on related models.
692
	 *		Eg 'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
693
	 *	@var string $order	If 'order_by' is used and its value is a string (NOT an array), then 'order' specifies whether to order the field specified in 'order_by' in ascending or
694
	 *		descending order. Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you want to order by the primary key.
695
	 *		Eg, EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join with the Datetime model's table(s) and order by its field DTT_EVT_start)
696
	 *		or EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
697
	 *
698
	 *	@var mixed $group_by name of field to order by, or an array of fields. Eg either 'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total')
699
	 *		Note: if no $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined primary keys). This
700
	 *		avoids some weirdness that results when using limits, tons of joins, and no group by, see https://events.codebasehq.com/projects/event-espresso/tickets/9389
701
	 *
702
	 *	@var array $having	exactly like WHERE parameters array, except these conditions apply to the grouped results (whereas WHERE conditions apply to the pre-grouped results)
703
	 *
704
	 *	@var array $force_join forces a join with the models named. Should be a numerically-indexed array where values are models to be joined in the query.Eg
705
	 *		array('Attendee','Payment','Datetime'). You may join with transient models using period, eg "Registration.Transaction.Payment".
706
	 *		You will probably only want to do this in hopes of increasing efficiency, as related models which belongs to the current model
707
	 *		(ie, the current model has a foreign key to them, like how Registration belongs to Attendee) can be cached in order
708
	 *		to avoid future queries
709
     *	@var string $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'. set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are filtered-out
710
	 *		if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS model's default where conditions
711
	 *		set it to 'other_models_only'. If you only want this model's default where conditions added to the query, use 'this_model_only'.
712
	 *		If you want to use all default where conditions (default), set to 'all'.
713
	 *	@var string $caps controls what capability requirements to apply to the query; ie, should we just NOT
714
	 *		apply any capabilities/permissions/restrictions and return everything? Or should we only show the
715
	 *		current user items they should be able to view on the frontend, backend, edit, or delete?
716
	 *		can be set to 'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
717
	 * }
718
	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed)
719
	 * Some full examples:
720
	 * 		get 10 transactions which have Scottish attendees:
721
	 * 		EEM_Transaction::instance()->get_all( array(
722
	 *			array(
723
	 *				'OR'=>array(
724
	 *					'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
725
	 *					'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
726
	 *				)
727
	 * 			),
728
	 *			'limit'=>10,
729
	 *			'group_by'=>'TXN_ID'
730
	 * 		));
731
	 * 		get all the answers to the question titled "shirt size" for event with id 12, ordered by their answer
732
	 * 		EEM_Answer::instance()->get_all(array(
733
	 *			array(
734
	 *				'Question.QST_display_text'=>'shirt size',
735
	 *				'Registration.Event.EVT_ID'=>12
736
	 * 			),
737
	 *			'order_by'=>array('ANS_value'=>'ASC')
738
	 *		));
739
	 * @throws \EE_Error
740
	 */
741
	public function get_all($query_params = array()){
742
		if( isset( $query_params[ 'limit' ] )
743
			&& ! isset( $query_params[ 'group_by' ] ) ) {
744
			$query_params[ 'group_by' ] = array_keys( $this->get_combined_primary_key_fields() );
745
		}
746
		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, NULL));
747
	}
748
749
	/**
750
	 * Modifies the query parameters so we only get back model objects
751
	 * that "belong" to the current user
752
	 * @param array $query_params @see EEM_Base::get_all()
753
	 * @return array like EEM_Base::get_all
754
	 */
755
	public function alter_query_params_to_only_include_mine( $query_params = array() ) {
756
		$wp_user_field_name = $this->wp_user_field_name();
757
		if( $wp_user_field_name ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $wp_user_field_name of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
758
			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
759
		}
760
		return $query_params;
761
	}
762
763
	/**
764
	 * Returns the name of the field's name that points to the WP_User table
765
	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
766
	 * foreign key to the WP_User table)
767
	 * @return string|boolean string on success, boolean false when there is no
768
	 * foreign key to the WP_User table
769
	 */
770
	public function wp_user_field_name() {
771
		try{
772
			if( ! empty( $this->_model_chain_to_wp_user ) ) {
773
				$models_to_follow_to_wp_users = explode( '.', $this->_model_chain_to_wp_user );
774
				$last_model_name = end( $models_to_follow_to_wp_users );
775
				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model( $last_model_name );
776
				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
777
			}else{
778
				$model_with_fk_to_wp_users = $this;
779
				$model_chain_to_wp_user = '';
780
			}
781
			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to( 'WP_User' );
782
			return $model_chain_to_wp_user . $wp_user_field->get_name();
783
		}catch( EE_Error $e ) {
784
			return false;
785
		}
786
	}
787
788
	/**
789
	 * Returns the _model_chain_to_wp_user string, which indicates which related model
790
	 * (or transiently-related model) has a foreign key to the wp_users table;
791
	 * useful for finding if model objects of this type are 'owned' by the current user.
792
	 * This is an empty string when the foreign key is on this model and when it isn't,
793
	 * but is only non-empty when this model's ownership is indicated by a RELATED model
794
	 * (or transiently-related model)
795
	 * @return string
796
	 */
797
	public function model_chain_to_wp_user(){
798
		return $this->_model_chain_to_wp_user;
799
	}
800
801
	/**
802
	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
803
	 * like how registrations don't have a foreign key to wp_users, but the
804
	 * events they are for are), or is unrelated to wp users.
805
	 * generally available
806
	 * @return boolean
807
	 */
808
	public function is_owned() {
809
		if( $this->model_chain_to_wp_user() ){
810
			return true;
811
		}else{
812
			try{
813
				$this->get_foreign_key_to( 'WP_User' );
814
				return true;
815
			}catch( EE_Error $e ){
816
				return false;
817
			}
818
		}
819
	}
820
821
822
823
	/**
824
	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but may want to
825
	 * preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on the model)
826
	 *
827
	 * @param array  $query_params      like EEM_Base::get_all's $query_params
828
	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
829
	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the fields on the model,
830
	 *                                  and the models we joined to in the query. However, you can override this and set the select to "*", or a specific column name, like "ATT_ID", etc.
831
	 *                                  If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
832
	 *                                  Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
833
	 *                                  and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
834
	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
835
	 * @throws \EE_Error
836
	 */
837
	protected function  _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
838
		// remember the custom selections, if any, and type cast as array
839
		// (unless $columns_to_select is an object, then just set as an empty array)
840
		// Note: (array) 'some string' === array( 'some string' )
841
		$this->_custom_selections = ! is_object( $columns_to_select ) ? (array) $columns_to_select : array();
842
		$model_query_info = $this->_create_model_query_info_carrier( $query_params );
843
		$select_expressions = $columns_to_select !== null
844
			? $this->_construct_select_from_input( $columns_to_select )
845
			: $this->_construct_default_select_sql( $model_query_info );
846
		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query( $model_query_info );
847
		return $this->_do_wpdb_query( 'get_results', array( $SQL, $output ) );
848
	}
849
850
	/**
851
	 * Gets an array of rows from the database just like $wpdb->get_results would,
852
	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
853
	 * take care of joins, field preparation etc.
854
	 *
855
	 * @param array $query_params like EEM_Base::get_all's $query_params
856
	 * @param string $output ARRAY_A, OBJECT_K, etc. Just like
857
	 * @param mixed $columns_to_select, What columns to select. By default, we select all columns specified by the fields on the model,
0 ignored issues
show
Documentation introduced by
There is no parameter named $columns_to_select,. Did you maybe mean $columns_to_select?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
858
	 * and the models we joined to in the query. However, you can override this and set the select to "*", or a specific column name, like "ATT_ID", etc.
859
	 * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
860
	 * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
861
	 * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
862
	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
863
	 * @throws \EE_Error
864
	 */
865
	public function  get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
866
		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
867
	}
868
869
870
	/**
871
	 * For creating a custom select statement
872
	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
873
	 * or an array where keys are aliases, and values are arrays where 0=>the selection SQL, and 1=>is the datatype
874
	 * @throws EE_Error
875
	 * @return string
876
	 */
877
	private function _construct_select_from_input($columns_to_select){
878
		if(is_array($columns_to_select)){
879
			$select_sql_array = array();
880
881
			foreach($columns_to_select as $alias => $selection_and_datatype){
882
				if( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])){
883
					throw new EE_Error(
884
						sprintf(
885
							__(
886
								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
887
								"event_espresso"
888
							),
889
							$selection_and_datatype,
890
							$alias
891
						)
892
					);
893
				}
894
				if( ! in_array( $selection_and_datatype[1],$this->_valid_wpdb_data_types)){
895
					throw new EE_Error(
896
						sprintf(
897
							__(
898
								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
899
								"event_espresso"
900
							),
901
							$selection_and_datatype[ 1 ],
902
							$selection_and_datatype[ 0 ],
903
							$alias,
904
							implode( ",", $this->_valid_wpdb_data_types )
905
						)
906
					);
907
				}
908
				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
909
			}
910
			$columns_to_select_string = implode(", ",$select_sql_array);
911
		}else{
912
			$columns_to_select_string = $columns_to_select;
913
		}
914
		return $columns_to_select_string;
915
916
	}
917
918
919
920
	/**
921
	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
922
	 *
923
	 * @return string
924
	 * @throws \EE_Error
925
	 */
926
	public function primary_key_name(){
927
		return $this->get_primary_key_field()->get_name();
928
	}
929
930
931
932
	/**
933
	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
934
	 * If there is no primary key on this model, $id is treated as primary key string
935
	 * @param mixed $id int or string, depending on the type of the model's primary key
936
	 * @return EE_Base_Class
937
	 */
938
	public function get_one_by_ID($id){
939
		if( $this->get_from_entity_map( $id ) ){
940
			return $this->get_from_entity_map( $id );
941
		}
942
		return $this->get_one(
943
			$this->alter_query_params_to_restrict_by_ID(
944
				$id,
945
				array( 'default_where_conditions' => 'minimum' )
946
			)
947
		);
948
	}
949
950
951
952
	/**
953
	 * Alters query parameters to only get items with this ID are returned.
954
	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string()
955
	 *
956
	 * @param int   $id
957
	 * @param array $query_params
958
	 * @return array of normal query params, @see EEM_Base::get_all
959
	 * @throws \EE_Error
960
	 */
961
	public function alter_query_params_to_restrict_by_ID( $id, $query_params = array() ) {
962
		if( ! isset( $query_params[ 0 ] ) ) {
963
			$query_params[ 0 ] = array();
964
		}
965
		if( $this->has_primary_key_field ( ) ) {
966
			$query_params[ 0 ][ $this->primary_key_name() ] = $id ;
967
		}else{
968
			//no primary key, so the $id must be from the get_index_primary_key_string()
969
			$query_params[0] = array_replace_recursive( $query_params[ 0 ], $this->parse_index_primary_key_string( $id ) );
970
		}
971
		return $query_params;
972
	}
973
974
975
976
	/**
977
	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an array. If no item is found,
978
	 * null is returned.
979
	 *
980
	 * @param array $query_params like EEM_Base's $query_params variable.
981
	 * @return EE_Base_Class | NULL
982
	 * @throws \EE_Error
983
	 */
984 View Code Duplication
	public function get_one($query_params = array()){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
985
		if( ! is_array( $query_params ) ){
986
			EE_Error::doing_it_wrong('EEM_Base::get_one', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
987
			$query_params = array();
988
		}
989
		$query_params['limit'] = 1;
990
		$items = $this->get_all($query_params);
991
		if(empty($items)){
992
			return null;
993
		}else{
994
			return array_shift($items);
995
		}
996
	}
997
998
999
1000
	/**
1001
	 * Returns the next x number of items in sequence from the given value as
1002
	 * found in the database matching the given query conditions.
1003
	 *
1004
	 * @param mixed $current_field_value    Value used for the reference point.
1005
	 * @param null  $field_to_order_by      What field is used for the
1006
	 *                                      reference point.
1007
	 * @param int   $limit                  How many to return.
1008
	 * @param array $query_params           Extra conditions on the query.
1009
	 * @param null  $columns_to_select      If left null, then an array of
1010
	 *                                      EE_Base_Class objects is returned,
1011
	 *                                      otherwise you can indicate just the
1012
	 *                                      columns you want returned.
1013
	 * @return EE_Base_Class[]|array
1014
	 * @throws \EE_Error
1015
	 */
1016
	public function next_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1017
		return $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, $limit, $query_params, $columns_to_select );
1018
	}
1019
1020
1021
1022
	/**
1023
	 * Returns the previous x number of items in sequence from the given value
1024
	 * as found in the database matching the given query conditions.
1025
	 *
1026
	 * @param mixed $current_field_value    Value used for the reference point.
1027
	 * @param null  $field_to_order_by      What field is used for the
1028
	 *                                      reference point.
1029
	 * @param int   $limit                  How many to return.
1030
	 * @param array $query_params           Extra conditions on the query.
1031
	 * @param null  $columns_to_select      If left null, then an array of
1032
	 *                                      EE_Base_Class objects is returned,
1033
	 *                                      otherwise you can indicate just the
1034
	 *                                      columns you want returned.
1035
	 * @return EE_Base_Class[]|array
1036
	 * @throws \EE_Error
1037
	 */
1038
	public function previous_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1039
		return $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, $limit, $query_params, $columns_to_select );
1040
	}
1041
1042
1043
1044
	/**
1045
	 * Returns the next item in sequence from the given value as found in the
1046
	 * database matching the given query conditions.
1047
	 *
1048
	 * @param mixed $current_field_value    Value used for the reference point.
1049
	 * @param null  $field_to_order_by      What field is used for the
1050
	 *                                      reference point.
1051
	 * @param array $query_params           Extra conditions on the query.
1052
	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1053
	 *                                      object is returned, otherwise you
1054
	 *                                      can indicate just the columns you
1055
	 *                                      want and a single array indexed by
1056
	 *                                      the columns will be returned.
1057
	 * @return EE_Base_Class|null|array()
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class|null|array() could not be parsed: Expected "|" or "end of type", but got "(" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1058
	 * @throws \EE_Error
1059
	 */
1060
	public function next( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1061
		$results = $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, 1, $query_params, $columns_to_select );
1062
		return empty( $results ) ? null : reset( $results );
1063
	}
1064
1065
1066
1067
1068
	/**
1069
	 * Returns the previous item in sequence from the given value as found in
1070
	 * the database matching the given query conditions.
1071
	 *
1072
	 * @param mixed $current_field_value    Value used for the reference point.
1073
	 * @param null $field_to_order_by       What field is used for the
1074
	 *                                      reference point.
1075
	 * @param array $query_params           Extra conditions on the query.
1076
	 * @param null $columns_to_select       If left null, then an EE_Base_Class
1077
	 *                                      object is returned, otherwise you
1078
	 *                                      can indicate just the columns you
1079
	 *                                      want and a single array indexed by
1080
	 *                                      the columns will be returned.
1081
 * @return EE_Base_Class|null|array()
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class|null|array() could not be parsed: Expected "|" or "end of type", but got "(" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1082
	 * @throws EE_Error
1083
	 */
1084
	public function previous( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1085
		$results = $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, 1, $query_params, $columns_to_select );
1086
		return empty( $results ) ? null : reset( $results );
1087
	}
1088
1089
1090
1091
1092
1093
	/**
1094
	 * Returns the a consecutive number of items in sequence from the given
1095
	 * value as found in the database matching the given query conditions.
1096
	 *
1097
	 * @param mixed $current_field_value    Value used for the reference point.
1098
	 * @param string $operand               What operand is used for the sequence.
1099
	 * @param string $field_to_order_by     What field is used for the reference point.
1100
	 * @param int $limit                    How many to return.
1101
	 * @param array $query_params           Extra conditions on the query.
1102
	 * @param null $columns_to_select       If left null, then an array of EE_Base_Class objects is returned,
1103
	 *                                      otherwise you can indicate just the columns you want returned.
1104
	 * @return EE_Base_Class[]|array
1105
	 * @throws EE_Error
1106
	 */
1107
	protected function _get_consecutive( $current_field_value, $operand = '>', $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1108
		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1109
		if ( empty( $field_to_order_by ) ) {
1110
			if ( $this->has_primary_key_field() ) {
1111
				$field_to_order_by = $this->get_primary_key_field()->get_name();
1112
			} else {
1113
1114
				if ( WP_DEBUG ) {
1115
					throw new EE_Error( __( 'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).', 'event_espresso' ) );
1116
				}
1117
				EE_Error::add_error( __('There was an error with the query.', 'event_espresso') );
1118
				return array();
1119
			}
1120
		}
1121
1122
		if( ! is_array( $query_params ) ){
1123
			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
1124
			$query_params = array();
1125
		}
1126
1127
		//let's add the where query param for consecutive look up.
1128
		$query_params[0][ $field_to_order_by ] = array( $operand, $current_field_value );
1129
		$query_params['limit'] = $limit;
1130
1131
		//set direction
1132
		$incoming_orderby = isset( $query_params['order_by'] ) ? (array)$query_params['order_by'] : array();
1133
		$query_params['order_by'] = $operand === '>'
1134
			? array( $field_to_order_by => 'ASC' ) + $incoming_orderby
1135
			: array( $field_to_order_by => 'DESC') + $incoming_orderby;
1136
1137
		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1138
		if ( empty( $columns_to_select ) ) {
1139
			return $this->get_all( $query_params );
1140
		} else {
1141
			//getting just the fields
1142
			return $this->_get_all_wpdb_results( $query_params, ARRAY_A, $columns_to_select );
1143
		}
1144
	}
1145
1146
1147
1148
1149
	/**
1150
	 * This sets the _timezone property after model object has been instantiated.
1151
	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1152
	 */
1153
	public function set_timezone( $timezone ) {
1154
		if ( $timezone !== null ) {
1155
			$this->_timezone = $timezone;
1156
		}
1157
		//note we need to loop through relations and set the timezone on those objects as well.
1158
		foreach ( $this->_model_relations as $relation ) {
1159
			$relation->set_timezone( $timezone );
1160
		}
1161
		//and finally we do the same for any datetime fields
1162
		foreach ( $this->_fields as $field ) {
1163
			if ( $field instanceof EE_Datetime_Field ) {
1164
				$field->set_timezone( $timezone );
1165
			}
1166
		}
1167
	}
1168
1169
1170
1171
	/**
1172
	 * This just returns whatever is set for the current timezone.
1173
	 *
1174
	 * @access public
1175
	 * @return string
1176
	 */
1177
	public function get_timezone() {
1178
		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1179
		if ( empty( $this->_timezone ) ) {
1180
			foreach( $this->_fields as $field ) {
1181
				if ( $field instanceof EE_Datetime_Field ) {
1182
					$this->set_timezone($field->get_timezone());
1183
					break;
1184
				}
1185
			}
1186
		}
1187
1188
		//if timezone STILL empty then return the default timezone for the site.
1189
		if ( empty( $this->_timezone ) ) {
1190
			$this->set_timezone( EEH_DTT_Helper::get_timezone() );
1191
		}
1192
		return $this->_timezone;
1193
	}
1194
1195
1196
1197
	/**
1198
	 * This returns the date formats set for the given field name and also ensures that
1199
	 * $this->_timezone property is set correctly.
1200
	 *
1201
	 * @since 4.6.x
1202
	 * @param string $field_name The name of the field the formats are being retrieved for.
1203
	 * @param bool   $pretty          Whether to return the pretty formats (true) or not (false).
1204
	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1205
	 *
1206
	 * @return array formats in an array with the date format first, and the time format last.
1207
	 */
1208
	public function get_formats_for( $field_name, $pretty = false ) {
1209
		$field_settings = $this->field_settings_for( $field_name );
1210
1211
		//if not a valid EE_Datetime_Field then throw error
1212
		if ( ! $field_settings instanceof EE_Datetime_Field ) {
1213
			throw new EE_Error( sprintf( __('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.', 'event_espresso' ), $field_name ) );
1214
		}
1215
1216
		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1217
		//the field.
1218
		$this->_timezone = $field_settings->get_timezone();
1219
1220
		return array( $field_settings->get_date_format( $pretty ), $field_settings->get_time_format( $pretty ) );
1221
	}
1222
1223
1224
1225
	/**
1226
	 * This returns the current time in a format setup for a query on this model.
1227
	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1228
	 * it will return:
1229
	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for NOW
1230
	 *  - or a unix timestamp (equivalent to time())
1231
	 *
1232
	 * @since 4.6.x
1233
	 * @param string $field_name The field the current time is needed for.
1234
	 * @param bool   $timestamp  True means to return a unix timestamp. Otherwise a
1235
	 *                           		 formatted string matching the set format for the field in the set timezone will
1236
	 *                           		 be returned.
1237
	 * @param string $what         Whether to return the string in just the time format, the date format, or both.
1238
	 *
1239
	 * @throws EE_Error   	If the given field_name is not of the EE_Datetime_Field type.
1240
	 *
1241
	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1242
	 *                    	     exception is triggered.
1243
	 */
1244
	public function current_time_for_query( $field_name, $timestamp = false, $what = 'both' ) {
1245
		$formats = $this->get_formats_for( $field_name );
1246
1247
		$DateTime = new DateTime( "now", new DateTimeZone( $this->_timezone ) );
1248
1249
		if ( $timestamp ) {
1250
			return $DateTime->format( 'U' );
1251
		}
1252
1253
		//not returning timestamp, so return formatted string in timezone.
1254
		switch( $what ) {
1255
			case 'time' :
1256
				return $DateTime->format( $formats[1] );
1257
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1258
			case 'date' :
1259
				return $DateTime->format( $formats[0] );
1260
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1261
			default :
1262
				return $DateTime->format( implode( ' ', $formats ) );
1263
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1264
		}
1265
	}
1266
1267
1268
1269
	/**
1270
	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1271
	 * for the model are.  Returns a DateTime object.
1272
	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1273
	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is ignored.
1274
	 *
1275
	 * @param string $field_name      The field being setup.
1276
	 * @param string $timestring      The date time string being used.
1277
	 * @param string $incoming_format The format for the time string.
1278
	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1279
	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming format is
1280
	 *                                'U', this is ignored.
1281
	 * @return DateTime
1282
	 * @throws \EE_Error
1283
	 */
1284
	public function convert_datetime_for_query( $field_name, $timestring, $incoming_format, $timezone = '' ) {
1285
1286
		//just using this to ensure the timezone is set correctly internally
1287
		$this->get_formats_for( $field_name );
1288
1289
		//load EEH_DTT_Helper
1290
		$set_timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone;
1291
1292
		$incomingDateTime = date_create_from_format( $incoming_format, $timestring, new DateTimeZone( $set_timezone ) );
1293
1294
		return $incomingDateTime->setTimezone( new DateTimeZone( $this->_timezone ) );
1295
	}
1296
1297
1298
1299
1300
	/**
1301
	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1302
	 * @return EE_Table_Base[]
1303
	 */
1304
	public function get_tables(){
1305
		return $this->_tables;
1306
	}
1307
1308
1309
1310
	/**
1311
	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1312
	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1313
	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for each row (in the primary table) we're trying to update; if not,
1314
	 * it inserts an entry in the secondary table.
1315
	 * Eg: if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a model object with EVT_ID = 1
1316
	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but there is no entry in wp_esp_event for this entry in wp_posts.
1317
	 * So, this update script will insert a row into wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in $fields_n_values,
1318
	 * the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which are not specified)
1319
	 *
1320
*@param array $fields_n_values keys are model fields (exactly like keys in EEM_Base::_fields, NOT db columns!), values are strings, ints, floats, and maybe arrays if they are to be serialized.
1321
	 * Basically, the values are what you'd expect to be values on the model, NOT necessarily what's in the DB. For example, if we wanted to update only the TXN_details on any Transactions where its ID=34,
1322
	 * we'd use this method as follows:
1323
	 * EEM_Transaction::instance()->update(
1324
	 *		array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1325
	 *		array(array('TXN_ID'=>34)));
1326
	 * @param array $query_params very much like EEM_Base::get_all's $query_params
1327
	 * in client code into what's expected to be stored on each field. Eg, consider updating Question's QST_admin_label field is of type Simple_HTML. If you use this function to update
1328
	 * that field to $new_value = (note replace 8's with appropriate opening and closing tags in the following example)"8script8alert('I hack all');8/script88b8boom baby8/b8", then if you set $values_already_prepared_by_model_object to TRUE,
1329
	 * it is assumed that you've already called EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the malicious javascript. However, if $values_already_prepared_by_model_object
1330
	 * is left as FALSE, then EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because
1331
	 * model objects perform their prepare_for_set function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we
1332
	 * escape HTML characters in the prepare_for_set method...)
1333
	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1334
	 * in this model's entity map according to $fields_n_values that match $query_params. This
1335
	 * obviously has some overhead, so you can disable it by setting this to FALSE, but
1336
	 * be aware that model objects being used could get out-of-sync with the database
1337
	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num rows affected which *could* include 0 which DOES NOT mean the query was bad)
1338
	 * @throws \EE_Error
1339
	 */
1340
	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = TRUE){
1341
		if( ! is_array( $query_params ) ){
1342
			EE_Error::doing_it_wrong('EEM_Base::update', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
1343
			$query_params = array();
1344
		}
1345
		/**
1346
		 * Action called before a model update call has been made.
1347
		 *
1348
		 * @param EEM_Base $model
1349
		 * @param array $fields_n_values the updated fields and their new values
1350
		 * @param array $query_params @see EEM_Base::get_all()
1351
		 */
1352
		do_action( 'AHEE__EEM_Base__update__begin',$this, $fields_n_values, $query_params );
1353
		/**
1354
		 * Filters the fields about to be updated given the query parameters. You can provide the
1355
		 * $query_params to $this->get_all() to find exactly which records will be updated
1356
		 * @param array $fields_n_values fields and their new values
1357
		 * @param EEM_Base $model the model being queried
1358
		 * @param array $query_params see EEM_Base::get_all()
1359
		 */
1360
		$fields_n_values = (array)apply_filters( 'FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this, $query_params );
1361
		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1362
		//to do that, for each table, verify that it's PK isn't null.
1363
		$tables= $this->get_tables();
1364
1365
		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1366
		//NOTE: we should make this code more efficient by NOT querying twice
1367
		//before the real update, but that needs to first go through ALPHA testing
1368
		//as it's dangerous. says Mike August 8 2014
1369
1370
			//we want to make sure the default_where strategy is ignored
1371
			$this->_ignore_where_strategy = TRUE;
1372
			$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1373
			foreach( $wpdb_select_results as $wpdb_result ){
1374
				// type cast stdClass as array
1375
				$wpdb_result = (array)$wpdb_result;
1376
				//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1377
				if( $this->has_primary_key_field() ){
1378
					$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1379
				}else{
1380
					//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1381
					$main_table_pk_value = null;
1382
				}
1383
				//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1384
				//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1385
				if(count($tables) > 1){
1386
					//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1387
					//in that table, and so we'll want to insert one
1388
					foreach($tables as $table_obj){
1389
						$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1390
						//if there is no private key for this table on the results, it means there's no entry
1391
						//in this table, right? so insert a row in the current table, using any fields available
1392
						if( ! ( array_key_exists( $this_table_pk_column, $wpdb_result) && $wpdb_result[ $this_table_pk_column ] )){
1393
							$success = $this->_insert_into_specific_table($table_obj, $fields_n_values, $main_table_pk_value);
1394
							//if we died here, report the error
1395
							if( ! $success ) {
1396
								return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by EEM_Base::update of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1397
							}
1398
						}
1399
					}
1400
				}
1401
1402
//				//and now check that if we have cached any models by that ID on the model, that
1403
//				//they also get updated properly
1404
//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1405
//				if( $model_object ){
1406
//					foreach( $fields_n_values as $field => $value ){
1407
//						$model_object->set($field, $value);
1408
			//let's make sure default_where strategy is followed now
1409
			$this->_ignore_where_strategy = FALSE;
1410
		}
1411
		//if we want to keep model objects in sync, AND
1412
		//if this wasn't called from a model object (to update itself)
1413
		//then we want to make sure we keep all the existing
1414
		//model objects in sync with the db
1415
		if( $keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object ){
1416
			if( $this->has_primary_key_field() ){
1417
				$model_objs_affected_ids = $this->get_col( $query_params );
1418
			}else{
1419
				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1420
				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A );
1421
				$model_objs_affected_ids = array();
1422
				foreach( $models_affected_key_columns as $row ){
1423
					$combined_index_key = $this->get_index_primary_key_string( $row );
1424
					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1425
				}
1426
1427
			}
1428
1429
			if( ! $model_objs_affected_ids ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $model_objs_affected_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1430
				//wait wait wait- if nothing was affected let's stop here
1431
				return 0;
1432
			}
1433
			foreach( $model_objs_affected_ids as $id ){
1434
				$model_obj_in_entity_map = $this->get_from_entity_map( $id );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $model_obj_in_entity_map is correct as $this->get_from_entity_map($id) (which targets EEM_Base::get_from_entity_map()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1435
				if( $model_obj_in_entity_map ){
1436
					foreach( $fields_n_values as $field => $new_value ){
1437
						$model_obj_in_entity_map->set( $field, $new_value );
1438
					}
1439
				}
1440
			}
1441
			//if there is a primary key on this model, we can now do a slight optimization
1442
			if( $this->has_primary_key_field() ){
1443
				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1444
				$query_params = array(
1445
					array( $this->primary_key_name() => array( 'IN', $model_objs_affected_ids ) ),
1446
					'limit' => count( $model_objs_affected_ids ), 'default_where_conditions' => 'none' );
1447
			}
1448
		}
1449
1450
		$model_query_info = $this->_create_model_query_info_carrier( $query_params );
1451
		$SQL = "UPDATE ".$model_query_info->get_full_join_sql()." SET ".$this->_construct_update_sql($fields_n_values).$model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1452
		$rows_affected = $this->_do_wpdb_query('query', array( $SQL ) );
1453
		/**
1454
		 * Action called after a model update call has been made.
1455
		 *
1456
		 * @param EEM_Base $model
1457
		 * @param array $fields_n_values the updated fields and their new values
1458
		 * @param array $query_params @see EEM_Base::get_all()
1459
		 * @param int $rows_affected
1460
		 */
1461
		do_action( 'AHEE__EEM_Base__update__end',$this, $fields_n_values, $query_params, $rows_affected );
1462
		return $rows_affected;//how many supposedly got updated
1463
	}
1464
1465
1466
1467
	/**
1468
	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1469
	 * are teh values of the field specified (or by default the primary key field)
1470
	 * that matched the query params. Note that you should pass the name of the
1471
	 * model FIELD, not the database table's column name.
1472
	 *
1473
	 * @param array  $query_params @see EEM_Base::get_all()
1474
	 * @param string $field_to_select
1475
	 * @return array just like $wpdb->get_col()
1476
	 * @throws \EE_Error
1477
	 */
1478
	public function get_col( $query_params  = array(), $field_to_select = NULL ){
1479
1480
		if( $field_to_select ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_select of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1481
			$field = $this->field_settings_for( $field_to_select );
1482
		}elseif( $this->has_primary_key_field ( ) ){
1483
			$field = $this->get_primary_key_field();
1484
		}else{
1485
			//no primary key, just grab the first column
1486
			$field = reset( $this->field_settings());
0 ignored issues
show
Bug introduced by
$this->field_settings() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
1487
		}
1488
1489
1490
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1491
		$select_expressions = $field->get_qualified_column();
1492
		$SQL ="SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1493
		return $this->_do_wpdb_query('get_col', array( $SQL ) );
1494
	}
1495
1496
1497
1498
	/**
1499
	 * Returns a single column value for a single row from the database
1500
	 *
1501
	 * @param array  $query_params    @see EEM_Base::get_all()
1502
	 * @param string $field_to_select @see EEM_Base::get_col()
1503
	 * @return string
1504
	 * @throws \EE_Error
1505
	 */
1506
	public function get_var( $query_params = array(), $field_to_select = NULL ) {
1507
		$query_params[ 'limit' ] = 1;
1508
		$col = $this->get_col( $query_params, $field_to_select );
1509
		if( ! empty( $col ) ) {
1510
			return reset( $col );
1511
		}else{
1512
			return NULL;
1513
		}
1514
	}
1515
1516
1517
1518
	/**
1519
	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party time?', Question.desc='what do you think?',..."
1520
	 * Values are filtered through wpdb->prepare to avoid against SQL injection, but currently no further filtering is done
1521
	 *
1522
	 * @global      $wpdb
1523
	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should be updated to in the DB
1524
	 * @return string of SQL
1525
	 * @throws \EE_Error
1526
	 */
1527
	public function _construct_update_sql($fields_n_values){
1528
		/** @type WPDB $wpdb */
1529
		global $wpdb;
1530
		$cols_n_values = array();
1531
		foreach($fields_n_values as $field_name => $value){
1532
			$field_obj = $this->field_settings_for($field_name);
1533
			//if the value is NULL, we want to assign the value to that.
1534
			//wpdb->prepare doesn't really handle that properly
1535
			$prepared_value = $this->_prepare_value_or_use_default( $field_obj, $fields_n_values );
1536
			$value_sql = $prepared_value===NULL ? 'NULL' : $wpdb->prepare( $field_obj->get_wpdb_data_type(), $prepared_value );
1537
			$cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1538
		}
1539
		return implode(",",$cols_n_values);
1540
1541
	}
1542
1543
1544
1545
	/**
1546
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1547
	 * Performs a HARD delete, meaning the database row should always be removed,
1548
	 * not just have a flag field on it switched
1549
	 * Wrapper for EEM_Base::delete_permanently()
1550
	 *
1551
	 * @param mixed $id
1552
	 * @return boolean whether the row got deleted or not
1553
	 * @throws \EE_Error
1554
	 */
1555
	public function delete_permanently_by_ID( $id ) {
1556
		return $this->delete_permanently(
1557
			array(
1558
				array( $this->get_primary_key_field()->get_name() => $id ),
1559
				'limit' 	=> 1
1560
			)
1561
		);
1562
	}
1563
1564
1565
1566
	/**
1567
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1568
	 * Wrapper for EEM_Base::delete()
1569
	 *
1570
	 * @param mixed $id
1571
	 * @return boolean whether the row got deleted or not
1572
	 * @throws \EE_Error
1573
	 */
1574
	public function delete_by_ID( $id ){
1575
		return $this->delete(
1576
			array(
1577
				array( $this->get_primary_key_field()->get_name() => $id ),
1578
				'limit' 	=> 1
1579
			)
1580
		);
1581
	}
1582
1583
1584
1585
	/**
1586
	 * Identical to delete_permanently, but does a "soft" delete if possible,
1587
	 * meaning if the model has a field that indicates its been "trashed" or
1588
	 * "soft deleted", we will just set that instead of actually deleting the rows.
1589
	 *
1590
	 * @see EEM_Base::delete_permanently
1591
	 * @param array   $query_params
1592
	 * @param boolean $allow_blocking
1593
	 * @return int how many rows got deleted
1594
	 * @throws \EE_Error
1595
	 */
1596
	public function delete($query_params,$allow_blocking = true){
1597
		return $this->delete_permanently($query_params, $allow_blocking);
1598
	}
1599
1600
1601
1602
	/**
1603
	 * Deletes the model objects that meet the query params. Note: this method is overridden
1604
	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1605
	 * as archived, not actually deleted
1606
	 *
1607
	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1608
	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1609
	 *                                that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1610
	 *                                which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1611
	 * @return int how many rows got deleted
1612
	 * @throws \EE_Error
1613
	 */
1614
	public function delete_permanently($query_params,$allow_blocking = true){
1615
		/**
1616
		 * Action called just before performing a real deletion query. You can use the
1617
		 * model and its $query_params to find exactly which items will be deleted
1618
		 * @param EEM_Base $model
1619
		 * @param array $query_params @see EEM_Base::get_all()
1620
		 * @param boolean $allow_blocking whether or not to allow related model objects
1621
		 * to block (prevent) this deletion
1622
		 */
1623
		do_action( 'AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking );
1624
		//some MySQL databases may be running safe mode, which may restrict
1625
		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1626
		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1627
		//to delete them
1628
		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1629
		$deletion_where = $this->_setup_ids_for_delete( $items_for_deletion, $allow_blocking);
1630
		if($deletion_where){
1631
			//echo "objects for deletion:";var_dump($objects_for_deletion);
1632
			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1633
			$table_aliases = array_keys( $this->_tables );
1634
			$SQL = "DELETE ".implode(", ",$table_aliases)." FROM ".$model_query_info->get_full_join_sql()." WHERE ".$deletion_where;
1635
1636
			//		/echo "delete sql:$SQL";
1637
			$rows_deleted = $this->_do_wpdb_query( 'query', array( $SQL ) );
1638
		}else{
1639
			$rows_deleted = 0;
1640
		}
1641
1642
		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1643
		if( $this->has_primary_key_field() ){
1644
			foreach($items_for_deletion as $item_for_deletion_row ){
1645
				$pk_value = $item_for_deletion_row[ $this->get_primary_key_field()->get_qualified_column() ];
1646
				if( isset( $this->_entity_map[ $pk_value ] ) ){
1647
					unset( $this->_entity_map[ $pk_value ] );
1648
				}
1649
			}
1650
		}
1651
1652
		/**
1653
		 * Action called just after performing a real deletion query. Although at this point the
1654
		 * items should have been deleted
1655
		 * @param EEM_Base $model
1656
		 * @param array $query_params @see EEM_Base::get_all()
1657
		 * @param int $rows_deleted
1658
		 */
1659
		do_action( 'AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted );
1660
		return $rows_deleted;//how many supposedly got deleted
1661
	}
1662
1663
1664
1665
	/**
1666
	 * Checks all the relations that throw error messages when there are blocking related objects
1667
	 * for related model objects. If there are any related model objects on those relations,
1668
	 * adds an EE_Error, and return true
1669
	 *
1670
	 * @param EE_Base_Class|int $this_model_obj_or_id
1671
	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which should be ignored when
1672
	 *                                                 determining whether there are related model objects which block this model object's deletion. Useful
1673
	 *                                                 if you know A is related to B and are considering deleting A, but want to see if A has any other objects
1674
	 *                                                 blocking its deletion before removing the relation between A and B
1675
	 * @return boolean
1676
	 * @throws \EE_Error
1677
	 */
1678
	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null){
1679
		//first, if $ignore_this_model_obj was supplied, get its model
1680
		if($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class){
1681
			$ignored_model = $ignore_this_model_obj->get_model();
1682
		}else{
1683
			$ignored_model = null;
1684
		}
1685
		//now check all the relations of $this_model_obj_or_id and see if there
1686
		//are any related model objects blocking it?
1687
		$is_blocked = false;
1688
		foreach($this->_model_relations as $relation_name => $relation_obj){
1689
			if( $relation_obj->block_delete_if_related_models_exist()){
1690
				//if $ignore_this_model_obj was supplied, then for the query
1691
				//on that model needs to be told to ignore $ignore_this_model_obj
1692
				if($ignored_model && $relation_name === $ignored_model->get_this_model_name()){
1693
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id,array(
1694
					array($ignored_model->get_primary_key_field()->get_name() => array('!=',$ignore_this_model_obj->ID()))));
0 ignored issues
show
Bug introduced by
It seems like $ignore_this_model_obj is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
1695
				}else{
1696
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1697
				}
1698
1699
				if($related_model_objects){
0 ignored issues
show
Bug Best Practice introduced by
The expression $related_model_objects of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1700
					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1701
					$is_blocked = true;
1702
				}
1703
			}
1704
		}
1705
		return $is_blocked;
1706
	}
1707
1708
1709
1710
	/**
1711
	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as well.
1712
	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1713
	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model info
1714
	 * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1715
	 * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1716
	 * @throws EE_Error
1717
	 * @return string    everything that comes after the WHERE statement.
1718
	 */
1719
	protected function _setup_ids_for_delete( $objects_for_deletion, $allow_blocking = true) {
1720
		if($this->has_primary_key_field()){
1721
			$primary_table = $this->_get_main_table();
1722
			$other_tables = $this->_get_other_tables();
1723
			$deletes = $query = array();
1724
			foreach ( $objects_for_deletion as $delete_object ) {
1725
				//before we mark this object for deletion,
1726
				//make sure there's no related objects blocking its deletion (if we're checking)
1727
				if (
1728
					$allow_blocking
1729
				    && $this->delete_is_blocked_by_related_models(
1730
						$delete_object[ $primary_table->get_fully_qualified_pk_column() ]
1731
					)
1732
				) {
1733
					continue;
1734
				}
1735
				//primary table deletes
1736
				if ( isset( $delete_object[ $primary_table->get_fully_qualified_pk_column() ] ) ) {
1737
					$deletes[ $primary_table->get_fully_qualified_pk_column() ][] = $delete_object[ $primary_table->get_fully_qualified_pk_column() ];
1738
				}
1739
				//other tables
1740
				if ( ! empty( $other_tables ) ) {
1741
					foreach ( $other_tables as $ot ) {
1742
						//first check if we've got the foreign key column here.
1743 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_fk_column() ] ) ) {
1744
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_fk_column() ];
1745
						}
1746
						// wait! it's entirely possible that we'll have a the primary key
1747
						// for this table in here, if it's a foreign key for one of the other secondary tables
1748 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_pk_column() ] ) ) {
1749
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_pk_column() ];
1750
						}
1751
						// finally, it is possible that the fk for this table is found
1752
						// in the fully qualified pk column for the fk table, so let's see if that's there!
1753 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_pk_on_fk_table() ] ) ) {
1754
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_pk_column() ];
1755
						}
1756
					}
1757
				}
1758
			}
1759
1760
			//we should have deletes now, so let's just go through and setup the where statement
1761
			foreach ( $deletes as $column => $values ) {
1762
				//make sure we have unique $values;
1763
				$values = array_unique($values);
1764
				$query[] = $column . ' IN(' . implode(",",$values) . ')';
1765
			}
1766
1767
			return !empty($query) ? implode(' AND ', $query ) : '';
1768
		}elseif(count($this->get_combined_primary_key_fields()) > 1){
1769
			$ways_to_identify_a_row = array();
1770
			$fields = $this->get_combined_primary_key_fields();
1771
			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1772
			foreach($objects_for_deletion as  $delete_object){
1773
				$values_for_each_cpk_for_a_row = array();
1774
				foreach($fields as $cpk_field){
1775
					$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()."=".$delete_object[$cpk_field->get_qualified_column()];
1776
				}
1777
				$ways_to_identify_a_row[] = "(".implode(" AND ",$values_for_each_cpk_for_a_row).")";
1778
			}
1779
			return implode(" OR ",$ways_to_identify_a_row);
1780
		}else{
1781
			//so there's no primary key and no combined key...
1782
			//sorry, can't help you
1783
			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key", "event_espresso"),get_class($this)));
1784
		}
1785
	}
1786
1787
1788
1789
	/**
1790
	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
1791
	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's column
1792
	 *
1793
	 * @param array  $query_params   like EEM_Base::get_all's
1794
	 * @param string $field_to_count field on model to count by (not column name)
1795
	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
1796
	 * @return int
1797
	 * @throws \EE_Error
1798
	 */
1799
	public function count($query_params =array(),$field_to_count = NULL, $distinct = FALSE){
1800
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1801
		if($field_to_count){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_count of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1802
			$field_obj = $this->field_settings_for($field_to_count);
1803
			$column_to_count = $field_obj->get_qualified_column();
1804
		}elseif($this->has_primary_key_field ()){
1805
			$pk_field_obj = $this->get_primary_key_field();
1806
			$column_to_count = $pk_field_obj->get_qualified_column();
1807
		}else{//there's no primary key
1808
			$column_to_count = '*';
1809
		}
1810
1811
		$column_to_count = $distinct ? "DISTINCT (" . $column_to_count . " )" : $column_to_count;
1812
		$SQL ="SELECT COUNT(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1813
		return (int)$this->_do_wpdb_query( 'get_var', array( $SQL) );
1814
	}
1815
1816
1817
1818
	/**
1819
	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
1820
	 *
1821
	 * @param array  $query_params like EEM_Base::get_all
1822
	 * @param string $field_to_sum name of field (array key in $_fields array)
1823
	 * @return float
1824
	 * @throws \EE_Error
1825
	 */
1826
	public function sum($query_params, $field_to_sum = NULL){
1827
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1828
1829
		if($field_to_sum){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_sum of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1830
			$field_obj = $this->field_settings_for($field_to_sum);
1831
1832
		}else{
1833
			$field_obj = $this->get_primary_key_field();
1834
		}
1835
		$column_to_count = $field_obj->get_qualified_column();
1836
1837
		$SQL ="SELECT SUM(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1838
		$return_value = $this->_do_wpdb_query('get_var',array( $SQL ) );
1839
		$data_type = $field_obj->get_wpdb_data_type();
1840
		if( $data_type === '%d' || $data_type === '%s' ){
1841
			return (float)$return_value;
1842
		}else{//must be %f
1843
			return (float)$return_value;
1844
		}
1845
	}
1846
1847
1848
1849
	/**
1850
	 * Just calls the specified method on $wpdb with the given arguments
1851
	 * Consolidates a little extra error handling code
1852
	 * @param string $wpdb_method
1853
	 * @param array  $arguments_to_provide
1854
	 * @throws EE_Error
1855
	 * @global wpdb $wpdb
1856
	 * @return mixed
1857
	 */
1858
	protected function _do_wpdb_query( $wpdb_method, $arguments_to_provide ){
1859
		//if we're in maintenance mode level 2, DON'T run any queries
1860
		//because level 2 indicates the database needs updating and
1861
		//is probably out of sync with the code
1862
		if( ! EE_Maintenance_Mode::instance()->models_can_query()){
1863
			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.", "event_espresso")));
1864
		}
1865
		/** @type WPDB $wpdb */
1866
		global $wpdb;
1867 View Code Duplication
		if( ! method_exists( $wpdb, $wpdb_method ) ){
1868
			throw new EE_Error( sprintf( __( 'There is no method named "%s" on Wordpress\' $wpdb object','event_espresso' ), $wpdb_method ) );
1869
		}
1870
		if( WP_DEBUG ){
1871
			$old_show_errors_value = $wpdb->show_errors;
1872
			$wpdb->show_errors( FALSE );
1873
		}
1874
		$result = $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
1875
		$this->show_db_query_if_previously_requested( $wpdb->last_query );
1876
		if( WP_DEBUG ){
1877
			$wpdb->show_errors( $old_show_errors_value );
0 ignored issues
show
Bug introduced by
The variable $old_show_errors_value 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...
1878
			if( ! empty( $wpdb->last_error ) ){
1879
				throw new EE_Error( sprintf( __( 'WPDB Error: "%s"', 'event_espresso' ), $wpdb->last_error ) );
1880
			}elseif( $result === false ){
1881
				throw new EE_Error( sprintf( __( 'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"', 'event_espresso' ), $wpdb_method, var_export( $arguments_to_provide, true ) ) );
1882
			}
1883
		}elseif( $result === false ) {
1884
			EE_Error::add_error( sprintf( __( 'A database error has occurred. Turn on WP_DEBUG for more information.', 'event_espresso' )), __FILE__, __FUNCTION__, __LINE__);
1885
		}
1886
		return $result;
1887
	}
1888
1889
1890
1891
	/**
1892
	 * Attempts to run the indicated WPDB method with the provided arguments,
1893
	 * and if there's an error tries to verify the DB is correct. Uses
1894
	 * the static property EEM_Base::$_db_verification_level to determine whether
1895
	 * we should try to fix the EE core db, the addons, or just give up
1896
	 * @param string $wpdb_method
1897
	 * @param array $arguments_to_provide
1898
	 * @return mixed
1899
	 */
1900
	private function _process_wpdb_query( $wpdb_method, $arguments_to_provide ) {
1901
		/** @type WPDB $wpdb */
1902
		global $wpdb;
1903
		$wpdb->last_error = null;
1904
		$result = call_user_func_array( array( $wpdb, $wpdb_method ), $arguments_to_provide );
1905
		// was there an error running the query? but we don't care on new activations
1906
		// (we're going to setup the DB anyway on new activations)
1907
		if ( ( $result === false || ! empty( $wpdb->last_error ) )
1908
			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
1909
		) {
1910
			switch ( EEM_Base::$_db_verification_level ) {
1911
1912
				case EEM_Base::db_verified_none :
1913
					// let's double-check core's DB
1914
					$error_message = $this->_verify_core_db( $wpdb_method, $arguments_to_provide );
1915
					break;
1916
1917
				case EEM_Base::db_verified_core :
1918
					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
1919
					$error_message = $this->_verify_addons_db( $wpdb_method, $arguments_to_provide );
1920
					break;
1921
1922
				case EEM_Base::db_verified_addons :
1923
					// ummmm... you in trouble
1924
					return $result;
1925
					break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1926
			}
1927
			if ( ! empty( $error_message ) ) {
1928
				EE_Log::instance()->log( __FILE__, __FUNCTION__, $error_message, 'error' );
1929
				trigger_error( $error_message );
1930
			}
1931
			return $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
1932
1933
		}
1934
1935
		return $result;
1936
	}
1937
1938
1939
1940
	/**
1941
	 * Verifies the EE core database is up-to-date and records that we've done it on
1942
	 * EEM_Base::$_db_verification_level
1943
	 * @param string $wpdb_method
1944
	 * @param array $arguments_to_provide
1945
	 * @return string
1946
	 */
1947 View Code Duplication
	private function _verify_core_db( $wpdb_method, $arguments_to_provide ){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1948
		/** @type WPDB $wpdb */
1949
		global $wpdb;
1950
		//ok remember that we've already attempted fixing the core db, in case the problem persists
1951
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
1952
		$error_message = sprintf(
1953
			__( 'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB', 'event_espresso' ),
1954
			$wpdb->last_error,
1955
			$wpdb_method,
1956
			json_encode( $arguments_to_provide )
1957
		);
1958
		EE_System::instance()->initialize_db_if_no_migrations_required( false, true );
1959
		return $error_message;
1960
	}
1961
1962
1963
1964
	/**
1965
	 * Verifies the EE addons' database is up-to-date and records that we've done it on
1966
	 * EEM_Base::$_db_verification_level
1967
	 * @param $wpdb_method
1968
	 * @param $arguments_to_provide
1969
	 * @return string
1970
	 */
1971 View Code Duplication
	private function _verify_addons_db( $wpdb_method, $arguments_to_provide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1972
		/** @type WPDB $wpdb */
1973
		global $wpdb;
1974
		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
1975
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
1976
		$error_message = sprintf(
1977
			__( 'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB', 'event_espresso' ),
1978
			$wpdb->last_error,
1979
			$wpdb_method,
1980
			json_encode( $arguments_to_provide )
1981
		);
1982
		EE_System::instance()->initialize_addons();
1983
		return $error_message;
1984
	}
1985
1986
1987
1988
	/**
1989
	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
1990
	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
1991
	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING ..."
1992
	 * @param EE_Model_Query_Info_Carrier $model_query_info
1993
	 * @return string
1994
	 */
1995
	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info){
1996
		return " FROM ".$model_query_info->get_full_join_sql().
1997
				$model_query_info->get_where_sql().
1998
				$model_query_info->get_group_by_sql().
1999
				$model_query_info->get_having_sql().
2000
				$model_query_info->get_order_by_sql().
2001
				$model_query_info->get_limit_sql();
2002
	}
2003
2004
	/**
2005
	 * Set to easily debug the next X queries ran from this model.
2006
	 * @param int $count
2007
	 */
2008
	public function show_next_x_db_queries($count = 1){
2009
		$this->_show_next_x_db_queries = $count;
2010
	}
2011
2012
2013
2014
	/**
2015
	 * @param $sql_query
2016
	 */
2017
	public function show_db_query_if_previously_requested($sql_query){
2018
		if($this->_show_next_x_db_queries > 0){
2019
			echo $sql_query;
2020
			$this->_show_next_x_db_queries--;
2021
		}
2022
	}
2023
2024
2025
2026
	/**
2027
	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2028
	 * There are the 3 cases:
2029
	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If $otherModelObject has no ID, it is first saved.
2030
	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj has no ID, it is first saved.
2031
	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2032
	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the join table
2033
	 *
2034
	 * @param        EE_Base_Class                     /int $thisModelObject
2035
	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2036
	 * @param string $relationName                     , key in EEM_Base::_relations
2037
	 *                                                 an attendee to a group, you also want to specify which role they will have in that group. So you would use this parameter to specify array('role-column-name'=>'role-id')
2038
	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation to for relation to methods that allow you to further specify extra columns to join by (such as HABTM).  Keep in mind that the only acceptable query_params is strict "col" => "value" pairs because these will be inserted in any new rows created as well.
2039
	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2040
	 * @throws \EE_Error
2041
	 */
2042
	public function add_relationship_to($id_or_obj,$other_model_id_or_obj, $relationName, $extra_join_model_fields_n_values = array()){
2043
		$relation_obj = $this->related_settings_for($relationName);
2044
		return $relation_obj->add_relation_to( $id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2045
	}
2046
2047
2048
2049
	/**
2050
	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2051
	 * There are the 3 cases:
2052
	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an error
2053
	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws an error
2054
	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2055
	 *
2056
	 * @param        EE_Base_Class /int $id_or_obj
2057
	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2058
	 * @param string $relationName key in EEM_Base::_relations
2059
	 * @return boolean of success
2060
	 * @throws \EE_Error
2061
	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to methods that allow you to further specify extra columns to join by (such as HABTM).  Keep in mind that the only acceptable query_params is strict "col" => "value" pairs because these will be inserted in any new rows created as well.
2062
	 */
2063
	public function remove_relationship_to($id_or_obj,  $other_model_id_or_obj, $relationName, $where_query= array() ){
2064
		$relation_obj = $this->related_settings_for($relationName);
2065
		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query );
2066
	}
2067
2068
2069
2070
	/**
2071
	 * @param mixed           $id_or_obj
2072
	 * @param string          $relationName
2073
	 * @param array           $where_query_params
2074
	 * @param EE_Base_Class[] objects to which relations were removed
2075
	 * @return \EE_Base_Class[]
2076
	 * @throws \EE_Error
2077
	 */
2078
	public function remove_relations($id_or_obj,$relationName,$where_query_params = array()){
2079
		$relation_obj = $this->related_settings_for($relationName);
2080
		return $relation_obj->remove_relations($id_or_obj, $where_query_params );
2081
	}
2082
2083
2084
2085
	/**
2086
	 * Gets all the related items of the specified $model_name, using $query_params.
2087
	 * Note: by default, we remove the "default query params"
2088
	 * because we want to get even deleted items etc.
2089
	 *
2090
	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2091
	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2092
	 * @param array  $query_params like EEM_Base::get_all
2093
	 * @return EE_Base_Class[]
2094
	 * @throws \EE_Error
2095
	 */
2096
	public function get_all_related($id_or_obj, $model_name, $query_params = null){
2097
		$model_obj = $this->ensure_is_obj($id_or_obj);
2098
		$relation_settings = $this->related_settings_for($model_name);
2099
		return $relation_settings->get_all_related($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2097 can be null; however, EE_Model_Relation_Base::get_all_related() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $query_params defined by parameter $query_params on line 2096 can also be of type null; however, EE_Model_Relation_Base::get_all_related() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
2100
	}
2101
2102
2103
2104
	/**
2105
	 * Deletes all the model objects across the relation indicated by $model_name
2106
	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2107
	 * However, if the model objects can't be deleted because of blocking related model objects, then
2108
	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2109
	 *
2110
	 * @param EE_Base_Class|int|string $id_or_obj
2111
	 * @param string                   $model_name
2112
	 * @param array                    $query_params
2113
	 * @return int how many deleted
2114
	 * @throws \EE_Error
2115
	 */
2116
	public function delete_related($id_or_obj,$model_name, $query_params = array()){
2117
		$model_obj = $this->ensure_is_obj($id_or_obj);
2118
		$relation_settings = $this->related_settings_for($model_name);
2119
		return $relation_settings->delete_all_related($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2117 can be null; however, EE_Model_Relation_Base::delete_all_related() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2120
	}
2121
2122
2123
2124
	/**
2125
	 * Hard deletes all the model objects across the relation indicated by $model_name
2126
	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2127
	 * the model objects can't be hard deleted because of blocking related model objects,
2128
	 * just does a soft-delete on them instead.
2129
	 *
2130
	 * @param EE_Base_Class|int|string $id_or_obj
2131
	 * @param string                   $model_name
2132
	 * @param array                    $query_params
2133
	 * @return int how many deleted
2134
	 * @throws \EE_Error
2135
	 */
2136
	public function delete_related_permanently($id_or_obj,$model_name, $query_params = array()){
2137
		$model_obj = $this->ensure_is_obj($id_or_obj);
2138
		$relation_settings = $this->related_settings_for($model_name);
2139
		return $relation_settings->delete_related_permanently($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2137 can be null; however, EE_Model_Relation_Base::...e_related_permanently() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2140
	}
2141
2142
2143
2144
	/**
2145
	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2146
	 * unless otherwise specified in the $query_params
2147
	 *
2148
	 * @param        int             /EE_Base_Class $id_or_obj
2149
	 * @param string $model_name     like 'Event', or 'Registration'
2150
	 * @param array  $query_params   like EEM_Base::get_all's
2151
	 * @param string $field_to_count name of field to count by. By default, uses primary key
2152
	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
2153
	 * @return int
2154
	 * @throws \EE_Error
2155
	 */
2156
	public function count_related($id_or_obj,$model_name,$query_params = array(),$field_to_count = null, $distinct = FALSE){
2157
		$related_model = $this->get_related_model_obj($model_name);
2158
		//we're just going to use the query params on the related model's normal get_all query,
2159
		//except add a condition to say to match the current mod
2160
		if( ! isset($query_params['default_where_conditions'])){
2161
			$query_params['default_where_conditions']='none';
2162
		}
2163
		$this_model_name = $this->get_this_model_name();
2164
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2165
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2166
		return $related_model->count($query_params,$field_to_count,$distinct);
2167
	}
2168
2169
2170
2171
	/**
2172
	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2173
	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2174
	 *
2175
	 * @param        int           /EE_Base_Class $id_or_obj
2176
	 * @param string $model_name   like 'Event', or 'Registration'
2177
	 * @param array  $query_params like EEM_Base::get_all's
2178
	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2179
	 * @return float
2180
	 * @throws \EE_Error
2181
	 */
2182
	public function sum_related($id_or_obj,$model_name,$query_params,$field_to_sum = null){
2183
		$related_model = $this->get_related_model_obj($model_name);
2184
		if( ! is_array( $query_params ) ){
2185
			EE_Error::doing_it_wrong('EEM_Base::sum_related', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
2186
			$query_params = array();
2187
		}
2188
		//we're just going to use the query params on the related model's normal get_all query,
2189
		//except add a condition to say to match the current mod
2190
		if( ! isset($query_params['default_where_conditions'])){
2191
			$query_params['default_where_conditions']='none';
2192
		}
2193
		$this_model_name = $this->get_this_model_name();
2194
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2195
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2196
		return $related_model->sum($query_params,$field_to_sum);
2197
	}
2198
2199
2200
2201
	/**
2202
	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given $modelObject
2203
	 *
2204
	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2205
	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2206
	 * @param array               $query_params     like EEM_Base::get_all's
2207
	 * @return EE_Base_Class
2208
	 * @throws \EE_Error
2209
	 */
2210
	public function get_first_related( EE_Base_Class $id_or_obj, $other_model_name, $query_params ){
2211
		$query_params['limit']=1;
2212
		$results = $this->get_all_related($id_or_obj,$other_model_name,$query_params);
2213
		if( $results ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2214
			return array_shift($results);
2215
		}else{
2216
			return null;
2217
		}
2218
2219
	}
2220
2221
	/**
2222
	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2223
	 * @return string
2224
	 */
2225
	public function get_this_model_name(){
2226
		return str_replace("EEM_","",get_class($this));
2227
	}
2228
2229
	/**
2230
	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2231
	 * @return EE_Any_Foreign_Model_Name_Field
2232
	 * @throws EE_Error
2233
	 */
2234
	public function get_field_containing_related_model_name(){
2235
		foreach($this->field_settings(true) as $field){
2236
			if($field instanceof EE_Any_Foreign_Model_Name_Field){
2237
				$field_with_model_name = $field;
2238
			}
2239
		}
2240 View Code Duplication
		if( !isset($field_with_model_name) || !$field_with_model_name ){
2241
			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"), $this->get_this_model_name() ));
2242
		}
2243
		return $field_with_model_name;
2244
	}
2245
2246
2247
2248
	/**
2249
	 * Inserts a new entry into the database, for each table.
2250
	 *
2251
	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2252
	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2253
	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2254
	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2255
	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2256
	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2257
	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if $values_already_prepared_by_model_object is false,
2258
	 * in the model object's domain if $values_already_prepared_by_model_object is true. See comment about this at the top of EEM_Base)
2259
	 * @return int new primary key on main table that got inserted
2260
	 * @throws EE_Error
2261
	 */
2262
	public function insert($field_n_values){
2263
		/**
2264
		 * Filters the fields and their values before inserting an item using the models
2265
		 * @param array $fields_n_values keys are the fields and values are their new values
2266
		 * @param EEM_Base $model the model used
2267
		 */
2268
		$field_n_values = (array)apply_filters( 'FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this );
2269
		if($this->_satisfies_unique_indexes($field_n_values)){
2270
			$main_table = $this->_get_main_table();
2271
			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2272
			if( $new_id !== false ) {
2273
				foreach($this->_get_other_tables() as $other_table){
2274
					$this->_insert_into_specific_table($other_table, $field_n_values,$new_id);
2275
				}
2276
			}
2277
			/**
2278
			 * Done just after attempting to insert a new model object
2279
			 *
2280
			 * @param EEM_Base $model used
2281
			 * @param array $fields_n_values fields and their values
2282
			 * @param int|string the ID of the newly-inserted model object
2283
			 */
2284
			do_action( 'AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id );
2285
			return $new_id;
2286
		}else{
2287
			return FALSE;
2288
		}
2289
	}
2290
2291
2292
2293
	/**
2294
	 * Checks that the result would satisfy the unique indexes on this model
2295
	 *
2296
	 * @param array  $field_n_values
2297
	 * @param string $action
2298
	 * @return boolean
2299
	 * @throws \EE_Error
2300
	 */
2301
	protected function _satisfies_unique_indexes($field_n_values,$action = 'insert'){
2302
		foreach($this->unique_indexes() as $index_name => $index){
2303
			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2304
			if($this->exists(array($uniqueness_where_params))){
2305
				EE_Error::add_error(
2306
					sprintf(
2307
						__(
2308
							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2309
							"event_espresso"
2310
						),
2311
						$action,
2312
						$this->_get_class_name(),
2313
						$index_name,
2314
						implode( ",", $index->field_names() ),
2315
						http_build_query( $uniqueness_where_params )
2316
					),
2317
					__FILE__,
2318
					__FUNCTION__,
2319
					__LINE__
2320
				);
2321
				return false;
2322
			}
2323
		}
2324
		return true;
2325
	}
2326
2327
2328
2329
	/**
2330
	 * Checks the database for an item that conflicts (ie, if this item were
2331
	 * saved to the DB would break some uniqueness requirement, like a primary key
2332
	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2333
	 * can be either an EE_Base_Class or an array of fields n values
2334
	 * @param EE_Base_Class|array $obj_or_fields_array
2335
	 * @param boolean $include_primary_key whether to use the model object's primary key when looking for conflicts
2336
	 * (ie, if false, we ignore the model object's primary key when finding "conflicts".
2337
	 * If true, it's also considered). Only works for INT primary key- STRING primary keys cannot be ignored
2338
	 * @throws EE_Error
2339
	 * @return EE_Base_Class
2340
	 */
2341
	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true ){
2342 View Code Duplication
		if($obj_or_fields_array instanceof EE_Base_Class){
2343
			$fields_n_values = $obj_or_fields_array->model_field_array();
2344
		}elseif( is_array($obj_or_fields_array)){
2345
			$fields_n_values = $obj_or_fields_array;
2346
		}else{
2347
			throw new EE_Error(
2348
				sprintf(
2349
					__(
2350
						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2351
						"event_espresso"
2352
					),
2353
					get_class( $this ),
2354
					$obj_or_fields_array
2355
				)
2356
			);
2357
		}
2358
		$query_params = array();
2359
		if( $this->has_primary_key_field() &&
2360
				( $include_primary_key || $this->get_primary_key_field() instanceof EE_Primary_Key_String_Field) &&
2361
				isset($fields_n_values[$this->primary_key_name()])){
2362
			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2363
		}
2364
		foreach($this->unique_indexes() as $unique_index_name=>$unique_index){
2365
			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2366
			$query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2367
		}
2368
		//if there is nothing to base this search on, then we shouldn't find anything
2369
		if( empty( $query_params ) ){
2370
			return array();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type documented by EEM_Base::get_one_conflicting of type EE_Base_Class|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
2371
		}else{
2372
			return $this->get_one($query_params);
2373
		}
2374
	}
2375
2376
2377
2378
	/**
2379
	 * Like count, but is optimized and returns a boolean instead of an int
2380
	 *
2381
	 * @param array $query_params
2382
	 * @return boolean
2383
	 * @throws \EE_Error
2384
	 */
2385
	public function exists($query_params){
2386
		$query_params['limit'] = 1;
2387
		return $this->count($query_params) > 0;
2388
	}
2389
2390
2391
2392
	/**
2393
	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2394
	 *
2395
	 * @param int|string $id
2396
	 * @return boolean
2397
	 * @throws \EE_Error
2398
	 */
2399
	public function exists_by_ID($id){
2400
		return $this->exists(array('default_where_conditions'=>'none', array($this->primary_key_name() => $id)));
2401
	}
2402
2403
2404
2405
	/**
2406
	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2407
	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2408
	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2409
	 * on the main table)
2410
	 * This is protected rather than private because private is not accessible to any child methods and there MAY be cases where we want to call it directly rather than via insert().
2411
	 * @access   protected
2412
	 * @param EE_Table_Base $table
2413
	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or float
2414
	 * @param int  $new_id 	for now we assume only int keys
2415
	 * @throws EE_Error
2416
	 * @global WPDB $wpdb only used to get the $wpdb->insert_id after performing an insert
2417
	 * @return int ID of new row inserted, or FALSE on failure
2418
	 */
2419
	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0 ){
2420
		global $wpdb;
2421
		$insertion_col_n_values = array();
2422
		$format_for_insertion = array();
2423
		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2424
		foreach($fields_on_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_on_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
2425
			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2426
			if($field_obj->is_auto_increment()){
2427
				continue;
2428
			}
2429
			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2430
			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2431
			if( $prepared_value !== NULL ){
2432
				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2433
				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2434
			}
2435
		}
2436
2437
		if($table instanceof EE_Secondary_Table && $new_id){
2438
			//its not the main table, so we should have already saved the main table's PK which we just inserted
2439
			//so add the fk to the main table as a column
2440
			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2441
			$format_for_insertion[]='%d';//yes right now we're only allowing these foreign keys to be INTs
2442
		}
2443
		//insert the new entry
2444
		$result = $this->_do_wpdb_query( 'insert', array( $table->get_table_name(), $insertion_col_n_values, $format_for_insertion ) );
2445
		if( $result === false ) {
2446
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by EEM_Base::_insert_into_specific_table of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
2447
		}
2448
		//ok, now what do we return for the ID of the newly-inserted thing?
2449
		if($this->has_primary_key_field()){
2450
			if($this->get_primary_key_field()->is_auto_increment()){
2451
				return $wpdb->insert_id;
2452
			}else{
2453
				//it's not an auto-increment primary key, so
2454
				//it must have been supplied
2455
				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2456
			}
2457
		}else{
2458
			//we can't return a  primary key because there is none. instead return
2459
			//a unique string indicating this model
2460
			return $this->get_index_primary_key_string($fields_n_values);
2461
		}
2462
	}
2463
2464
2465
2466
	/**
2467
	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2468
	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2469
	 * and there is no default, we pass it along. WPDB will take care of it)
2470
	 *
2471
	 * @param EE_Model_Field_Base $field_obj
2472
	 * @param array               $fields_n_values
2473
	 * @return mixed string|int|float depending on what the table column will be expecting
2474
	 * @throws \EE_Error
2475
	 */
2476
	protected function _prepare_value_or_use_default( $field_obj, $fields_n_values ){
2477
		//if this field doesn't allow nullable, don't allow it
2478
		if( ! $field_obj->is_nullable() && (
2479
				! isset( $fields_n_values[ $field_obj->get_name() ] ) ||
2480
				$fields_n_values[ $field_obj->get_name() ] === NULL ) ){
2481
			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2482
		}
2483
		$unprepared_value = isset( $fields_n_values[ $field_obj->get_name() ] ) ? $fields_n_values[ $field_obj->get_name() ] : NULL;
2484
		return $this->_prepare_value_for_use_in_db( $unprepared_value, $field_obj);
2485
	}
2486
2487
2488
	/**
2489
	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's prepare_for_use_in_db method on the value,
2490
	 * and depending on $value_already_prepare_by_model_obj, may also call the field's prepare_for_set() method.
2491
	 * @param mixed $value value in the client code domain if $value_already_prepared_by_model_object is false, otherwise a value
2492
	 * in the model object's domain (see lengthy comment at top of file)
2493
	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume $value is a custom selection
2494
	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2495
	 */
2496
	private function _prepare_value_for_use_in_db($value, $field){
2497
		if($field && $field instanceof EE_Model_Field_Base){
2498
			switch( $this->_values_already_prepared_by_model_object ){
2499
				/** @noinspection PhpMissingBreakStatementInspection */
2500
				case self::not_prepared_by_model_object:
2501
					$value = $field->prepare_for_set($value);
2502
					//purposefully left out "return"
2503
				case self::prepared_by_model_object:
2504
					$value = $field->prepare_for_use_in_db($value);
2505
				case self::prepared_for_use_in_db:
2506
					//leave the value alone
2507
			}
2508
			return $value;
2509
		}else{
2510
			return $value;
2511
		}
2512
	}
2513
2514
	/**
2515
	 * Returns the main table on this model
2516
	 * @return EE_Primary_Table
2517
	 * @throws EE_Error
2518
	 */
2519
	protected function _get_main_table(){
2520
		foreach($this->_tables as $table){
2521
			if($table instanceof EE_Primary_Table){
2522
				return $table;
2523
			}
2524
		}
2525
		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor','event_espresso'),get_class($this)));
2526
	}
2527
2528
2529
2530
	/**
2531
	 * table
2532
	 * returns EE_Primary_Table table name
2533
	 *
2534
	 * @return string
2535
	 * @throws \EE_Error
2536
	 */
2537
	public function table() {
2538
		return $this->_get_main_table()->get_table_name();
2539
	}
2540
2541
	/**
2542
	 * table
2543
	 * returns first EE_Secondary_Table table name
2544
	 * @return string
2545
	 */
2546
	public function second_table() {
2547
		// grab second table from tables array
2548
		$second_table = end( $this->_tables );
2549
		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : NULL;
2550
	}
2551
2552
2553
2554
	/**
2555
	 * get_table_obj_by_alias
2556
	 * returns table name given it's alias
2557
	 *
2558
	 * @param string $table_alias
2559
	 * @return EE_Primary_Table | EE_Secondary_Table
2560
	 */
2561
	public function get_table_obj_by_alias( $table_alias = '' ) {
2562
		return isset( $this->_tables[ $table_alias ] ) ? $this->_tables[ $table_alias ] : NULL;
2563
	}
2564
2565
2566
2567
	/**
2568
	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2569
	 * @return EE_Secondary_Table[]
2570
	 */
2571
	protected function _get_other_tables(){
2572
		$other_tables =array();
2573
		foreach($this->_tables as $table_alias => $table){
2574
			if($table instanceof EE_Secondary_Table){
2575
				$other_tables[$table_alias] = $table;
2576
			}
2577
		}
2578
		return $other_tables;
2579
	}
2580
2581
	/**
2582
	 * Finds all the fields that correspond to the given table
2583
	 * @param string $table_alias, array key in EEM_Base::_tables
0 ignored issues
show
Documentation introduced by
There is no parameter named $table_alias,. Did you maybe mean $table_alias?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
2584
	 * @return EE_Model_Field_Base[]
2585
	 */
2586
	public function _get_fields_for_table($table_alias){
2587
		return $this->_fields[$table_alias];
2588
	}
2589
2590
2591
2592
	/**
2593
	 * Recurses through all the where parameters, and finds all the related models we'll need
2594
	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't need any
2595
	 * related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related Registration model.
2596
	 * If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the related Registration, Transaction, and Payment models.
2597
	 *
2598
	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2599
	 * @return EE_Model_Query_Info_Carrier
2600
	 * @throws \EE_Error
2601
	 */
2602
	public function _extract_related_models_from_query($query_params){
2603
		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2604
		if ( array_key_exists( 0, $query_params ) ) {
2605
			$this->_extract_related_models_from_sub_params_array_keys( $query_params[0], $query_info_carrier, 0 );
2606
		}
2607 View Code Duplication
		if ( array_key_exists( 'group_by', $query_params ) ) {
2608
			if ( is_array( $query_params['group_by'] ) ) {
2609
				$this->_extract_related_models_from_sub_params_array_values(
2610
					$query_params['group_by'],
2611
					$query_info_carrier,
2612
					'group_by'
2613
				);
2614
			} elseif ( ! empty ( $query_params['group_by'] ) ) {
2615
				$this->_extract_related_model_info_from_query_param(
2616
					$query_params['group_by'],
2617
					$query_info_carrier,
2618
					'group_by'
2619
				);
2620
			}
2621
		}
2622
		if ( array_key_exists( 'having', $query_params ) ) {
2623
			$this->_extract_related_models_from_sub_params_array_keys(
2624
				$query_params[0],
2625
				$query_info_carrier,
2626
				'having'
2627
			);
2628
		}
2629 View Code Duplication
		if ( array_key_exists( 'order_by', $query_params ) ) {
2630
			if ( is_array( $query_params['order_by'] ) ) {
2631
				$this->_extract_related_models_from_sub_params_array_keys(
2632
					$query_params['order_by'],
2633
					$query_info_carrier,
2634
					'order_by'
2635
				);
2636
			} elseif ( ! empty( $query_params['order_by'] ) ) {
2637
				$this->_extract_related_model_info_from_query_param(
2638
					$query_params['order_by'],
2639
					$query_info_carrier,
2640
					'order_by'
2641
				);
2642
			}
2643
		}
2644
		if ( array_key_exists( 'force_join', $query_params ) ) {
2645
			$this->_extract_related_models_from_sub_params_array_values(
2646
				$query_params['force_join'],
2647
				$query_info_carrier,
2648
				'force_join'
2649
			);
2650
		}
2651
		return $query_info_carrier;
2652
	}
2653
2654
	/**
2655
	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
2656
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2657
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2658
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2659
	 * @throws EE_Error
2660
	 * @return \EE_Model_Query_Info_Carrier
2661
	 */
2662
	private function _extract_related_models_from_sub_params_array_keys($sub_query_params, EE_Model_Query_Info_Carrier $model_query_info_carrier,$query_param_type){
2663
		if (!empty($sub_query_params)){
2664
			$sub_query_params = (array) $sub_query_params;
2665
			foreach($sub_query_params as $param => $possibly_array_of_params){
2666
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2667
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier,$query_param_type);
2668
2669
				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
2670
				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
2671
				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
2672
				//of array('Registration.TXN_ID'=>23)
2673
				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
2674
				if(in_array($query_param_sans_stars, $this->_logic_query_param_keys,true)){
2675
					if (! is_array($possibly_array_of_params)){
2676
						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))", "event_espresso"),
2677
							$param,$possibly_array_of_params));
2678
					}else{
2679
						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params, $model_query_info_carrier,$query_param_type);
2680
					}
2681
				}elseif($query_param_type === 0 //ie WHERE
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param_type (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
2682
						&& is_array($possibly_array_of_params)
2683
						&& isset($possibly_array_of_params[2])
2684
						&& $possibly_array_of_params[2] == true){
2685
					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
2686
					//indicating that $possible_array_of_params[1] is actually a field name,
2687
					//from which we should extract query parameters!
2688 View Code Duplication
					if( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1] ) ) {
2689
						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s", "event_espresso"),$query_param_type,implode(",",$possibly_array_of_params)));
2690
					}
2691
					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1], $model_query_info_carrier, $query_param_type);
2692
				}
2693
			}
2694
		}
2695
		return $model_query_info_carrier;
2696
	}
2697
2698
2699
	/**
2700
	 * For extracting related models from forced_joins, where the array values contain the info about what
2701
	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
2702
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2703
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2704
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2705
	 * @throws EE_Error
2706
	 * @return \EE_Model_Query_Info_Carrier
2707
	 */
2708
	private function _extract_related_models_from_sub_params_array_values($sub_query_params, EE_Model_Query_Info_Carrier $model_query_info_carrier,$query_param_type){
2709
		if (!empty($sub_query_params)){
2710
			if(!is_array($sub_query_params)){
2711
				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),$sub_query_params));
2712
			}
2713
			foreach($sub_query_params as $param){
2714
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2715
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier, $query_param_type);
2716
			}
2717
		}
2718
		return $model_query_info_carrier;
2719
	}
2720
2721
2722
2723
	/**
2724
	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
2725
	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
2726
	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
2727
	 * but use them in a different order. Eg, we need to know what models we are querying
2728
	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on other
2729
	 * models before we can finalize the where clause SQL.
2730
	 * @param array $query_params
2731
	 * @throws EE_Error
2732
	 * @return EE_Model_Query_Info_Carrier
2733
	 */
2734
	public function _create_model_query_info_carrier($query_params){
2735
		if ( ! is_array( $query_params ) ) {
2736
			EE_Error::doing_it_wrong(
2737
				'EEM_Base::_create_model_query_info_carrier',
2738
				sprintf(
2739
					__(
2740
						'$query_params should be an array, you passed a variable of type %s',
2741
						'event_espresso'
2742
					),
2743
					gettype( $query_params )
2744
				),
2745
				'4.6.0'
2746
			);
2747
			$query_params = array();
2748
		}
2749
		$where_query_params = isset( $query_params[0] ) ? $query_params[0] : array();
2750
		//first check if we should alter the query to account for caps or not
2751
		//because the caps might require us to do extra joins
2752
		if ( isset( $query_params['caps'] ) && $query_params['caps'] !== 'none' ) {
2753
			$query_params[0] = $where_query_params = array_replace_recursive(
2754
				$where_query_params,
2755
				$this->caps_where_conditions(
2756
					$query_params['caps']
2757
				)
2758
			);
2759
		}
2760
		$query_object = $this->_extract_related_models_from_query( $query_params );
2761
		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
2762
		foreach ( $where_query_params as $key => $value ) {
2763
			if ( is_int( $key ) ) {
2764
				throw new EE_Error(
2765
					sprintf(
2766
						__(
2767
							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
2768
							"event_espresso"
2769
						),
2770
						$key,
2771
						var_export( $value, true ),
2772
						var_export( $query_params, true ),
2773
						get_class( $this )
2774
					)
2775
				);
2776
			}
2777
		}
2778
		if (
2779
			array_key_exists( 'default_where_conditions', $query_params )
2780
			&& ! empty( $query_params['default_where_conditions'] )
2781
		) {
2782
			$use_default_where_conditions = $query_params['default_where_conditions'];
2783
		} else {
2784
			$use_default_where_conditions = 'all';
2785
		}
2786
		$where_query_params = array_merge(
2787
			$this->_get_default_where_conditions_for_models_in_query(
2788
				$query_object,
2789
				$use_default_where_conditions,
2790
				$where_query_params
2791
			),
2792
			$where_query_params
2793
		);
2794
		$query_object->set_where_sql( $this->_construct_where_clause( $where_query_params ) );
2795
		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
2796
		// So we need to setup a subquery and use that for the main join.
2797
		// Note for now this only works on the primary table for the model.
2798
		// So for instance, you could set the limit array like this:
2799
		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
2800
		if ( array_key_exists( 'on_join_limit', $query_params ) && ! empty( $query_params['on_join_limit'] ) ) {
2801
			$query_object->set_main_model_join_sql(
2802
				$this->_construct_limit_join_select(
2803
					$query_params['on_join_limit'][0],
2804
					$query_params['on_join_limit'][1]
2805
				)
2806
			);
2807
		}
2808
		//set limit
2809
		if ( array_key_exists( 'limit', $query_params ) ) {
2810
			if ( is_array( $query_params['limit'] ) ) {
2811
				if ( ! isset( $query_params['limit'][0], $query_params['limit'][1] ) ) {
2812
					$e = sprintf(
2813
						__(
2814
							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
2815
							"event_espresso"
2816
						),
2817
						http_build_query( $query_params['limit'] )
2818
					);
2819
					throw new EE_Error( $e . "|" . $e );
2820
				}
2821
				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
2822
				$query_object->set_limit_sql( " LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1] );
2823
			} elseif ( ! empty ( $query_params['limit'] ) ) {
2824
				$query_object->set_limit_sql( " LIMIT " . $query_params['limit'] );
2825
			}
2826
		}
2827
		//set order by
2828
		if ( array_key_exists( 'order_by', $query_params ) ) {
2829
			if ( is_array( $query_params['order_by'] ) ) {
2830
				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
2831
				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
2832
				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
2833
				if ( array_key_exists( 'order', $query_params ) ) {
2834
					throw new EE_Error(
2835
						sprintf(
2836
							__(
2837
								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
2838
								"event_espresso"
2839
							),
2840
							get_class( $this ),
2841
							implode( ", ", array_keys( $query_params['order_by'] ) ),
2842
							implode( ", ", $query_params['order_by'] ),
2843
							$query_params['order']
2844
						)
2845
					);
2846
				}
2847
				$this->_extract_related_models_from_sub_params_array_keys(
2848
					$query_params['order_by'],
2849
					$query_object,
2850
					'order_by'
2851
				);
2852
				//assume it's an array of fields to order by
2853
				$order_array = array();
2854
				foreach ( $query_params['order_by'] as $field_name_to_order_by => $order ) {
2855
					$order = $this->_extract_order( $order );
2856
					$order_array[] = $this->_deduce_column_name_from_query_param( $field_name_to_order_by ) . SP . $order;
0 ignored issues
show
Documentation introduced by
$field_name_to_order_by is of type integer|string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2857
				}
2858
				$query_object->set_order_by_sql( " ORDER BY " . implode( ",", $order_array ) );
2859
			} elseif ( ! empty ( $query_params['order_by'] ) ) {
2860
				$this->_extract_related_model_info_from_query_param(
2861
					$query_params['order_by'],
2862
					$query_object,
2863
					'order',
2864
					$query_params['order_by']
2865
				);
2866
				$order = isset( $query_params['order'] )
2867
					? $this->_extract_order( $query_params['order'] )
2868
					: 'DESC';
2869
				$query_object->set_order_by_sql(
2870
					" ORDER BY " . $this->_deduce_column_name_from_query_param( $query_params['order_by'] ) . SP . $order
2871
				);
2872
			}
2873
		}
2874
		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
2875
		if ( ! array_key_exists( 'order_by', $query_params )
2876
		     && array_key_exists( 'order', $query_params )
2877
		     && ! empty( $query_params['order'] )
2878
		) {
2879
			$pk_field = $this->get_primary_key_field();
2880
			$order = $this->_extract_order( $query_params['order'] );
2881
			$query_object->set_order_by_sql( " ORDER BY " . $pk_field->get_qualified_column() . SP . $order );
2882
		}
2883
		//set group by
2884
		if ( array_key_exists( 'group_by', $query_params ) ) {
2885
			if ( is_array( $query_params['group_by'] ) ) {
2886
				//it's an array, so assume we'll be grouping by a bunch of stuff
2887
				$group_by_array = array();
2888
				foreach ( $query_params['group_by'] as $field_name_to_group_by ) {
2889
					$group_by_array[] = $this->_deduce_column_name_from_query_param( $field_name_to_group_by );
2890
				}
2891
				$query_object->set_group_by_sql( " GROUP BY " . implode( ", ", $group_by_array ) );
2892
			} elseif ( ! empty ( $query_params['group_by'] ) ) {
2893
				$query_object->set_group_by_sql(
2894
					" GROUP BY " . $this->_deduce_column_name_from_query_param( $query_params['group_by'] )
2895
				);
2896
			}
2897
		}
2898
		//set having
2899
		if ( array_key_exists( 'having', $query_params ) && $query_params['having'] ) {
2900
			$query_object->set_having_sql( $this->_construct_having_clause( $query_params['having'] ) );
2901
		}
2902
		//now, just verify they didn't pass anything wack
2903
		foreach ( $query_params as $query_key => $query_value ) {
2904 View Code Duplication
			if ( ! in_array( $query_key, $this->_allowed_query_params, true ) ) {
2905
				throw new EE_Error(
2906
					sprintf(
2907
						__(
2908
							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
2909
							'event_espresso'
2910
						),
2911
						$query_key,
2912
						get_class( $this ),
2913
//						print_r( $this->_allowed_query_params, TRUE )
2914
						implode( ',', $this->_allowed_query_params )
2915
					)
2916
				);
2917
			}
2918
		}
2919
		$main_model_join_sql = $query_object->get_main_model_join_sql();
2920
		if ( empty( $main_model_join_sql ) ) {
2921
			$query_object->set_main_model_join_sql( $this->_construct_internal_join() );
2922
		}
2923
		return $query_object;
2924
	}
2925
2926
2927
2928
	/**
2929
	 * Gets the where conditions that should be imposed on the query based on the
2930
	 * context (eg reading frontend, backend, edit or delete).
2931
	 *
2932
	 * @param string $context one of EEM_Base::valid_cap_contexts()
2933
	 * @return array like EEM_Base::get_all() 's $query_params[0]
2934
	 * @throws \EE_Error
2935
	 */
2936
	public function caps_where_conditions( $context = self::caps_read ) {
2937
		EEM_Base::verify_is_valid_cap_context( $context );
2938
		$cap_where_conditions = array();
2939
		$cap_restrictions = $this->caps_missing( $context );
2940
		/**
2941
		 * @var $cap_restrictions EE_Default_Where_Conditions[]
2942
		 */
2943
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
2944
				$cap_where_conditions = array_replace_recursive( $cap_where_conditions, $restriction_if_no_cap->get_default_where_conditions() );
2945
		}
2946
		return apply_filters( 'FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context, $cap_restrictions );
2947
	}
2948
2949
	/**
2950
	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
2951
	 * otherwise throws an exception
2952
	 * @param string $should_be_order_string
2953
	 * @return string either ASC, asc, DESC or desc
2954
	 * @throws EE_Error
2955
	 */
2956 View Code Duplication
	private function _extract_order($should_be_order_string){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2957
		if(in_array($should_be_order_string, $this->_allowed_order_values)){
2958
			return $should_be_order_string;
2959
		}else{
2960
			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ", "event_espresso"),get_class($this),$should_be_order_string));
2961
		}
2962
	}
2963
2964
2965
2966
	/**
2967
	 * Looks at all the models which are included in this query, and asks each
2968
	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
2969
	 * so they can be merged
2970
	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
2971
	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.  'none' means NO default where conditions will be used AT ALL during this query.
2972
	 * 'other_models_only' means default where conditions from other models will be used, but not for this primary model. 'all', the default, means
2973
	 * default where conditions will apply as normal
2974
	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
2975
	 * @throws EE_Error
2976
	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
2977
	 */
2978
	private function _get_default_where_conditions_for_models_in_query(EE_Model_Query_Info_Carrier $query_info_carrier,$use_default_where_conditions = 'all',$where_query_params = array()){
2979
		$allowed_used_default_where_conditions_values = array(
2980
				'all',
2981
				'this_model_only',
2982
				'other_models_only',
2983
				'minimum',
2984
				'none'
2985
			);
2986 View Code Duplication
		if( ! in_array($use_default_where_conditions,$allowed_used_default_where_conditions_values)){
2987
			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s", "event_espresso"),$use_default_where_conditions,implode(", ",$allowed_used_default_where_conditions_values)));
2988
		}
2989
		$universal_query_params = array();
2990
		if( $use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only' ){
2991
			$universal_query_params = $this->_get_default_where_conditions();
2992
		} else if( $use_default_where_conditions === 'minimum' ) {
2993
			$universal_query_params = $this->_get_minimum_where_conditions();
2994
		}
2995
		if(in_array($use_default_where_conditions,array('all','other_models_only'))){
2996
			foreach($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name){
2997
				$related_model = $this->get_related_model_obj($model_name);
2998
				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
2999
				$overrides = $this->_override_defaults_or_make_null_friendly(
3000
					$related_model_universal_where_params,
3001
					$where_query_params,
3002
					$related_model,
3003
					$model_relation_path
3004
				);
3005
				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3006
					$universal_query_params,
3007
					$overrides
3008
				);
3009
			}
3010
		}
3011
		return $universal_query_params;
3012
	}
3013
3014
3015
3016
	/**
3017
	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3018
	 * then we also add a special where condition which allows for that model's primary key
3019
	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3020
	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3021
	 *
3022
	 * @param array    $default_where_conditions
3023
	 * @param array    $provided_where_conditions
3024
	 * @param EEM_Base $model
3025
	 * @param string   $model_relation_path like 'Transaction.Payment.'
3026
	 * @return array like EEM_Base::get_all's $query_params[0]
3027
	 * @throws \EE_Error
3028
	 */
3029
	private function _override_defaults_or_make_null_friendly($default_where_conditions,$provided_where_conditions,$model,$model_relation_path){
3030
		$null_friendly_where_conditions = array();
3031
		$none_overridden = true;
3032
		$or_condition_key_for_defaults = 'OR*'.get_class($model);
3033
3034
		foreach($default_where_conditions as $key => $val){
3035
			if( isset($provided_where_conditions[$key])){
3036
				$none_overridden = false;
3037
			}else{
3038
				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3039
			}
3040
		}
3041
		if( $none_overridden && $default_where_conditions){
0 ignored issues
show
Bug Best Practice introduced by
The expression $default_where_conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3042
			if($model->has_primary_key_field()){
3043
				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path.".".$model->primary_key_name()] = array('IS NULL');
3044
			}/*else{
3045
				//@todo NO PK, use other defaults
3046
			}*/
3047
		}
3048
		return $null_friendly_where_conditions;
3049
	}
3050
3051
	/**
3052
	 * Uses the _default_where_conditions_strategy set during __construct() to get
3053
	 * default where conditions on all get_all, update, and delete queries done by this model.
3054
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3055
	 * NOT array('Event_CPT.post_type'=>'esp_event').
3056
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3057
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3058
	 */
3059
	private function _get_default_where_conditions($model_relation_path = null){
3060
		if ( $this->_ignore_where_strategy ){
3061
			return array();
3062
		}
3063
		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3064
	}
3065
	/**
3066
	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3067
	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3068
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3069
	 * NOT array('Event_CPT.post_type'=>'esp_event').
3070
	 * Similar to _get_default_where_conditions
3071
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3072
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3073
	 */
3074
	protected function _get_minimum_where_conditions($model_relation_path = null){
3075
		if ( $this->_ignore_where_strategy ){
3076
			return array();
3077
		}
3078
		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3079
	}
3080
3081
3082
3083
	/**
3084
	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3085
	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3086
	 *
3087
	 * @param EE_Model_Query_Info_Carrier $model_query_info
3088
	 * @return string
3089
	 * @throws \EE_Error
3090
	 */
3091
	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info){
3092
		$selects = $this->_get_columns_to_select_for_this_model();
3093
		foreach($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included){
3094
			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3095
			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model( $model_relation_chain );
3096
			foreach ( $other_model_selects as $key => $value ) {
3097
				$selects[] = $value;
3098
			}
3099
		}
3100
		return implode(", ",$selects);
3101
	}
3102
3103
	/**
3104
	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3105
	 * So that's going to be the columns for all the fields on the model
3106
	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3107
	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3108
	 */
3109
	public function _get_columns_to_select_for_this_model($model_relation_chain = ''){
3110
		$fields = $this->field_settings();
3111
		$selects = array();
3112
		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain, $this->get_this_model_name());
3113
		foreach($fields as $field_obj){
3114
			$selects[] = $table_alias_with_model_relation_chain_prefix . $field_obj->get_table_alias().".".$field_obj->get_table_column()." AS '".$table_alias_with_model_relation_chain_prefix.$field_obj->get_table_alias().".".$field_obj->get_table_column()."'";
3115
		}
3116
		//make sure we are also getting the PKs of each table
3117
		$tables = $this->get_tables();
3118
		if(count($tables) > 1){
3119
			foreach($tables as $table_obj){
3120
				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix . $table_obj->get_fully_qualified_pk_column();
3121
				if( ! in_array($qualified_pk_column,$selects)){
3122
					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3123
				}
3124
			}
3125
		}
3126
		return $selects;
3127
	}
3128
3129
3130
3131
	/**
3132
	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3133
	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3134
	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the SQL
3135
	 * for joining, and the data types
3136
	 * @param null|string 	$original_query_param
3137
	 * @param string $query_param like Registration.Transaction.TXN_ID
3138
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3139
	 * @param 	string $query_param_type like Registration.Transaction.TXN_ID
3140
	 * or 'PAY_ID'. Otherwise, we don't expect there to be a column name. We only want model names, eg 'Event.Venue' or 'Registration's
3141
	 * @param string $original_query_param what it originally was (eg Registration.Transaction.TXN_ID). If null, we assume it matches $query_param
3142
	 * @throws EE_Error
3143
	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3144
	 */
3145
	private function _extract_related_model_info_from_query_param(
3146
		$query_param,
3147
		EE_Model_Query_Info_Carrier $passed_in_query_info,
3148
		$query_param_type,
3149
		$original_query_param = null
3150
	) {
3151
		if( $original_query_param === null ){
3152
			$original_query_param = $query_param;
3153
		}
3154
		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3155
		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3156
		$allow_logic_query_params = in_array($query_param_type,array('where','having'));
3157
		$allow_fields = in_array($query_param_type,array('where','having','order_by','group_by','order'));
3158
		//check to see if we have a field on this model
3159
		$this_model_fields = $this->field_settings(true);
3160
		if(array_key_exists($query_param,$this_model_fields)){
3161
			if($allow_fields){
3162
				return;
3163
			}else{
3164
				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s", "event_espresso"),
3165
						$query_param,get_class($this),$query_param_type,$original_query_param));
3166
			}
3167
		}
3168
		//check if this is a special logic query param
3169
		elseif(in_array($query_param, $this->_logic_query_param_keys, TRUE)){
3170
			if($allow_logic_query_params){
3171
				return;
3172
			}else{
3173
				throw new EE_Error(
3174
					sprintf(
3175
						__( 'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s', 'event_espresso' ),
3176
						implode( '", "', $this->_logic_query_param_keys ),
3177
						$query_param ,
3178
						get_class( $this ),
3179
						'<br />',
3180
						"\t" . ' $passed_in_query_info = <pre>' . print_r( $passed_in_query_info, TRUE ) . '</pre>' . "\n\t" . ' $query_param_type = ' . $query_param_type . "\n\t" . ' $original_query_param = ' . $original_query_param
3181
					)
3182
				);
3183
			}
3184
		}
3185
3186
		//check if it's a custom selection
3187
		elseif(array_key_exists($query_param,$this->_custom_selections)){
3188
			return;
3189
		}
3190
3191
		//check if has a model name at the beginning
3192
		//and
3193
		//check if it's a field on a related model
3194
		foreach($this->_model_relations as $valid_related_model_name=>$relation_obj){
3195
			if(strpos($query_param, $valid_related_model_name.".") === 0){
3196
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
3197
				$query_param = substr($query_param, strlen($valid_related_model_name."."));
3198
				if($query_param === ''){
3199
					//nothing left to $query_param
3200
					//we should actually end in a field name, not a model like this!
3201
					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ", "event_espresso"),
3202
					$query_param,$query_param_type,get_class($this),$valid_related_model_name));
3203
				}else{
3204
					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3205
					$related_model_obj->_extract_related_model_info_from_query_param($query_param, $passed_in_query_info, $query_param_type, $original_query_param);
3206
					return;
3207
				}
3208
			}elseif($query_param === $valid_related_model_name){
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param (string) and $valid_related_model_name (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
3209
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
3210
				return;
3211
			}
3212
		}
3213
3214
3215
		//ok so $query_param didn't start with a model name
3216
		//and we previously confirmed it wasn't a logic query param or field on the current model
3217
		//it's wack, that's what it is
3218
		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s", "event_espresso"),
3219
				$query_param,get_class($this),$query_param_type,$original_query_param));
3220
3221
	}
3222
3223
3224
3225
	/**
3226
	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3227
	 * and store it on $passed_in_query_info
3228
	 *
3229
	 * @param string                      $model_name
3230
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3231
	 * @param string                      $original_query_param used to extract the relation chain between the queried model and $model_name.
3232
	 *                                                          Eg, if we are querying Event, and are adding a join to 'Payment' with the original query param key 'Registration.Transaction.Payment.PAY_amount',
3233
	 *                                                          we want to extract 'Registration.Transaction.Payment', in case Payment wants to add default query params so that it will know
3234
	 *                                                          what models to prepend onto its default query params or in case it wants to rename tables (in case there are multiple joins to the same table)
3235
	 * @return void
3236
	 * @throws \EE_Error
3237
	 */
3238
	private function _add_join_to_model($model_name, EE_Model_Query_Info_Carrier $passed_in_query_info,$original_query_param){
3239
		$relation_obj = $this->related_settings_for($model_name);
3240
3241
		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3242
		//check if the relation is HABTM, because then we're essentially doing two joins
3243
		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3244
		if($relation_obj instanceof EE_HABTM_Relation){
3245
			$join_model_obj = $relation_obj->get_join_model();
3246
			//replace the model specified with the join model for this relation chain, whi
3247
			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name, $join_model_obj->get_this_model_name(), $model_relation_chain);
3248
			$new_query_info = new EE_Model_Query_Info_Carrier(
3249
					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3250
					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3251
			$passed_in_query_info->merge( $new_query_info  );
3252
		}
3253
		//now just join to the other table pointed to by the relation object, and add its data types
3254
		$new_query_info = new EE_Model_Query_Info_Carrier(
3255
				array($model_relation_chain=>$model_name),
3256
				$relation_obj->get_join_statement($model_relation_chain));
3257
		$passed_in_query_info->merge( $new_query_info  );
3258
	}
3259
3260
3261
3262
	/**
3263
	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3264
	 *
3265
	 * @param array $where_params like EEM_Base::get_all
3266
	 * @return string of SQL
3267
	 * @throws \EE_Error
3268
	 */
3269
	private function _construct_where_clause($where_params){
3270
		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3271
		if($SQL){
3272
			return " WHERE ". $SQL;
3273
		}else{
3274
			return '';
3275
		}
3276
	}
3277
3278
3279
3280
	/**
3281
	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3282
	 * and should be passed HAVING parameters, not WHERE parameters
3283
	 *
3284
	 * @param array $having_params
3285
	 * @return string
3286
	 * @throws \EE_Error
3287
	 */
3288
	private function _construct_having_clause($having_params){
3289
		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3290
		if($SQL){
3291
			return " HAVING ". $SQL;
3292
		}else{
3293
			return '';
3294
		}
3295
3296
	}
3297
3298
	/**
3299
	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3300
	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on EEM_Attendee.
3301
	 * @param string $field_name
3302
	 * @param string $model_name
3303
	 * @return EE_Model_Field_Base
3304
	 * @throws EE_Error
3305
	 */
3306
	protected function _get_field_on_model($field_name,$model_name){
3307
		$model_class = 'EEM_'.$model_name;
3308
		$model_filepath = $model_class.".model.php";
3309
		if ( is_readable($model_filepath)){
3310
			require_once($model_filepath);
3311
			$model_instance=call_user_func($model_name."::instance");
3312
			/* @var $model_instance EEM_Base */
3313
			return $model_instance->field_settings_for($field_name);
3314
		}else{
3315
			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s','event_espresso'),$model_name,$model_class,$model_filepath));
3316
		}
3317
	}
3318
3319
3320
3321
	/**
3322
	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND Event_Meta.meta_value = 'foo'))"
3323
	 * @param array  $where_params see EEM_Base::get_all for documentation
3324
	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3325
	 * @throws EE_Error
3326
	 * @return string of SQL
3327
	 */
3328
	private function _construct_condition_clause_recursive($where_params, $glue = ' AND'){
3329
		$where_clauses=array();
3330
		foreach($where_params as $query_param => $op_and_value_or_sub_condition){
3331
			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3332
			if(in_array($query_param,$this->_logic_query_param_keys)){
3333
				switch($query_param){
3334
					case 'not':
3335
					case 'NOT':
3336
						$where_clauses[] = "! (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, $glue).")";
3337
						break;
3338
					case 'and':
3339
					case 'AND':
3340
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' AND ') .")";
3341
						break;
3342
					case 'or':
3343
					case 'OR':
3344
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' OR ') .")";
3345
						break;
3346
				}
3347
			}else{
3348
				$field_obj = $this->_deduce_field_from_query_param($query_param);
3349
3350
				//if it's not a normal field, maybe it's a custom selection?
3351
				if( ! $field_obj){
3352
					if(isset( $this->_custom_selections[$query_param][1])){
3353
						$field_obj = $this->_custom_selections[$query_param][1];
3354
					}else{
3355
						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection", "event_espresso"),$query_param));
3356
					}
3357
				}
3358
				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3359
				$where_clauses[]=$this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
0 ignored issues
show
Documentation introduced by
$query_param is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3360
			}
3361
		}
3362
		return $where_clauses ? implode( $glue, $where_clauses ) : '';
3363
	}
3364
3365
3366
3367
	/**
3368
	 * Takes the input parameter and extract the table name (alias) and column name
3369
	 * @param array $query_param  like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3370
	 * @throws EE_Error
3371
	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3372
	 */
3373
	private function _deduce_column_name_from_query_param($query_param){
3374
		$field = $this->_deduce_field_from_query_param($query_param);
0 ignored issues
show
Documentation introduced by
$query_param is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3375
3376
		if( $field ){
3377
			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param( $field->get_model_name(), $query_param );
0 ignored issues
show
Documentation introduced by
$query_param is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3378
			return $table_alias_prefix . $field->get_qualified_column();
3379
		}elseif(array_key_exists($query_param,$this->_custom_selections)){
3380
			//maybe it's custom selection item?
3381
			//if so, just use it as the "column name"
3382
			return $query_param;
3383
		}else{
3384
			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)", "event_espresso"),$query_param,implode(",",$this->_custom_selections)));
3385
		}
3386
	}
3387
3388
	/**
3389
	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition query
3390
	 * param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get overwritten
3391
	 * Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3392
	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3393
	 * @param string $condition_query_param_key
3394
	 * @return string
3395
	 */
3396 View Code Duplication
	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3397
		$pos_of_star = strpos($condition_query_param_key, '*');
3398
		if($pos_of_star === FALSE){
3399
			return $condition_query_param_key;
3400
		}else{
3401
			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3402
			return $condition_query_param_sans_star;
3403
		}
3404
	}
3405
3406
3407
3408
	/**
3409
	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3410
	 * @param mixed array | string 	$op_and_value
3411
	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3412
	 * @throws EE_Error
3413
	 * @return string
3414
	 */
3415
	private function _construct_op_and_value($op_and_value, $field_obj){
3416
		if ( is_array( $op_and_value ) ) {
3417
			$operator = isset( $op_and_value[0] ) ? $this->_prepare_operator_for_sql( $op_and_value[0] ) : null;
3418
			if ( ! $operator ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $operator of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
3419
				$php_array_like_string = array();
3420
				foreach ( $op_and_value as $key => $value ) {
3421
					$php_array_like_string[] = "$key=>$value";
3422
				}
3423
				throw new EE_Error(
3424
					sprintf(
3425
						__(
3426
							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
3427
							"event_espresso"
3428
						),
3429
						implode( ",", $php_array_like_string )
3430
					)
3431
				);
3432
			}
3433
			$value = isset( $op_and_value[1] ) ? $op_and_value[1] : null;
3434
		} else {
3435
			$operator = '=';
3436
			$value = $op_and_value;
3437
		}
3438
		//check to see if the value is actually another field
3439
		if ( is_array( $op_and_value ) && isset( $op_and_value[2] ) && $op_and_value[2] == true ) {
3440
			return $operator . SP . $this->_deduce_column_name_from_query_param( $value );
3441
		} elseif ( in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) {
3442
			//in this case, the value should be an array, or at least a comma-separated list
3443
			//it will need to handle a little differently
3444
			$cleaned_value = $this->_construct_in_value( $value, $field_obj );
3445
			//note: $cleaned_value has already been run through $wpdb->prepare()
3446
			return $operator . SP . $cleaned_value;
3447
		} elseif ( in_array( $operator, $this->_between_style_operators ) && is_array( $value ) ) {
3448
			//the value should be an array with count of two.
3449
			if ( count( $value ) !== 2 ) {
3450
				throw new EE_Error(
3451
					sprintf(
3452
						__(
3453
							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3454
							'event_espresso'
3455
						),
3456
						"BETWEEN"
3457
					)
3458
				);
3459
			}
3460
			$cleaned_value = $this->_construct_between_value( $value, $field_obj );
3461
			return $operator . SP . $cleaned_value;
3462 View Code Duplication
		} elseif ( in_array( $operator, $this->_null_style_operators ) ) {
3463
			if ( $value !== null ) {
3464
				throw new EE_Error(
3465
					sprintf(
3466
						__(
3467
							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3468
							"event_espresso"
3469
						),
3470
						$value,
3471
						$operator
3472
					)
3473
				);
3474
			}
3475
			return $operator;
3476
		} elseif ( $operator === 'LIKE' && ! is_array( $value ) ) {
3477
			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3478
			//remove other junk. So just treat it as a string.
3479
			return $operator . SP . $this->_wpdb_prepare_using_field( $value, '%s' );
3480
		} elseif ( ! in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) {
3481
			return $operator . SP . $this->_wpdb_prepare_using_field( $value, $field_obj );
3482 View Code Duplication
		} elseif ( in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) {
3483
			throw new EE_Error(
3484
				sprintf(
3485
					__(
3486
						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3487
						'event_espresso'
3488
					),
3489
					$operator,
3490
					$operator
3491
				)
3492
			);
3493
		} elseif ( ! in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) {
3494
			throw new EE_Error(
3495
				sprintf(
3496
					__(
3497
						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3498
						'event_espresso'
3499
					),
3500
					$operator,
3501
					$operator
3502
				)
3503
			);
3504
		} else {
3505
			throw new EE_Error(
3506
				sprintf(
3507
					__(
3508
						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3509
						"event_espresso"
3510
					),
3511
					http_build_query( $op_and_value )
3512
				)
3513
			);
3514
		}
3515
	}
3516
3517
3518
3519
	/**
3520
	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
3521
	 *
3522
	 * @param array                      $values
3523
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg '%s'
3524
	 * @return string
3525
	 * @throws \EE_Error
3526
	 */
3527
	public function _construct_between_value( $values, $field_obj ) {
3528
		$cleaned_values = array();
3529
		foreach ( $values as $value ) {
3530
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3531
		}
3532
		return  $cleaned_values[0] . " AND " . $cleaned_values[1];
3533
	}
3534
3535
3536
3537
	/**
3538
	 * Takes an array or a comma-separated list of $values and cleans them
3539
	 * according to $data_type using $wpdb->prepare, and then makes the list a
3540
	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
3541
	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
3542
	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
3543
	 *
3544
	 * @param mixed                      $values    array or comma-separated string
3545
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
3546
	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
3547
	 * @throws \EE_Error
3548
	 */
3549
	public function _construct_in_value($values,  $field_obj){
3550
		//check if the value is a CSV list
3551
		if(is_string($values)){
3552
			//in which case, turn it into an array
3553
			$values = explode(",",$values);
3554
		}
3555
		$cleaned_values = array();
3556
		foreach($values as $value){
0 ignored issues
show
Bug introduced by
The expression $values of type object|integer|double|null|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3557
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3558
		}
3559
		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
3560
		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
3561
		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
3562
		if(empty($cleaned_values)){
3563
			$all_fields = $this->field_settings();
3564
			$a_field = array_shift($all_fields);
3565
			$main_table = $this->_get_main_table();
3566
			$cleaned_values[] = "SELECT ".$a_field->get_table_column()." FROM ".$main_table->get_table_name()." WHERE FALSE";
3567
		}
3568
		return "(".implode(",",$cleaned_values).")";
3569
	}
3570
3571
3572
3573
	/**
3574
	 *
3575
	 * @param mixed 	$value
3576
	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
3577
	 * @throws EE_Error
3578
	 * @return false|null|string
3579
	 */
3580
	private function _wpdb_prepare_using_field($value,$field_obj){
3581
		/** @type WPDB $wpdb */
3582
		global $wpdb;
3583
		if($field_obj instanceof EE_Model_Field_Base){
3584
			return $wpdb->prepare($field_obj->get_wpdb_data_type(),$this->_prepare_value_for_use_in_db($value, $field_obj));
3585
		}else{//$field_obj should really just be a data type
3586 View Code Duplication
			if( ! in_array($field_obj,$this->_valid_wpdb_data_types)){
3587
				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),$field_obj,implode(",",$this->_valid_wpdb_data_types)));
3588
			}
3589
			return $wpdb->prepare($field_obj,$value);
3590
		}
3591
	}
3592
3593
3594
3595
	/**
3596
	 * Takes the input parameter and finds the model field that it indicates.
3597
	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3598
	 * @throws EE_Error
3599
	 * @return EE_Model_Field_Base
3600
	 */
3601
	protected function _deduce_field_from_query_param($query_param_name){
3602
		//ok, now proceed with deducing which part is the model's name, and which is the field's name
3603
		//which will help us find the database table and column
3604
3605
		$query_param_parts = explode(".",$query_param_name);
3606
		if(empty($query_param_parts)){
3607
			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",'event_espresso'),$query_param_name));
3608
		}
3609
		$number_of_parts = count($query_param_parts);
3610
		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
3611
		if($number_of_parts === 1){
3612
			$field_name = $last_query_param_part;
3613
			$model_obj = $this;
3614
		}else{// $number_of_parts >= 2
3615
			//the last part is the column name, and there are only 2parts. therefore...
3616
			$field_name = $last_query_param_part;
3617
			$model_obj = $this->get_related_model_obj( $query_param_parts[ $number_of_parts - 2 ]);
3618
		}
3619
		try{
3620
			return $model_obj->field_settings_for($field_name);
3621
		}catch(EE_Error $e){
3622
			return null;
3623
		}
3624
	}
3625
3626
3627
3628
	/**
3629
	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's alias and column
3630
	 * which corresponds to it
3631
	 * @param string $field_name
3632
	 * @throws EE_Error
3633
	 * @return string
3634
	 */
3635
	public function _get_qualified_column_for_field($field_name){
3636
		$all_fields = $this->field_settings();
3637
		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : FALSE;
3638
		if($field){
3639
			return $field->get_qualified_column();
3640
		}else{
3641
			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",'event_espresso'),$field_name,get_class($this)));
3642
		}
3643
	}
3644
3645
3646
3647
	/**
3648
	 * constructs the select use on special limit joins
3649
	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although its setup so the select query will be setup on and just doing the special select join off of the primary table (as that is typically where the limits would be set).
3650
	 *
3651
	 * @param  string $table_alias The table the select is being built for
3652
	 * @param  mixed|string $limit The limit for this select
3653
	 * @return string                The final select join element for the query.
3654
	 */
3655
	public function _construct_limit_join_select( $table_alias, $limit ) {
3656
		$SQL = '';
3657
		foreach ( $this->_tables as $table_obj ) {
3658
			if ( $table_obj instanceof EE_Primary_Table ) {
3659
				$SQL .= $table_alias === $table_obj->get_table_alias()
3660
					? $table_obj->get_select_join_limit( $limit )
3661
					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
3662
			} elseif ( $table_obj instanceof EE_Secondary_Table ) {
3663
				$SQL .= $table_alias === $table_obj->get_table_alias()
3664
					? $table_obj->get_select_join_limit_join( $limit )
3665
					: SP . $table_obj->get_join_sql( $table_alias ) . SP;
3666
			}
3667
		}
3668
		return $SQL;
3669
	}
3670
3671
3672
3673
	/**
3674
	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
3675
	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
3676
	 *
3677
	 * @return string SQL
3678
	 * @throws \EE_Error
3679
	 */
3680
	public function _construct_internal_join(){
3681
		$SQL = $this->_get_main_table()->get_table_sql();
3682
		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
3683
		return $SQL;
3684
	}
3685
3686
3687
3688
	/**
3689
	 * Constructs the SQL for joining all the tables on this model.
3690
	 * Normally $alias should be the primary table's alias, but in cases where
3691
	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the primary table)
3692
	 * then we should provide that secondary table's alias.
3693
	 * Eg, with $alias being the primary table's alias, this will construct SQL like:
3694
	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
3695
	 * With $alias being a secondary table's alias, this will construct SQL like:
3696
	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
3697
	 *
3698
	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
3699
	 * @return string
3700
	 */
3701
	public function _construct_internal_join_to_table_with_alias($alias_prefixed){
3702
		$SQL = '';
3703
		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
3704
		foreach($this->_tables as $table_obj){
3705
			if($table_obj instanceof EE_Secondary_Table){//table is secondary table
3706
				if($alias_sans_prefix === $table_obj->get_table_alias()){
3707
					//so we're joining to this table, meaning the table is already in
3708
					//the FROM statement, BUT the primary table isn't. So we want
3709
					//to add the inverse join sql
3710
					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
3711
				}else{
3712
					//just add a regular JOIN to this table from the primary table
3713
					$SQL .= $table_obj->get_join_sql($alias_prefixed);
3714
				}
3715
			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
3716
		}
3717
		return $SQL;
3718
	}
3719
3720
	/**
3721
	 * Gets an array for storing all the data types on the next-to-be-executed-query.
3722
	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being their data type (eg, '%s', '%d', etc)
3723
	 * @return array
3724
	 */
3725
	public function _get_data_types(){
3726
		$data_types = array();
3727
		foreach( $this->field_settings() as $field_obj){
3728
			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
3729
			/** @var $field_obj EE_Model_Field_Base */
3730
			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
3731
		}
3732
		return $data_types;
3733
	}
3734
3735
3736
3737
	/**
3738
	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
3739
	 * @param string $model_name
3740
	 * @throws EE_Error
3741
	 * @return EEM_Base
3742
	 */
3743
	public function get_related_model_obj($model_name){
3744
		$model_classname = "EEM_".$model_name;
3745
		if(!class_exists($model_classname)){
3746
			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",'event_espresso'),$model_name,$model_classname));
3747
		}
3748
		return call_user_func($model_classname."::instance");
3749
	}
3750
3751
3752
	/**
3753
	 * Returns the array of EE_ModelRelations for this model.
3754
	 * @return EE_Model_Relation_Base[]
3755
	 */
3756
	public function relation_settings(){
3757
		return $this->_model_relations;
3758
	}
3759
3760
	/**
3761
	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
3762
	 * because without THOSE models, this model probably doesn't have much purpose.
3763
	 * (Eg, without an event, datetimes have little purpose.)
3764
	 * @return EE_Belongs_To_Relation[]
3765
	 */
3766
	public function belongs_to_relations(){
3767
		$belongs_to_relations = array();
3768
		foreach($this->relation_settings() as $model_name => $relation_obj){
3769
			if($relation_obj instanceof EE_Belongs_To_Relation){
3770
				$belongs_to_relations[$model_name] = $relation_obj;
3771
			}
3772
		}
3773
		return $belongs_to_relations;
3774
	}
3775
3776
3777
3778
	/**
3779
	 * Returns the specified EE_Model_Relation, or throws an exception
3780
	 * @param string $relation_name name of relation, key in $this->_relatedModels
3781
	 * @throws EE_Error
3782
	 * @return EE_Model_Relation_Base
3783
	 */
3784
	public function related_settings_for($relation_name){
3785
		$relatedModels=$this->relation_settings();
3786 View Code Duplication
		if(!array_key_exists($relation_name,$relatedModels)){
3787
			throw new EE_Error(
3788
				sprintf(
3789
					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...','event_espresso'),
3790
					$relation_name,
3791
					$this->_get_class_name(),
3792
					implode( ', ', array_keys( $relatedModels ))
3793
				)
3794
			);
3795
		}
3796
		return $relatedModels[$relation_name];
3797
	}
3798
3799
3800
3801
	/**
3802
	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all fields
3803
	 * @param string $fieldName
3804
	 * @throws EE_Error
3805
	 * @return EE_Model_Field_Base
3806
	 */
3807 View Code Duplication
	public function field_settings_for($fieldName){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3808
		$fieldSettings=$this->field_settings(true);
3809
		if( ! array_key_exists($fieldName,$fieldSettings)){
3810
			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'",'event_espresso'),$fieldName,get_class($this)));
3811
		}
3812
		return $fieldSettings[$fieldName];
3813
	}
3814
3815
	/**
3816
	 * Checks if this field exists on this model
3817
	 * @param string $fieldName a key in the model's _field_settings array
3818
	 * @return boolean
3819
	 */
3820
	public function has_field($fieldName){
3821
		$fieldSettings = $this->field_settings(true);
3822
		if( isset($fieldSettings[$fieldName])){
3823
			return true;
3824
		}else{
3825
			return false;
3826
		}
3827
	}
3828
3829
	/**
3830
	 * Returns whether or not this model has a relation to the specified model
3831
	 * @param string $relation_name possibly one of the keys in the relation_settings array
3832
	 * @return boolean
3833
	 */
3834
	public function has_relation($relation_name){
3835
		$relations = $this->relation_settings();
3836
		if(isset($relations[$relation_name])){
3837
			return true;
3838
		}else{
3839
			return false;
3840
		}
3841
	}
3842
3843
3844
	/**
3845
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3846
	 * Eg, on EE_Answer that would be ANS_ID field object
3847
	 * @param $field_obj
3848
	 * @return EE_Model_Field_Base
3849
	 */
3850
	public function is_primary_key_field( $field_obj ){
3851
		return $field_obj instanceof EE_Primary_Key_Field_Base ? TRUE : FALSE;
3852
	}
3853
3854
3855
3856
	/**
3857
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3858
	 * Eg, on EE_Answer that would be ANS_ID field object
3859
	 * @return EE_Model_Field_Base
3860
	 * @throws EE_Error
3861
	 */
3862
	public function get_primary_key_field(){
3863
		if( $this->_primary_key_field === NULL ){
3864
			foreach( $this->field_settings( TRUE ) as $field_obj ){
3865
				if( $this->is_primary_key_field( $field_obj )){
3866
					$this->_primary_key_field = $field_obj;
3867
					break;
3868
				}
3869
			}
3870
			if( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base ){
3871
				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s",'event_espresso'),get_class($this)));
3872
			}
3873
		}
3874
		return $this->_primary_key_field;
3875
	}
3876
3877
3878
3879
	/**
3880
	 * Returns whether or not not there is a primary key on this model.
3881
	 * Internally does some caching.
3882
	 * @return boolean
3883
	 */
3884
	public function has_primary_key_field(){
3885
		if($this->_has_primary_key_field === null){
3886
			try{
3887
				$this->get_primary_key_field();
3888
				$this->_has_primary_key_field = true;
3889
			}catch(EE_Error $e){
3890
				$this->_has_primary_key_field = false;
3891
			}
3892
		}
3893
		return $this->_has_primary_key_field;
3894
	}
3895
3896
3897
3898
	/**
3899
	 * Finds the first field of type $field_class_name.
3900
	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field, EE_Foreign_Key_Field, etc
3901
	 * @return EE_Model_Field_Base or null if none is found
3902
	 */
3903
	public function get_a_field_of_type($field_class_name){
3904
		foreach($this->field_settings() as $field){
3905
			if( $field instanceof $field_class_name ){
3906
				return $field;
3907
			}
3908
		}
3909
		return null;
3910
	}
3911
3912
3913
	/**
3914
	 * Gets a foreign key field pointing to model.
3915
	 * @param string $model_name eg Event, Registration, not EEM_Event
3916
	 * @return EE_Foreign_Key_Field_Base
3917
	 * @throws EE_Error
3918
	 */
3919
	public function get_foreign_key_to($model_name){
3920
		if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
3921
			foreach($this->field_settings() as $field){
3922
				if(
3923
					$field instanceof EE_Foreign_Key_Field_Base
3924
					&& in_array($model_name,$field->get_model_names_pointed_to() )
3925
				) {
3926
					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
3927
					break;
3928
				}
3929
			}
3930 View Code Duplication
			if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
3931
				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",'event_espresso'),$model_name,get_class($this)));
3932
			}
3933
		}
3934
		return $this->_cache_foreign_key_to_fields[ $model_name ];
3935
	}
3936
3937
3938
3939
	/**
3940
	 * Gets the actual table for the table alias
3941
	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
3942
	 * a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'. Either one works
3943
	 * @return EE_Table_Base
3944
	 */
3945
	public function get_table_for_alias($table_alias){
3946
		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
3947
		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
3948
	}
3949
3950
3951
3952
	/**
3953
	 * Returns a flat array of all field son this model, instead of organizing them
3954
	 * by table_alias as they are in the constructor.
3955
	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
3956
	 * @return EE_Model_Field_Base[] where the keys are the field's name
3957
	 */
3958
	public function field_settings($include_db_only_fields = false){
3959
		if( $include_db_only_fields ){
3960 View Code Duplication
			if( $this->_cached_fields === NULL ){
3961
				$this->_cached_fields = array();
3962
				foreach($this->_fields as $fields_corresponding_to_table){
3963
					foreach($fields_corresponding_to_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_corresponding_to_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3964
						$this->_cached_fields[$field_name]=$field_obj;
3965
					}
3966
				}
3967
			}
3968
			return $this->_cached_fields;
3969 View Code Duplication
		}else{
3970
			if( $this->_cached_fields_non_db_only === NULL ){
3971
				$this->_cached_fields_non_db_only = array();
3972
				foreach($this->_fields as $fields_corresponding_to_table){
3973
					foreach($fields_corresponding_to_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_corresponding_to_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3974
						/** @var $field_obj EE_Model_Field_Base */
3975
						if( ! $field_obj->is_db_only_field() ){
3976
							$this->_cached_fields_non_db_only[$field_name]=$field_obj;
3977
						}
3978
					}
3979
				}
3980
			}
3981
			return $this->_cached_fields_non_db_only;
3982
		}
3983
	}
3984
3985
3986
3987
	/**
3988
	 *        cycle though array of attendees and create objects out of each item
3989
	 *
3990
	 * @access        private
3991
	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
3992
	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not, numerically indexed)
3993
	 * @throws \EE_Error
3994
	 */
3995
	protected function _create_objects( $rows = array() ) {
3996
		$array_of_objects=array();
3997
		if(empty($rows)){
3998
			return array();
3999
		}
4000
		$count_if_model_has_no_primary_key = 0;
4001
		$has_primary_key = $this->has_primary_key_field();
4002
		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4003
		foreach ( (array)$rows as $row ) {
4004
			if(empty($row)){
4005
				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4006
				return array();
4007
			}
4008
			//check if we've already set this object in the results array,
4009
			//in which case there's no need to process it further (again)
4010
			if( $has_primary_key ) {
4011
				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4012
					$row,
4013
					$primary_key_field->get_qualified_column(),
4014
					$primary_key_field->get_table_column()
4015
				);
4016
				if( $table_pk_value && isset( $array_of_objects[ $table_pk_value ] ) ) {
4017
					continue;
4018
				}
4019
			}
4020
			$classInstance = $this->instantiate_class_from_array_or_object($row);
4021 View Code Duplication
			if( ! $classInstance ) {
4022
				throw new EE_Error(
4023
					sprintf(
4024
						__( 'Could not create instance of class %s from row %s', 'event_espresso' ),
4025
						$this->get_this_model_name(),
4026
						http_build_query( $row )
4027
					)
4028
				);
4029
			}
4030
			//set the timezone on the instantiated objects
4031
			$classInstance->set_timezone( $this->_timezone );
4032
			//make sure if there is any timezone setting present that we set the timezone for the object
4033
			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4034
			$array_of_objects[ $key ] = $classInstance;
4035
			//also, for all the relations of type BelongsTo, see if we can cache
4036
			//those related models
4037
			//(we could do this for other relations too, but if there are conditions
4038
			//that filtered out some fo the results, then we'd be caching an incomplete set
4039
			//so it requires a little more thought than just caching them immediately...)
4040
			foreach($this->_model_relations as $modelName => $relation_obj){
4041
				if( $relation_obj instanceof EE_Belongs_To_Relation){
4042
					//check if this model's INFO is present. If so, cache it on the model
4043
					$other_model = $relation_obj->get_other_model();
4044
					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4045
					//if we managed to make a model object from the results, cache it on the main model object
4046
					if( $other_model_obj_maybe ){
4047
						//set timezone on these other model objects if they are present
4048
						$other_model_obj_maybe->set_timezone( $this->_timezone );
4049
						$classInstance->cache($modelName, $other_model_obj_maybe);
4050
					}
4051
				}
4052
			}
4053
		}
4054
		return $array_of_objects;
4055
	}
4056
4057
4058
4059
	/**
4060
	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default values.
4061
	 * A typical example of where this is used is when creating a new item and the initial load of a form.  We dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the object (as set in the model_field!).
4062
	 *
4063
	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4064
	 */
4065
	public function create_default_object() {
4066
4067
		$this_model_fields_and_values = array();
4068
		//setup the row using default values;
4069
		foreach ( $this->field_settings() as $field_name => $field_obj ) {
4070
			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4071
		}
4072
4073
		$className = $this->_get_class_name();
4074
		$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_and_values ), FALSE, FALSE );
4075
4076
		return $classInstance;
4077
	}
4078
4079
4080
4081
	/**
4082
	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4083
	 *                             or an stdClass where each property is the name of a column,
4084
	 * @return EE_Base_Class
4085
	 * @throws \EE_Error
4086
	 */
4087
	public function instantiate_class_from_array_or_object($cols_n_values){
4088
		if( ! is_array( $cols_n_values ) && is_object( $cols_n_values )) {
4089
			$cols_n_values = get_object_vars( $cols_n_values );
4090
		}
4091
		$primary_key = NULL;
4092
		//make sure the array only has keys that are fields/columns on this model
4093
		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values( $cols_n_values );
4094
		if( $this->has_primary_key_field() && isset( $this_model_fields_n_values[ $this->primary_key_name() ] ) ){
4095
			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
4096
		}
4097
		$className=$this->_get_class_name();
4098
4099
		//check we actually found results that we can use to build our model object
4100
		//if not, return null
4101
		if( $this->has_primary_key_field()){
4102
			if(empty( $this_model_fields_n_values[$this->primary_key_name()] )){
4103
				return NULL;
4104
			}
4105
		}else if($this->unique_indexes()){
4106
			$first_column = reset($this_model_fields_n_values);
4107
			if(empty($first_column)){
4108
				return NULL;
4109
			}
4110
		}
4111
4112
		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4113
		if ( $primary_key){
4114
			$classInstance = $this->get_from_entity_map( $primary_key );
4115
			if( ! $classInstance) {
4116
				$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
4117
				// add this new object to the entity map
4118
				$classInstance = $this->add_to_entity_map( $classInstance );
0 ignored issues
show
Bug introduced by
It seems like $classInstance can be null; however, add_to_entity_map() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
4119
			}
4120
		}else{
4121
			$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
4122
		}
4123
4124
			//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4125
		$this->set_timezone( $classInstance->get_timezone() );
4126
		return $classInstance;
4127
	}
4128
	/**
4129
	 * Gets the model object from the  entity map if it exists
4130
	 * @param int|string $id the ID of the model object
4131
	 * @return EE_Base_Class
4132
	 */
4133
	public function get_from_entity_map( $id ){
4134
		return isset( $this->_entity_map[ $id ] ) ? $this->_entity_map[ $id ] : NULL;
4135
	}
4136
4137
4138
4139
	/**
4140
	 * add_to_entity_map
4141
	 *
4142
	 * Adds the object to the model's entity mappings
4143
	 * 		Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4144
	 * 		and for the remainder of the request, it's even more up-to-date than what's in the database.
4145
	 * 		So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4146
	 * 		If the database gets updated directly and you want the entity mapper to reflect that change,
4147
	 * 		then this method should be called immediately after the update query
4148
	 *
4149
	 * @param 	EE_Base_Class $object
4150
	 * @throws EE_Error
4151
	 * @return \EE_Base_Class
4152
	 */
4153
	public function add_to_entity_map( EE_Base_Class $object) {
4154
		$className = $this->_get_class_name();
4155
		if( ! $object instanceof $className ){
4156
			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),is_object( $object ) ? get_class( $object ) : $object, $className ) );
4157
		}
4158
		/** @var $object EE_Base_Class */
4159
		if ( ! $object->ID() ){
4160
			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.", "event_espresso"),get_class($this)));
4161
		}
4162
		// double check it's not already there
4163
		$classInstance = $this->get_from_entity_map( $object->ID() );
4164
		if ( $classInstance ) {
4165
			return $classInstance;
4166
		} else {
4167
			$this->_entity_map[ $object->ID() ] = $object;
4168
			return $object;
4169
		}
4170
	}
4171
4172
	/**
4173
	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4174
	 *
4175
	 * Given an array where keys are column (or column alias) names and values,
4176
	 * returns an array of their corresponding field names and database values
4177
	 * @param array $cols_n_values
4178
	 * @return array
4179
	 */
4180
	public function deduce_fields_n_values_from_cols_n_values( $cols_n_values ) {
4181
		return $this->_deduce_fields_n_values_from_cols_n_values( $cols_n_values );
0 ignored issues
show
Documentation introduced by
$cols_n_values is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4182
	}
4183
4184
4185
	/**
4186
	 * _deduce_fields_n_values_from_cols_n_values
4187
	 *
4188
	 * Given an array where keys are column (or column alias) names and values,
4189
	 * returns an array of their corresponding field names and database values
4190
	 *
4191
	 * @param string $cols_n_values
4192
	 * @return array
4193
	 */
4194
	protected function _deduce_fields_n_values_from_cols_n_values( $cols_n_values ){
4195
		$this_model_fields_n_values = array();
4196
		foreach( $this->get_tables() as $table_alias => $table_obj ) {
4197
			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values, $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column() );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $table_pk_value is correct as $this->_get_column_value...e_obj->get_pk_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
4198
			//there is a primary key on this table and its not set. Use defaults for all its columns
4199
			if( $table_pk_value === null && $table_obj->get_pk_column() ){
4200
				foreach( $this->_get_fields_for_table( $table_alias ) as $field_name => $field_obj ) {
0 ignored issues
show
Bug introduced by
The expression $this->_get_fields_for_table($table_alias) of type object<EE_Model_Field_Base> is not traversable.
Loading history...
4201
					if( ! $field_obj->is_db_only_field() ){
4202
						//prepare field as if its coming from db
4203
						$prepared_value = $field_obj->prepare_for_set( $field_obj->get_default_value() );
4204
						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db( $prepared_value );
4205
					}
4206
				}
4207
			}else{
4208
				//the table's rows existed. Use their values
4209
				foreach( $this->_get_fields_for_table( $table_alias ) as $field_name => $field_obj ) {
0 ignored issues
show
Bug introduced by
The expression $this->_get_fields_for_table($table_alias) of type object<EE_Model_Field_Base> is not traversable.
Loading history...
4210
					if( ! $field_obj->is_db_only_field() ){
4211
						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this_model_fields_n_values[$field_name] is correct as $this->_get_column_value...bj->get_table_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
4212
							$cols_n_values, $field_obj->get_qualified_column(),
4213
							$field_obj->get_table_column()
4214
						);
4215
					}
4216
				}
4217
			}
4218
		}
4219
		return $this_model_fields_n_values;
4220
	}
4221
4222
4223
4224
	/**
4225
	 * @param $cols_n_values
4226
	 * @param $qualified_column
4227
	 * @param $regular_column
4228
	 * @return null
4229
	 */
4230
	protected function _get_column_value_with_table_alias_or_not( $cols_n_values, $qualified_column, $regular_column ){
4231
		$value = null;
4232
		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4233
		//does the field on the model relate to this column retrieved from the db?
4234
		//or is it a db-only field? (not relating to the model)
4235
		if( isset( $cols_n_values[ $qualified_column ] ) ){
4236
			$value = $cols_n_values[ $qualified_column ];
4237
		}elseif( isset( $cols_n_values[ $regular_column ] ) ){
4238
			$value = $cols_n_values[ $regular_column ];
4239
		}
4240
		return $value;
4241
	}
4242
4243
4244
4245
	/**
4246
	 * refresh_entity_map_from_db
4247
	 * Makes sure the model object in the entity map at $id assumes the values
4248
	 * of the database (opposite of EE_base_Class::save())
4249
	 *
4250
	 * @param int|string $id
4251
	 * @return EE_Base_Class
4252
	 * @throws \EE_Error
4253
	 */
4254
	public function refresh_entity_map_from_db( $id ){
4255
		$obj_in_map = $this->get_from_entity_map( $id );
4256
		if( $obj_in_map ){
4257
			$wpdb_results = $this->_get_all_wpdb_results(
4258
				array( array( $this->get_primary_key_field()->get_name() => $id ), 'limit' => 1 )
4259
			);
4260
			if( $wpdb_results && is_array( $wpdb_results ) ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $wpdb_results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4261
				$one_row = reset( $wpdb_results );
4262
				foreach( $this->_deduce_fields_n_values_from_cols_n_values($one_row ) as $field_name => $db_value ) {
4263
					$obj_in_map->set_from_db( $field_name, $db_value );
4264
				}
4265
				//clear the cache of related model objects
4266
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
4267
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
4268
				}
4269
			}
4270
			return $obj_in_map;
4271
		}else{
4272
			return $this->get_one_by_ID( $id );
4273
		}
4274
	}
4275
4276
4277
4278
	/**
4279
	 * refresh_entity_map_with
4280
	 * Leaves the entry in the entity map alone, but updates it to match the provided
4281
	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4282
	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4283
	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4284
	 *
4285
	 * @param int|string    $id
4286
	 * @param EE_Base_Class $replacing_model_obj
4287
	 * @return \EE_Base_Class
4288
	 * @throws \EE_Error
4289
	 */
4290
	public function refresh_entity_map_with( $id, $replacing_model_obj ) {
4291
		$obj_in_map = $this->get_from_entity_map( $id );
4292
		if( $obj_in_map ){
4293
			if( $replacing_model_obj instanceof EE_Base_Class ){
4294
				foreach( $replacing_model_obj->model_field_array() as $field_name => $value ) {
4295
					$obj_in_map->set( $field_name, $value );
4296
				}
4297
				//make the model object in the entity map's cache match the $replacing_model_obj
4298
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
4299
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
4300
					foreach( $replacing_model_obj->get_all_from_cache( $relation_name ) as $cache_id => $cached_obj ) {
4301
						$obj_in_map->cache( $relation_name, $cached_obj, $cache_id );
4302
					}
4303
				}
4304
			}
4305
			return $obj_in_map;
4306
		}else{
4307
			$this->add_to_entity_map( $replacing_model_obj );
4308
			return $replacing_model_obj;
4309
		}
4310
	}
4311
4312
4313
4314
	/**
4315
	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4316
	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4317
	 * require_once($this->_getClassName().".class.php");
4318
	 * @return string
4319
	 */
4320
	private function _get_class_name(){
4321
		return "EE_".$this->get_this_model_name();
4322
	}
4323
4324
4325
4326
	/**
4327
	 * Get the name of the items this model represents, for the quantity specified. Eg,
4328
	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4329
	 * it would be 'Events'.
4330
	 * @param int $quantity
4331
	 * @return string
4332
	 */
4333
	public function item_name($quantity = 1){
4334
		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4335
	}
4336
4337
4338
4339
	/**
4340
	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4341
	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called (http://www.garfieldtech.com/blog/php-magic-call)
4342
	 * and passed the method's name and arguments.
4343
	 * Instead of requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that happen?)
4344
	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function)
4345
	 * and accepts 2 arguments: the object on which the function was called, and an array of the original arguments passed to the function. Whatever their callback function returns will be returned by this function.
4346
	 * Example: in functions.php (or in a plugin):
4347
	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
4348
	 * function my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4349
	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4350
	 *        return $previousReturnValue.$returnString;
4351
	 * }
4352
	 * require('EEM_Answer.model.php');
4353
	 * $answer=EEM_Answer::instance();
4354
	 * echo $answer->my_callback('monkeys',100);
4355
	 * //will output "you called my_callback! and passed args:monkeys,100"
4356
	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4357
	 * @param array  $args       array of original arguments passed to the function
4358
	 * @throws EE_Error
4359
	 * @return mixed whatever the plugin which calls add_filter decides
4360
	 */
4361 View Code Duplication
	public function __call($methodName,$args){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4362
		$className=get_class($this);
4363
		$tagName="FHEE__{$className}__{$methodName}";
4364
		if(!has_filter($tagName)){
4365
			throw new EE_Error(
4366
				sprintf(
4367
					__( 'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );', 'event_espresso' ),
4368
					$methodName,
4369
					$className,
4370
					$tagName,
4371
					'<br />'
4372
				)
4373
			);
4374
		}
4375
4376
		return apply_filters($tagName,null,$this,$args);
4377
	}
4378
4379
4380
4381
	/**
4382
	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4383
	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4384
	 *
4385
	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4386
	 *                                                       the EE_Base_Class object that corresponds to this Model,
4387
	 *                                                       the object's class name
4388
	 *                                                       or object's ID
4389
	 * @param boolean $ensure_is_in_db                       if set, we will also verify this model object
4390
	 *                                                       exists in the database. If it does not, we add it
4391
	 * @throws EE_Error
4392
	 * @return EE_Base_Class
4393
	 */
4394
	public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ){
4395
		$className = $this->_get_class_name();
4396
		if ( $base_class_obj_or_id instanceof $className ) {
4397
			$model_object = $base_class_obj_or_id;
4398
		} else {
4399
			$primary_key_field = $this->get_primary_key_field();
4400
			if (
4401
				$primary_key_field instanceof EE_Primary_Key_Int_Field
4402
				&& (
4403
					is_int( $base_class_obj_or_id )
4404
					|| is_string( $base_class_obj_or_id )
4405
				)
4406
			) {
4407
				// assume it's an ID.
4408
				// either a proper integer or a string representing an integer (eg "101" instead of 101)
4409
				$model_object = $this->get_one_by_ID( $base_class_obj_or_id );
4410
			} else if (
4411
				$primary_key_field instanceof EE_Primary_Key_String_Field
4412
			    && is_string( $base_class_obj_or_id )
4413
			) {
4414
				// assume its a string representation of the object
4415
				$model_object = $this->get_one_by_ID( $base_class_obj_or_id );
4416
			} else {
4417
				throw new EE_Error(
4418
					sprintf(
4419
						__(
4420
							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
4421
							'event_espresso'
4422
						),
4423
						$base_class_obj_or_id,
4424
						$this->_get_class_name(),
4425
						print_r( $base_class_obj_or_id, true )
4426
					)
4427
				);
4428
			}
4429
		}
4430
		if ( $ensure_is_in_db && $model_object->ID() !== null ) {
4431
			$model_object->save();
4432
		}
4433
		return $model_object;
4434
	}
4435
4436
4437
4438
	/**
4439
	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
4440
	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
4441
	 * returns it ID.
4442
	 * @param EE_Base_Class|int|string $base_class_obj_or_id
4443
	 * @return int|string depending on the type of this model object's ID
4444
	 * @throws EE_Error
4445
	 */
4446
	public function ensure_is_ID($base_class_obj_or_id){
4447
		$className = $this->_get_class_name();
4448
		if( $base_class_obj_or_id instanceof $className ){
4449
			/** @var $base_class_obj_or_id EE_Base_Class */
4450
			$id = $base_class_obj_or_id->ID();
4451
		}elseif(is_int($base_class_obj_or_id)){
4452
			//assume it's an ID
4453
			$id = $base_class_obj_or_id;
4454
		}elseif(is_string($base_class_obj_or_id)){
4455
			//assume its a string representation of the object
4456
			$id = $base_class_obj_or_id;
4457
		}else{
4458
			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",'event_espresso'),$base_class_obj_or_id,$this->_get_class_name(),print_r($base_class_obj_or_id,true)));
4459
		}
4460
		return $id;
4461
	}
4462
4463
4464
4465
	/**
4466
	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
4467
	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
4468
	 * been sanitized and converted into the appropriate domain.
4469
	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by the model
4470
	 * object/model field) is when making a method call from WITHIN a model object, which has direct access to its sanitized
4471
	 * values.
4472
	 * Note: after changing this setting, you should set it back to its previous value (using get_assumption_concerning_values_already_prepared_by_model_object())
4473
	 * eg.
4474
	 * $EVT = EEM_Event::instance(); $old_setting = $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
4475
	 * $EVT->assume_values_already_prepared_by_model_object(true);
4476
	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
4477
	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
4478
	 * @param int $values_already_prepared like one of the constants on EEM_Base
4479
	 * @return void
4480
	 */
4481
	public function assume_values_already_prepared_by_model_object($values_already_prepared = self::not_prepared_by_model_object){
4482
		$this->_values_already_prepared_by_model_object = $values_already_prepared;
0 ignored issues
show
Documentation Bug introduced by
The property $_values_already_prepared_by_model_object was declared of type boolean, but $values_already_prepared is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
4483
	}
4484
	/**
4485
	 * Read comments for assume_values_already_prepared_by_model_object()
4486
	 * @return int
4487
	 */
4488
	public function get_assumption_concerning_values_already_prepared_by_model_object(){
4489
		return $this->_values_already_prepared_by_model_object;
4490
	}
4491
4492
	/**
4493
	 * Gets all the indexes on this model
4494
	 * @return EE_Index[]
4495
	 */
4496
	public function indexes(){
4497
		return $this->_indexes;
4498
	}
4499
	/**
4500
	 * Gets all the Unique Indexes on this model
4501
	 * @return EE_Unique_Index[]
4502
	 */
4503
	public function unique_indexes(){
4504
		$unique_indexes = array();
4505
		foreach($this->_indexes as $name => $index){
4506
			if($index instanceof EE_Unique_Index){
4507
				$unique_indexes [$name] = $index;
4508
			}
4509
		}
4510
		return $unique_indexes;
4511
	}
4512
4513
4514
4515
	/**
4516
	 * Gets all the fields which, when combined, make the primary key.
4517
	 * This is usually just an array with 1 element (the primary key), but in cases
4518
	 * where there is no primary key, it's a combination of fields as defined
4519
	 * on a primary index
4520
	 *
4521
	 * @return EE_Model_Field_Base[] indexed by the field's name
4522
	 * @throws \EE_Error
4523
	 */
4524
	public function get_combined_primary_key_fields(){
4525
		foreach($this->indexes() as $index){
4526
			if($index instanceof EE_Primary_Key_Index){
4527
				return $index->fields();
4528
			}
4529
		}
4530
		return array( $this->primary_key_name() => $this->get_primary_key_field());
4531
	}
4532
	
4533
4534
4535
4536
	/**
4537
	 * Used to build a primary key string (when the model has no primary key),
4538
	 * which can be used a unique string to identify this model object.
4539
	 *
4540
	 * @param array $cols_n_values keys are field names, values are their values
4541
	 * @return string
4542
	 * @throws \EE_Error
4543
	 */
4544
	public function get_index_primary_key_string($cols_n_values){
4545
		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values, $this->get_combined_primary_key_fields());
4546
		return http_build_query($cols_n_values_for_primary_key_index);
4547
	}
4548
4549
4550
4551
	/**
4552
	 * Gets the field values from the primary key string
4553
	 *
4554
	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
4555
	 * @param string $index_primary_key_string
4556
	 * @return null|array
4557
	 * @throws \EE_Error
4558
	 */
4559
	public function parse_index_primary_key_string( $index_primary_key_string) {
4560
		$key_fields = $this->get_combined_primary_key_fields();
4561
		//check all of them are in the $id
4562
		$key_vals_in_combined_pk = array();
4563
		parse_str( $index_primary_key_string, $key_vals_in_combined_pk );
4564
		foreach( $key_fields as $key_field_name => $field_obj ) {
4565
			if( ! isset( $key_vals_in_combined_pk[ $key_field_name ] ) ){
4566
				return NULL;
4567
			}
4568
		}
4569
		return $key_vals_in_combined_pk;
4570
	}
4571
4572
4573
4574
	/**
4575
	 * verifies that an array of key-value pairs for model fields has a key
4576
	 * for each field comprising the primary key index
4577
	 *
4578
	 * @param array $key_vals
4579
	 * @return boolean
4580
	 * @throws \EE_Error
4581
	 */
4582
	public function has_all_combined_primary_key_fields( $key_vals ) {
4583
		$keys_it_should_have = array_keys( $this->get_combined_primary_key_fields() );
4584
		foreach( $keys_it_should_have as $key ){
4585
			if( ! isset( $key_vals[ $key ] ) ){
4586
				return false;
4587
			}
4588
		}
4589
		return true;
4590
	}
4591
4592
4593
	/**
4594
	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
4595
	 * We consider something to be a copy if all the attributes match (except the ID, of course).
4596
	 * @param array|EE_Base_Class $model_object_or_attributes_array 	If its an array, it's field-value pairs
4597
	 * @param array                $query_params like EEM_Base::get_all's query_params.
4598
	 * @throws EE_Error
4599
	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed)
4600
	 */
4601
	public function get_all_copies($model_object_or_attributes_array, $query_params = array()){
4602
4603 View Code Duplication
		if($model_object_or_attributes_array instanceof EE_Base_Class){
4604
			$attributes_array = $model_object_or_attributes_array->model_field_array();
4605
		}elseif(is_array($model_object_or_attributes_array)){
4606
			$attributes_array = $model_object_or_attributes_array;
4607
		}else{
4608
			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s", "event_espresso"),$model_object_or_attributes_array));
4609
		}
4610
		//even copies obviously won't have the same ID, so remove the primary key
4611
		//from the WHERE conditions for finding copies (if there is a primary key, of course)
4612
		if($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])){
4613
			unset($attributes_array[$this->primary_key_name()]);
4614
		}
4615
		if(isset($query_params[0])){
4616
			$query_params[0] = array_merge($attributes_array,$query_params);
4617
		}else{
4618
			$query_params[0] = $attributes_array;
4619
		}
4620
		return $this->get_all($query_params);
4621
	}
4622
4623
4624
4625
	/**
4626
	 * Gets the first copy we find. See get_all_copies for more details
4627
	 *
4628
	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
4629
	 * @param array $query_params
4630
	 * @return EE_Base_Class
4631
	 * @throws \EE_Error
4632
	 */
4633 View Code Duplication
	public function get_one_copy($model_object_or_attributes_array,$query_params = array()){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4634
		if( ! is_array( $query_params ) ){
4635
			EE_Error::doing_it_wrong('EEM_Base::get_one_copy', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
4636
			$query_params = array();
4637
		}
4638
		$query_params['limit'] = 1;
4639
		$copies = $this->get_all_copies($model_object_or_attributes_array,$query_params);
4640
		if(is_array($copies)){
4641
			return array_shift($copies);
4642
		}else{
4643
			return null;
4644
		}
4645
	}
4646
4647
4648
4649
	/**
4650
	 * Updates the item with the specified id. Ignores default query parameters because
4651
	 * we have specified the ID, and its assumed we KNOW what we're doing
4652
	 *
4653
	 * @param array      $fields_n_values keys are field names, values are their new values
4654
	 * @param int|string $id              the value of the primary key to update
4655
	 * @return int number of rows updated
4656
	 * @throws \EE_Error
4657
	 */
4658
	public function update_by_ID($fields_n_values,$id){
4659
		$query_params = array(0=>array($this->get_primary_key_field()->get_name() => $id),
4660
			'default_where_conditions'=>'other_models_only',);
4661
		return $this->update($fields_n_values,$query_params);
4662
	}
4663
4664
4665
4666
	/**
4667
	 * Changes an operator which was supplied to the models into one usable in SQL
4668
	 * @param string $operator_supplied
4669
	 * @return string an operator which can be used in SQL
4670
	 * @throws EE_Error
4671
	 */
4672
	private function _prepare_operator_for_sql($operator_supplied){
4673
		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied] : null;
4674 View Code Duplication
		if($sql_operator){
4675
			return $sql_operator;
4676
		}else{
4677
			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s", "event_espresso"),$operator_supplied,implode(",",array_keys($this->_valid_operators))));
4678
		}
4679
	}
4680
4681
4682
4683
	/**
4684
	 * Gets an array where keys are the primary keys and values are their 'names'
4685
	 * (as determined by the model object's name() function, which is often overridden)
4686
	 *
4687
	 * @param array $query_params like get_all's
4688
	 * @return string[]
4689
	 * @throws \EE_Error
4690
	 */
4691
	public function get_all_names($query_params = array()){
4692
		$objs = $this->get_all($query_params);
4693
		$names = array();
4694
		foreach($objs as $obj){
4695
			$names[$obj->ID()] = $obj->name();
4696
		}
4697
		return $names;
4698
	}
4699
4700
4701
4702
	/**
4703
	 * Gets an array of primary keys from the model objects. If you acquired the model objects
4704
	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
4705
	 * this is duplicated effort and reduces efficiency) you would be better to use
4706
	 * array_keys() on $model_objects.
4707
	 *
4708
	 * @param \EE_Base_Class[] $model_objects
4709
	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it in the returned array
4710
	 * @return array
4711
	 * @throws \EE_Error
4712
	 */
4713
	public function get_IDs( $model_objects, $filter_out_empty_ids = false) {
4714
		if( ! $this->has_primary_key_field() ) {
4715
			if( WP_DEBUG ) {
4716
				EE_Error::add_error(
4717
					__( 'Trying to get IDs from a model than has no primary key', 'event_espresso' ),
4718
					__FILE__,
4719
					__FUNCTION__,
4720
					__LINE__
4721
				);
4722
			}
4723
		}
4724
		$IDs = array();
4725
		foreach( $model_objects as $model_object ) {
4726
			$id = $model_object->ID();
4727
			if( ! $id ) {
4728
				if( $filter_out_empty_ids ) {
4729
					continue;
4730
				}
4731
				if ( WP_DEBUG ) {
4732
					EE_Error::add_error(
4733
						__(
4734
							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
4735
							'event_espresso'
4736
						),
4737
						__FILE__,
4738
						__FUNCTION__,
4739
						__LINE__
4740
					);
4741
				}
4742
			}
4743
			$IDs[] = $id;
4744
		}
4745
		return $IDs;
4746
	}
4747
4748
	/**
4749
	 * Returns the string used in capabilities relating to this model. If there
4750
	 * are no capabilities that relate to this model returns false
4751
	 * @return string|false
4752
	 */
4753
	public function cap_slug(){
4754
		return apply_filters( 'FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
4755
	}
4756
4757
4758
4759
	/**
4760
	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
4761
	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
4762
	 * only returns the cap restrictions array in that context (ie, the array
4763
	 * at that key)
4764
	 *
4765
	 * @param string $context
4766
	 * @return EE_Default_Where_Conditions[] indexed by associated capability
4767
	 * @throws \EE_Error
4768
	 */
4769
	public function cap_restrictions( $context = EEM_Base::caps_read ) {
4770
		EEM_Base::verify_is_valid_cap_context( $context );
4771
		//check if we ought to run the restriction generator first
4772
		if(
4773
			isset( $this->_cap_restriction_generators[ $context ] )
4774
			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
4775
			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
4776
		) {
4777
			$this->_cap_restrictions[ $context ] = array_merge(
4778
				$this->_cap_restrictions[ $context ],
4779
				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
4780
			);
4781
		}
4782
		//and make sure we've finalized the construction of each restriction
4783
		foreach( $this->_cap_restrictions[ $context ] as $where_conditions_obj ) {
4784
			if ( $where_conditions_obj instanceof EE_Default_Where_Conditions ) {
4785
				$where_conditions_obj->_finalize_construct( $this );
4786
			}
4787
		}
4788
4789
		return $this->_cap_restrictions[ $context ];
4790
	}
4791
4792
	/**
4793
	 * Indicating whether or not this model thinks its a wp core model
4794
	 * @return boolean
4795
	 */
4796
	public function is_wp_core_model(){
4797
		return $this->_wp_core_model;
4798
	}
4799
4800
4801
4802
	/**
4803
	 * Gets all the caps that are missing which impose a restriction on
4804
	 * queries made in this context
4805
	 *
4806
	 * @param string $context one of EEM_Base::caps_ constants
4807
	 * @return EE_Default_Where_Conditions[] indexed by capability name
4808
	 * @throws \EE_Error
4809
	 */
4810
	public function caps_missing( $context = EEM_Base::caps_read ) {
4811
		$missing_caps = array();
4812
		$cap_restrictions = $this->cap_restrictions( $context );
4813
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
4814
			if( ! EE_Capabilities::instance()->current_user_can( $cap, $this->get_this_model_name() . '_model_applying_caps') ) {
4815
				$missing_caps[ $cap ] = $restriction_if_no_cap;
4816
			}
4817
		}
4818
		return $missing_caps;
4819
	}
4820
4821
	/**
4822
	 * Gets the mapping from capability contexts to action strings used in capability names
4823
	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
4824
	 * one of 'read', 'edit', or 'delete'
4825
	 */
4826
	public function cap_contexts_to_cap_action_map() {
4827
		return apply_filters( 'FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map, $this );
4828
	}
4829
4830
4831
4832
	/**
4833
	 * Gets the action string for the specified capability context
4834
	 * @param string $context
4835
	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
4836
	 * @throws \EE_Error
4837
	 */
4838
	public function cap_action_for_context( $context ) {
4839
		$mapping = $this->cap_contexts_to_cap_action_map();
4840
		if( isset( $mapping[ $context ] ) ) {
4841
			return $mapping[ $context ];
4842
		}
4843
		if( $action = apply_filters( 'FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context ) ) {
4844
			return $action;
4845
		}
4846
		throw new EE_Error(
4847
			sprintf(
4848
				__( 'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso' ),
4849
				$context,
4850
				implode(',', array_keys( $this->cap_contexts_to_cap_action_map() ) )
4851
			)
4852
		);
4853
4854
	}
4855
4856
	/**
4857
	 * Returns all the capability contexts which are valid when querying models
4858
	 * @return array
4859
	 */
4860
	static public function valid_cap_contexts() {
4861
		return apply_filters( 'FHEE__EEM_Base__valid_cap_contexts', array(
4862
			self::caps_read,
4863
			self::caps_read_admin,
4864
			self::caps_edit,
4865
			self::caps_delete
4866
		));
4867
	}
4868
4869
4870
4871
	/**
4872
	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
4873
	 * @param string $context
4874
	 * @return bool
4875
	 * @throws \EE_Error
4876
	 */
4877
	static public function verify_is_valid_cap_context( $context ) {
4878
		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
4879 View Code Duplication
		if( in_array( $context, $valid_cap_contexts ) ) {
4880
			return true;
4881
		}else{
4882
			throw new EE_Error(
4883
				sprintf(
4884
					__( 'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s', 'event_espresso' ),
4885
					$context,
4886
					'EEM_Base' ,
4887
					implode(',', $valid_cap_contexts )
4888
				)
4889
			);
4890
		}
4891
	}
4892
4893
	/**
4894
	 * Clears all the models field caches. This is only useful when a sub-class
4895
	 * might have added a field or something and these caches might be invalidated
4896
	 */
4897
	protected function _invalidate_field_caches() {
4898
		$this->_cache_foreign_key_to_fields = array();
4899
		$this->_cached_fields = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_cached_fields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4900
		$this->_cached_fields_non_db_only = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_cached_fields_non_db_only.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4901
	}
4902
4903
4904
4905
4906
}
4907