Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like EEM_Base often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use EEM_Base, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
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 | /** |
||
211 | * This holds the id of the blog currently making the query. Has no bearing on single site but is used for multisite. |
||
212 | * @var int |
||
213 | */ |
||
214 | protected static $_model_query_blog_id; |
||
215 | |||
216 | /** |
||
217 | * A copy of _fields, except the array keys are the model names pointed to by |
||
218 | * the field |
||
219 | * @var EE_Model_Field_Base[] |
||
220 | */ |
||
221 | private $_cache_foreign_key_to_fields = array(); |
||
222 | |||
223 | /** |
||
224 | * Cached list of all the fields on the model, indexed by their name |
||
225 | * @var EE_Model_Field_Base[] |
||
226 | */ |
||
227 | private $_cached_fields = NULL; |
||
228 | |||
229 | /** |
||
230 | * Cached list of all the fields on the model, except those that are |
||
231 | * marked as only pertinent to the database |
||
232 | * @var EE_Model_Field_Base[] |
||
233 | */ |
||
234 | private $_cached_fields_non_db_only = NULL; |
||
235 | |||
236 | /** |
||
237 | * A cached reference to the primary key for quick lookup |
||
238 | * @var EE_Model_Field_Base |
||
239 | */ |
||
240 | private $_primary_key_field = NULL; |
||
241 | |||
242 | /** |
||
243 | * Flag indicating whether this model has a primary key or not |
||
244 | * @var boolean |
||
245 | */ |
||
246 | protected $_has_primary_key_field=null; |
||
247 | |||
248 | /** |
||
249 | * Whether or not this model is based off a table in WP core only (CPTs should set |
||
250 | * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true). |
||
251 | * @var boolean |
||
252 | */ |
||
253 | protected $_wp_core_model = false; |
||
254 | |||
255 | /** |
||
256 | * List of valid operators that can be used for querying. |
||
257 | * The keys are all operators we'll accept, the values are the real SQL |
||
258 | * operators used |
||
259 | * @var array |
||
260 | */ |
||
261 | protected $_valid_operators = array( |
||
262 | '='=>'=', |
||
263 | '<='=>'<=', |
||
264 | '<'=>'<', |
||
265 | '>='=>'>=', |
||
266 | '>'=>'>', |
||
267 | '!='=>'!=', |
||
268 | 'LIKE'=>'LIKE', |
||
269 | 'like'=>'LIKE', |
||
270 | 'NOT_LIKE'=>'NOT LIKE', |
||
271 | 'not_like'=>'NOT LIKE', |
||
272 | 'NOT LIKE'=>'NOT LIKE', |
||
273 | 'not like'=>'NOT LIKE', |
||
274 | 'IN'=>'IN', |
||
275 | 'in'=>'IN', |
||
276 | 'NOT_IN'=>'NOT IN', |
||
277 | 'not_in'=>'NOT IN', |
||
278 | 'NOT IN'=>'NOT IN', |
||
279 | 'not in'=>'NOT IN', |
||
280 | 'between' => 'BETWEEN', |
||
281 | 'BETWEEN' => 'BETWEEN', |
||
282 | 'IS_NOT_NULL' => 'IS NOT NULL', |
||
283 | 'is_not_null' =>'IS NOT NULL', |
||
284 | 'IS NOT NULL' => 'IS NOT NULL', |
||
285 | 'is not null' => 'IS NOT NULL', |
||
286 | 'IS_NULL' => 'IS NULL', |
||
287 | 'is_null' => 'IS NULL', |
||
288 | 'IS NULL' => 'IS NULL', |
||
289 | 'is null' => 'IS NULL', |
||
290 | 'REGEXP' => 'REGEXP', |
||
291 | 'regexp' => 'REGEXP', |
||
292 | 'NOT_REGEXP' => 'NOT REGEXP', |
||
293 | 'not_regexp' => 'NOT REGEXP', |
||
294 | 'NOT REGEXP' => 'NOT REGEXP', |
||
295 | 'not regexp' => 'NOT REGEXP', |
||
296 | ); |
||
297 | |||
298 | /** |
||
299 | * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)' |
||
300 | * @var array |
||
301 | */ |
||
302 | protected $_in_style_operators = array('IN', 'NOT IN'); |
||
303 | |||
304 | /** |
||
305 | * operators that work like 'BETWEEN'. Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND '12-31-2012'" |
||
306 | * @var array |
||
307 | */ |
||
308 | protected $_between_style_operators = array( 'BETWEEN' ); |
||
309 | |||
310 | /** |
||
311 | * operators that are used for handling NUll and !NULL queries. Typically used for when checking if a row exists on a join table. |
||
312 | * @var array |
||
313 | */ |
||
314 | protected $_null_style_operators = array( 'IS NOT NULL', 'IS NULL'); |
||
315 | |||
316 | /** |
||
317 | * Allowed values for $query_params['order'] for ordering in queries |
||
318 | * @var array |
||
319 | */ |
||
320 | protected $_allowed_order_values = array('asc','desc','ASC','DESC'); |
||
321 | |||
322 | /** |
||
323 | * When these are keys in a WHERE or HAVING clause, they are handled much differently |
||
324 | * than regular field names. It is assumed that their values are an array of WHERE conditions |
||
325 | * @var array |
||
326 | */ |
||
327 | private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR'); |
||
328 | |||
329 | /** |
||
330 | * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a |
||
331 | * 'where', but 'where' clauses are so common that we thought we'd omit it |
||
332 | * @var array |
||
333 | */ |
||
334 | private $_allowed_query_params = array(0, 'limit','order_by','group_by','having','force_join','order','on_join_limit','default_where_conditions', 'caps'); |
||
335 | |||
336 | /** |
||
337 | * All the data types that can be used in $wpdb->prepare statements. |
||
338 | * @var array |
||
339 | */ |
||
340 | private $_valid_wpdb_data_types = array('%d','%s','%f'); |
||
341 | |||
342 | /** |
||
343 | * EE_Registry Object |
||
344 | * @var object |
||
345 | * @access protected |
||
346 | */ |
||
347 | protected $EE = NULL; |
||
348 | |||
349 | |||
350 | /** |
||
351 | * Property which, when set, will have this model echo out the next X queries to the page for debugging. |
||
352 | * @var int |
||
353 | */ |
||
354 | protected $_show_next_x_db_queries = 0; |
||
355 | |||
356 | /** |
||
357 | * When using _get_all_wpdb_results, you can specify a custom selection. If you do so, |
||
358 | * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc. |
||
359 | * @var array |
||
360 | */ |
||
361 | protected $_custom_selections = array(); |
||
362 | |||
363 | /** |
||
364 | * key => value Entity Map using array( EEM_Base::$_model_query_blog_id => array( ID => model object ) ) |
||
365 | * caches every model object we've fetched from the DB on this request |
||
366 | * @var array |
||
367 | */ |
||
368 | protected $_entity_map; |
||
369 | |||
370 | /** |
||
371 | * constant used to show EEM_Base has not yet verified the db on this http request |
||
372 | */ |
||
373 | const db_verified_none = 0; |
||
374 | /** |
||
375 | * constant used to show EEM_Base has verified the EE core db on this http request, |
||
376 | * but not the addons' dbs |
||
377 | */ |
||
378 | const db_verified_core = 1; |
||
379 | /** |
||
380 | * constant used to show EEM_Base has verified the addons' dbs (and implicitly |
||
381 | * the EE core db too) |
||
382 | */ |
||
383 | const db_verified_addons = 2; |
||
384 | |||
385 | /** |
||
386 | * indicates whether an EEM_Base child has already re-verified the DB |
||
387 | * is ok (we don't want to do it repetitively). Should be set to one the constants |
||
388 | * looking like EEM_Base::db_verified_* |
||
389 | * @var int - 0 = none, 1 = core, 2 = addons |
||
390 | */ |
||
391 | protected static $_db_verification_level = EEM_Base::db_verified_none; |
||
392 | |||
393 | |||
394 | |||
395 | |||
396 | /** |
||
397 | * About all child constructors: |
||
398 | * they should define the _tables, _fields and _model_relations arrays. |
||
399 | * Should ALWAYS be called after child constructor. |
||
400 | * In order to make the child constructors to be as simple as possible, this parent constructor |
||
401 | * finalizes constructing all the object's attributes. |
||
402 | * Generally, rather than requiring a child to code |
||
403 | * $this->_tables = array( |
||
404 | * 'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts') |
||
405 | * ...); |
||
406 | * (thus repeating itself in the array key and in the constructor of the new EE_Table,) |
||
407 | * each EE_Table has a function to set the table's alias after the constructor, using |
||
408 | * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations |
||
409 | * do something similar. |
||
410 | * |
||
411 | * @param null $timezone |
||
412 | * @throws \EE_Error |
||
413 | */ |
||
414 | protected function __construct( $timezone = NULL ){ |
||
546 | |||
547 | /** |
||
548 | * Generates the cap restrictions for the given context, or if they were |
||
549 | * already generated just gets what's cached |
||
550 | * @param string $context one of EEM_Base::valid_cap_contexts() |
||
551 | * @return EE_Default_Where_Conditions[] |
||
552 | */ |
||
553 | protected function _generate_cap_restrictions( $context ){ |
||
561 | |||
562 | |||
563 | /** |
||
564 | * Used to set the $_model_query_blog_id static property. |
||
565 | * |
||
566 | * @param int $blog_id If provided then will set the blog_id for the models to this id. If not provided then the |
||
567 | * value for get_current_blog_id() will be used. |
||
568 | */ |
||
569 | public static function set_model_query_blog_id( $blog_id = 0 ) { |
||
572 | |||
573 | |||
574 | |||
575 | |||
576 | /** |
||
577 | * Returns whatever is set as the internal $model_query_blog_id. |
||
578 | * |
||
579 | * @return int |
||
580 | */ |
||
581 | public static function get_model_query_blog_id() { |
||
584 | |||
585 | |||
586 | |||
587 | /** |
||
588 | * This function is a singleton method used to instantiate the Espresso_model object |
||
589 | * |
||
590 | * @access public |
||
591 | * @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) |
||
592 | * @return static (as in the concrete child class) |
||
593 | */ |
||
594 | View Code Duplication | public static function instance( $timezone = NULL ){ |
|
|
|||
595 | |||
596 | // check if instance of Espresso_model already exists |
||
597 | if ( ! static::$_instance instanceof static) { |
||
598 | // instantiate Espresso_model |
||
599 | static::$_instance = new static( $timezone ); |
||
600 | } |
||
601 | |||
602 | //we might have a timezone set, let set_timezone decide what to do with it |
||
603 | static::$_instance->set_timezone( $timezone ); |
||
604 | |||
605 | // Espresso_model object |
||
606 | return static::$_instance; |
||
607 | } |
||
608 | |||
609 | |||
610 | |||
611 | /** |
||
612 | * resets the model and returns it |
||
613 | * @param null | string $timezone |
||
614 | * @return static |
||
615 | */ |
||
616 | public static function reset( $timezone = NULL ){ |
||
617 | if ( ! is_null( static::$_instance ) ) { |
||
618 | static::$_instance = null; |
||
619 | |||
620 | return self::instance( $timezone ); |
||
621 | } |
||
622 | return null; |
||
623 | } |
||
624 | |||
625 | |||
626 | |||
627 | /** |
||
628 | * retrieve the status details from esp_status table as an array IF this model has the status table as a relation. |
||
629 | * |
||
630 | * @param boolean $translated return localized strings or JUST the array. |
||
631 | * @return array |
||
632 | * @throws \EE_Error |
||
633 | */ |
||
634 | public function status_array( $translated = FALSE ) { |
||
635 | if ( ! array_key_exists( 'Status', $this->_model_relations ) ) { |
||
636 | return array(); |
||
637 | } |
||
638 | $model_name = $this->get_this_model_name(); |
||
639 | $status_type = str_replace( ' ', '_', strtolower( str_replace( '_', ' ', $model_name ) ) ); |
||
640 | $stati = EEM_Status::instance()->get_all( array( array( 'STS_type' => $status_type ) ) ); |
||
641 | $status_array = array(); |
||
642 | foreach ( $stati as $status ) { |
||
643 | $status_array[ $status->ID() ] = $status->get( 'STS_code' ); |
||
644 | } |
||
645 | return $translated |
||
646 | ? EEM_Status::instance()->localized_status( $status_array, false, 'sentence' ) |
||
647 | : $status_array; |
||
648 | } |
||
649 | |||
650 | |||
651 | |||
652 | /** |
||
653 | * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB. |
||
654 | * |
||
655 | * @param array $query_params { |
||
656 | * @var array $0 (where) array { |
||
657 | * eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine if user is bob') |
||
658 | * becomes |
||
659 | * SQL >> "...WHERE QST_display_text = 'Are you bob?' AND QST_admin_text = 'Determine if user is bob'...") |
||
660 | * To add WHERE conditions based on related models (and even models-related-to-related-models) prepend the model's name |
||
661 | * onto the field name. Eg, EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); |
||
662 | * becomes |
||
663 | * SQL >> "SELECT * FROM wp_posts AS Event_CPT |
||
664 | * LEFT JOIN wp_esp_event_meta AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID |
||
665 | * LEFT JOIN wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID |
||
666 | * LEFT JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID |
||
667 | * LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID |
||
668 | * WHERE Venue_CPT.ID = 12 |
||
669 | * Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables). |
||
670 | * Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have |
||
671 | * "Registration.Attendee.ATT_ID" as a field on a query for events (because events are related to Registrations, which are related to Attendees). |
||
672 | * You can take it even further with "Registration.Transaction.Payment.PAY_amount" etc. |
||
673 | * To change the operator (from the default of '='), change the value to an numerically-indexed array, where the |
||
674 | * first item in the list is the operator. |
||
675 | * eg: array( 'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34), 'QST_wp_user' => array('in',array(1,2,7,23))) |
||
676 | * becomes |
||
677 | * SQL >> "...WHERE QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN (1,2,7,23)...". |
||
678 | * Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT LIKE, IN (followed by numeric-indexed array), |
||
679 | * NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL |
||
680 | * Values can be a string, int, or float. They can also be arrays IFF the operator is IN. |
||
681 | * Also, values can actually be field names. To indicate the value is a field, |
||
682 | * simply provide a third array item (true) to the operator-value array like so: |
||
683 | * eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) |
||
684 | * becomes |
||
685 | * SQL >> "...WHERE DTT_reg_limit > DTT_sold" |
||
686 | * Note: you can also use related model field names like you would any other field name. |
||
687 | * eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) |
||
688 | * could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) |
||
689 | * Also, by default all the where conditions are AND'd together. |
||
690 | * To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together |
||
691 | * eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' => 345678912)) |
||
692 | * becomes |
||
693 | * SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". |
||
694 | * Also, to negate an entire set of conditions, use 'NOT' as an array key. |
||
695 | * eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23) |
||
696 | * becomes |
||
697 | * SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) |
||
698 | * Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default, |
||
699 | * 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" |
||
700 | * to join conditions, it will continue to "stick" until you specify an AND. |
||
701 | * eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') |
||
702 | * becomes |
||
703 | * SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'" |
||
704 | * They can be nested indefinitely. |
||
705 | * eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) |
||
706 | * becomes |
||
707 | * SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." |
||
708 | * GOTCHA: |
||
709 | * 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. |
||
710 | * eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), |
||
711 | * as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. |
||
712 | * becomes |
||
713 | * SQL >> "PAY_timestamp != 4234232", ignoring the first two PAY_timestamp conditions). |
||
714 | * To overcome this, you can add a '*' character to the end of the field's name, followed by anything. |
||
715 | * These will be removed when generating the SQL string, but allow for the array keys to be unique. |
||
716 | * eg: you could rewrite the previous query as: |
||
717 | * array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) |
||
718 | * which correctly becomes |
||
719 | * SQL >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" |
||
720 | * This can be applied to condition operators too, |
||
721 | * eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson'))); |
||
722 | * @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 |
||
723 | * SQL "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively. |
||
724 | * Remember when you provide two numbers for the limit, the 1st number is the OFFSET, the 2nd is the LIMIT |
||
725 | * @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. |
||
726 | * Send an array in the following format array('on_join_limit' => array( 'table_alias', array(1,2) ) ). |
||
727 | * @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'), |
||
728 | * which would becomes SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. |
||
729 | * Like the 'where' conditions, these fields can be on related models. |
||
730 | * Eg 'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related to 'Registration' (like Event, Attendee, Price, Datetime, etc.) |
||
731 | * @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 |
||
732 | * 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. |
||
733 | * 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) |
||
734 | * or EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC" |
||
735 | * |
||
736 | * @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') |
||
737 | * 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 |
||
738 | * 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 |
||
739 | * |
||
740 | * @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) |
||
741 | * |
||
742 | * @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 |
||
743 | * array('Attendee','Payment','Datetime'). You may join with transient models using period, eg "Registration.Transaction.Payment". |
||
744 | * You will probably only want to do this in hopes of increasing efficiency, as related models which belongs to the current model |
||
745 | * (ie, the current model has a foreign key to them, like how Registration belongs to Attendee) can be cached in order |
||
746 | * to avoid future queries |
||
747 | * @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 |
||
748 | * if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS model's default where conditions |
||
749 | * set it to 'other_models_only'. If you only want this model's default where conditions added to the query, use 'this_model_only'. |
||
750 | * If you want to use all default where conditions (default), set to 'all'. |
||
751 | * @var string $caps controls what capability requirements to apply to the query; ie, should we just NOT |
||
752 | * apply any capabilities/permissions/restrictions and return everything? Or should we only show the |
||
753 | * current user items they should be able to view on the frontend, backend, edit, or delete? |
||
754 | * can be set to 'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete' |
||
755 | * } |
||
756 | * @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) |
||
757 | * Some full examples: |
||
758 | * get 10 transactions which have Scottish attendees: |
||
759 | * EEM_Transaction::instance()->get_all( array( |
||
760 | * array( |
||
761 | * 'OR'=>array( |
||
762 | * 'Registration.Attendee.ATT_fname'=>array('like','Mc%'), |
||
763 | * 'Registration.Attendee.ATT_fname*other'=>array('like','Mac%') |
||
764 | * ) |
||
765 | * ), |
||
766 | * 'limit'=>10, |
||
767 | * 'group_by'=>'TXN_ID' |
||
768 | * )); |
||
769 | * get all the answers to the question titled "shirt size" for event with id 12, ordered by their answer |
||
770 | * EEM_Answer::instance()->get_all(array( |
||
771 | * array( |
||
772 | * 'Question.QST_display_text'=>'shirt size', |
||
773 | * 'Registration.Event.EVT_ID'=>12 |
||
774 | * ), |
||
775 | * 'order_by'=>array('ANS_value'=>'ASC') |
||
776 | * )); |
||
777 | * @throws \EE_Error |
||
778 | */ |
||
779 | public function get_all($query_params = array()){ |
||
780 | if( isset( $query_params[ 'limit' ] ) |
||
781 | && ! isset( $query_params[ 'group_by' ] ) ) { |
||
782 | $query_params[ 'group_by' ] = array_keys( $this->get_combined_primary_key_fields() ); |
||
783 | } |
||
784 | return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, NULL)); |
||
785 | } |
||
786 | |||
787 | /** |
||
788 | * Modifies the query parameters so we only get back model objects |
||
789 | * that "belong" to the current user |
||
790 | * @param array $query_params @see EEM_Base::get_all() |
||
791 | * @return array like EEM_Base::get_all |
||
792 | */ |
||
793 | public function alter_query_params_to_only_include_mine( $query_params = array() ) { |
||
794 | $wp_user_field_name = $this->wp_user_field_name(); |
||
795 | if( $wp_user_field_name ){ |
||
796 | $query_params[0][ $wp_user_field_name ] = get_current_user_id(); |
||
797 | } |
||
798 | return $query_params; |
||
799 | } |
||
800 | |||
801 | /** |
||
802 | * Returns the name of the field's name that points to the WP_User table |
||
803 | * on this model (or follows the _model_chain_to_wp_user and uses that model's |
||
804 | * foreign key to the WP_User table) |
||
805 | * @return string|boolean string on success, boolean false when there is no |
||
806 | * foreign key to the WP_User table |
||
807 | */ |
||
808 | public function wp_user_field_name() { |
||
809 | try{ |
||
810 | if( ! empty( $this->_model_chain_to_wp_user ) ) { |
||
811 | $models_to_follow_to_wp_users = explode( '.', $this->_model_chain_to_wp_user ); |
||
812 | $last_model_name = end( $models_to_follow_to_wp_users ); |
||
813 | $model_with_fk_to_wp_users = EE_Registry::instance()->load_model( $last_model_name ); |
||
814 | $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.'; |
||
815 | }else{ |
||
816 | $model_with_fk_to_wp_users = $this; |
||
817 | $model_chain_to_wp_user = ''; |
||
818 | } |
||
819 | $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to( 'WP_User' ); |
||
820 | return $model_chain_to_wp_user . $wp_user_field->get_name(); |
||
821 | }catch( EE_Error $e ) { |
||
822 | return false; |
||
823 | } |
||
824 | } |
||
825 | |||
826 | /** |
||
827 | * Returns the _model_chain_to_wp_user string, which indicates which related model |
||
828 | * (or transiently-related model) has a foreign key to the wp_users table; |
||
829 | * useful for finding if model objects of this type are 'owned' by the current user. |
||
830 | * This is an empty string when the foreign key is on this model and when it isn't, |
||
831 | * but is only non-empty when this model's ownership is indicated by a RELATED model |
||
832 | * (or transiently-related model) |
||
833 | * @return string |
||
834 | */ |
||
835 | public function model_chain_to_wp_user(){ |
||
836 | return $this->_model_chain_to_wp_user; |
||
837 | } |
||
838 | |||
839 | /** |
||
840 | * Whether this model is 'owned' by a specific wordpress user (even indirectly, |
||
841 | * like how registrations don't have a foreign key to wp_users, but the |
||
842 | * events they are for are), or is unrelated to wp users. |
||
843 | * generally available |
||
844 | * @return boolean |
||
845 | */ |
||
846 | public function is_owned() { |
||
847 | if( $this->model_chain_to_wp_user() ){ |
||
848 | return true; |
||
849 | }else{ |
||
850 | try{ |
||
851 | $this->get_foreign_key_to( 'WP_User' ); |
||
852 | return true; |
||
853 | }catch( EE_Error $e ){ |
||
854 | return false; |
||
855 | } |
||
856 | } |
||
857 | } |
||
858 | |||
859 | |||
860 | |||
861 | /** |
||
862 | * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but may want to |
||
863 | * preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on the model) |
||
864 | * |
||
865 | * @param array $query_params like EEM_Base::get_all's $query_params |
||
866 | * @param string $output ARRAY_A, OBJECT_K, etc. Just like |
||
867 | * @param mixed $columns_to_select , What columns to select. By default, we select all columns specified by the fields on the model, |
||
868 | * 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. |
||
869 | * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array. |
||
870 | * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection |
||
871 | * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d')) |
||
872 | * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT) |
||
873 | * @throws \EE_Error |
||
874 | */ |
||
875 | protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){ |
||
876 | // remember the custom selections, if any, and type cast as array |
||
877 | // (unless $columns_to_select is an object, then just set as an empty array) |
||
878 | // Note: (array) 'some string' === array( 'some string' ) |
||
879 | $this->_custom_selections = ! is_object( $columns_to_select ) ? (array) $columns_to_select : array(); |
||
880 | $model_query_info = $this->_create_model_query_info_carrier( $query_params ); |
||
881 | $select_expressions = $columns_to_select !== null |
||
882 | ? $this->_construct_select_from_input( $columns_to_select ) |
||
883 | : $this->_construct_default_select_sql( $model_query_info ); |
||
884 | $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query( $model_query_info ); |
||
885 | return $this->_do_wpdb_query( 'get_results', array( $SQL, $output ) ); |
||
886 | } |
||
887 | |||
888 | /** |
||
889 | * Gets an array of rows from the database just like $wpdb->get_results would, |
||
890 | * but you can use the $query_params like on EEM_Base::get_all() to more easily |
||
891 | * take care of joins, field preparation etc. |
||
892 | * |
||
893 | * @param array $query_params like EEM_Base::get_all's $query_params |
||
894 | * @param string $output ARRAY_A, OBJECT_K, etc. Just like |
||
895 | * @param mixed $columns_to_select, What columns to select. By default, we select all columns specified by the fields on the model, |
||
896 | * 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. |
||
897 | * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array. |
||
898 | * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection |
||
899 | * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d')) |
||
900 | * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT) |
||
901 | * @throws \EE_Error |
||
902 | */ |
||
903 | public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){ |
||
904 | return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select); |
||
905 | } |
||
906 | |||
907 | |||
908 | /** |
||
909 | * For creating a custom select statement |
||
910 | * @param mixed $columns_to_select either a string to be inserted directly as the select statement, |
||
911 | * or an array where keys are aliases, and values are arrays where 0=>the selection SQL, and 1=>is the datatype |
||
912 | * @throws EE_Error |
||
913 | * @return string |
||
914 | */ |
||
915 | private function _construct_select_from_input($columns_to_select){ |
||
916 | if(is_array($columns_to_select)){ |
||
917 | $select_sql_array = array(); |
||
918 | |||
919 | foreach($columns_to_select as $alias => $selection_and_datatype){ |
||
920 | if( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])){ |
||
921 | throw new EE_Error( |
||
922 | sprintf( |
||
923 | __( |
||
924 | "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')", |
||
925 | "event_espresso" |
||
926 | ), |
||
927 | $selection_and_datatype, |
||
928 | $alias |
||
929 | ) |
||
930 | ); |
||
931 | } |
||
932 | if( ! in_array( $selection_and_datatype[1],$this->_valid_wpdb_data_types)){ |
||
933 | throw new EE_Error( |
||
934 | sprintf( |
||
935 | __( |
||
936 | "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)", |
||
937 | "event_espresso" |
||
938 | ), |
||
939 | $selection_and_datatype[ 1 ], |
||
940 | $selection_and_datatype[ 0 ], |
||
941 | $alias, |
||
942 | implode( ",", $this->_valid_wpdb_data_types ) |
||
943 | ) |
||
944 | ); |
||
945 | } |
||
946 | $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias"; |
||
947 | } |
||
948 | $columns_to_select_string = implode(", ",$select_sql_array); |
||
949 | }else{ |
||
950 | $columns_to_select_string = $columns_to_select; |
||
951 | } |
||
952 | return $columns_to_select_string; |
||
953 | |||
954 | } |
||
955 | |||
956 | |||
957 | |||
958 | /** |
||
959 | * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID' |
||
960 | * |
||
961 | * @return string |
||
962 | * @throws \EE_Error |
||
963 | */ |
||
964 | public function primary_key_name(){ |
||
965 | return $this->get_primary_key_field()->get_name(); |
||
966 | } |
||
967 | |||
968 | |||
969 | |||
970 | /** |
||
971 | * Gets a single item for this model from the DB, given only its ID (or null if none is found). |
||
972 | * If there is no primary key on this model, $id is treated as primary key string |
||
973 | * @param mixed $id int or string, depending on the type of the model's primary key |
||
974 | * @return EE_Base_Class |
||
975 | */ |
||
976 | public function get_one_by_ID($id){ |
||
977 | if( $this->get_from_entity_map( $id ) ){ |
||
978 | return $this->get_from_entity_map( $id ); |
||
979 | } |
||
980 | return $this->get_one( |
||
981 | $this->alter_query_params_to_restrict_by_ID( |
||
982 | $id, |
||
983 | array( 'default_where_conditions' => 'minimum' ) |
||
984 | ) |
||
985 | ); |
||
986 | } |
||
987 | |||
988 | |||
989 | |||
990 | /** |
||
991 | * Alters query parameters to only get items with this ID are returned. |
||
992 | * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string() |
||
993 | * |
||
994 | * @param int $id |
||
995 | * @param array $query_params |
||
996 | * @return array of normal query params, @see EEM_Base::get_all |
||
997 | * @throws \EE_Error |
||
998 | */ |
||
999 | public function alter_query_params_to_restrict_by_ID( $id, $query_params = array() ) { |
||
1000 | if( ! isset( $query_params[ 0 ] ) ) { |
||
1001 | $query_params[ 0 ] = array(); |
||
1002 | } |
||
1003 | if( $this->has_primary_key_field ( ) ) { |
||
1004 | $query_params[ 0 ][ $this->primary_key_name() ] = $id ; |
||
1005 | }else{ |
||
1006 | //no primary key, so the $id must be from the get_index_primary_key_string() |
||
1007 | $query_params[0] = array_replace_recursive( $query_params[ 0 ], $this->parse_index_primary_key_string( $id ) ); |
||
1008 | } |
||
1009 | return $query_params; |
||
1010 | } |
||
1011 | |||
1012 | |||
1013 | |||
1014 | /** |
||
1015 | * 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, |
||
1016 | * null is returned. |
||
1017 | * |
||
1018 | * @param array $query_params like EEM_Base's $query_params variable. |
||
1019 | * @return EE_Base_Class | NULL |
||
1020 | * @throws \EE_Error |
||
1021 | */ |
||
1022 | View Code Duplication | public function get_one($query_params = array()){ |
|
1023 | if( ! is_array( $query_params ) ){ |
||
1024 | 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' ); |
||
1025 | $query_params = array(); |
||
1026 | } |
||
1027 | $query_params['limit'] = 1; |
||
1028 | $items = $this->get_all($query_params); |
||
1029 | if(empty($items)){ |
||
1030 | return null; |
||
1031 | }else{ |
||
1032 | return array_shift($items); |
||
1033 | } |
||
1034 | } |
||
1035 | |||
1036 | |||
1037 | |||
1038 | /** |
||
1039 | * Returns the next x number of items in sequence from the given value as |
||
1040 | * found in the database matching the given query conditions. |
||
1041 | * |
||
1042 | * @param mixed $current_field_value Value used for the reference point. |
||
1043 | * @param null $field_to_order_by What field is used for the |
||
1044 | * reference point. |
||
1045 | * @param int $limit How many to return. |
||
1046 | * @param array $query_params Extra conditions on the query. |
||
1047 | * @param null $columns_to_select If left null, then an array of |
||
1048 | * EE_Base_Class objects is returned, |
||
1049 | * otherwise you can indicate just the |
||
1050 | * columns you want returned. |
||
1051 | * @return EE_Base_Class[]|array |
||
1052 | * @throws \EE_Error |
||
1053 | */ |
||
1054 | public function next_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) { |
||
1055 | return $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, $limit, $query_params, $columns_to_select ); |
||
1056 | } |
||
1057 | |||
1058 | |||
1059 | |||
1060 | /** |
||
1061 | * Returns the previous x number of items in sequence from the given value |
||
1062 | * as found in the database matching the given query conditions. |
||
1063 | * |
||
1064 | * @param mixed $current_field_value Value used for the reference point. |
||
1065 | * @param null $field_to_order_by What field is used for the |
||
1066 | * reference point. |
||
1067 | * @param int $limit How many to return. |
||
1068 | * @param array $query_params Extra conditions on the query. |
||
1069 | * @param null $columns_to_select If left null, then an array of |
||
1070 | * EE_Base_Class objects is returned, |
||
1071 | * otherwise you can indicate just the |
||
1072 | * columns you want returned. |
||
1073 | * @return EE_Base_Class[]|array |
||
1074 | * @throws \EE_Error |
||
1075 | */ |
||
1076 | public function previous_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) { |
||
1077 | return $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, $limit, $query_params, $columns_to_select ); |
||
1078 | } |
||
1079 | |||
1080 | |||
1081 | |||
1082 | /** |
||
1083 | * Returns the next item in sequence from the given value as found in the |
||
1084 | * database matching the given query conditions. |
||
1085 | * |
||
1086 | * @param mixed $current_field_value Value used for the reference point. |
||
1087 | * @param null $field_to_order_by What field is used for the |
||
1088 | * reference point. |
||
1089 | * @param array $query_params Extra conditions on the query. |
||
1090 | * @param null $columns_to_select If left null, then an EE_Base_Class |
||
1091 | * object is returned, otherwise you |
||
1092 | * can indicate just the columns you |
||
1093 | * want and a single array indexed by |
||
1094 | * the columns will be returned. |
||
1095 | * @return EE_Base_Class|null|array() |
||
1096 | * @throws \EE_Error |
||
1097 | */ |
||
1098 | public function next( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) { |
||
1099 | $results = $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, 1, $query_params, $columns_to_select ); |
||
1100 | return empty( $results ) ? null : reset( $results ); |
||
1101 | } |
||
1102 | |||
1103 | |||
1104 | |||
1105 | |||
1106 | /** |
||
1107 | * Returns the previous item in sequence from the given value as found in |
||
1108 | * the database matching the given query conditions. |
||
1109 | * |
||
1110 | * @param mixed $current_field_value Value used for the reference point. |
||
1111 | * @param null $field_to_order_by What field is used for the |
||
1112 | * reference point. |
||
1113 | * @param array $query_params Extra conditions on the query. |
||
1114 | * @param null $columns_to_select If left null, then an EE_Base_Class |
||
1115 | * object is returned, otherwise you |
||
1116 | * can indicate just the columns you |
||
1117 | * want and a single array indexed by |
||
1118 | * the columns will be returned. |
||
1119 | * @return EE_Base_Class|null|array() |
||
1120 | * @throws EE_Error |
||
1121 | */ |
||
1122 | public function previous( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) { |
||
1123 | $results = $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, 1, $query_params, $columns_to_select ); |
||
1124 | return empty( $results ) ? null : reset( $results ); |
||
1125 | } |
||
1126 | |||
1127 | |||
1128 | |||
1129 | |||
1130 | |||
1131 | /** |
||
1132 | * Returns the a consecutive number of items in sequence from the given |
||
1133 | * value as found in the database matching the given query conditions. |
||
1134 | * |
||
1135 | * @param mixed $current_field_value Value used for the reference point. |
||
1136 | * @param string $operand What operand is used for the sequence. |
||
1137 | * @param string $field_to_order_by What field is used for the reference point. |
||
1138 | * @param int $limit How many to return. |
||
1139 | * @param array $query_params Extra conditions on the query. |
||
1140 | * @param null $columns_to_select If left null, then an array of EE_Base_Class objects is returned, |
||
1141 | * otherwise you can indicate just the columns you want returned. |
||
1142 | * @return EE_Base_Class[]|array |
||
1143 | * @throws EE_Error |
||
1144 | */ |
||
1145 | protected function _get_consecutive( $current_field_value, $operand = '>', $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) { |
||
1146 | //if $field_to_order_by is empty then let's assume we're ordering by the primary key. |
||
1147 | if ( empty( $field_to_order_by ) ) { |
||
1148 | if ( $this->has_primary_key_field() ) { |
||
1149 | $field_to_order_by = $this->get_primary_key_field()->get_name(); |
||
1150 | } else { |
||
1151 | |||
1152 | if ( WP_DEBUG ) { |
||
1153 | 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' ) ); |
||
1154 | } |
||
1155 | EE_Error::add_error( __('There was an error with the query.', 'event_espresso') ); |
||
1156 | return array(); |
||
1157 | } |
||
1158 | } |
||
1159 | |||
1160 | if( ! is_array( $query_params ) ){ |
||
1161 | 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' ); |
||
1162 | $query_params = array(); |
||
1163 | } |
||
1164 | |||
1165 | //let's add the where query param for consecutive look up. |
||
1166 | $query_params[0][ $field_to_order_by ] = array( $operand, $current_field_value ); |
||
1167 | $query_params['limit'] = $limit; |
||
1168 | |||
1169 | //set direction |
||
1170 | $incoming_orderby = isset( $query_params['order_by'] ) ? (array)$query_params['order_by'] : array(); |
||
1171 | $query_params['order_by'] = $operand === '>' |
||
1172 | ? array( $field_to_order_by => 'ASC' ) + $incoming_orderby |
||
1173 | : array( $field_to_order_by => 'DESC') + $incoming_orderby; |
||
1174 | |||
1175 | //if $columns_to_select is empty then that means we're returning EE_Base_Class objects |
||
1176 | if ( empty( $columns_to_select ) ) { |
||
1177 | return $this->get_all( $query_params ); |
||
1178 | } else { |
||
1179 | //getting just the fields |
||
1180 | return $this->_get_all_wpdb_results( $query_params, ARRAY_A, $columns_to_select ); |
||
1181 | } |
||
1182 | } |
||
1183 | |||
1184 | |||
1185 | |||
1186 | |||
1187 | /** |
||
1188 | * This sets the _timezone property after model object has been instantiated. |
||
1189 | * @param null | string $timezone valid PHP DateTimeZone timezone string |
||
1190 | */ |
||
1191 | public function set_timezone( $timezone ) { |
||
1192 | if ( $timezone !== null ) { |
||
1193 | $this->_timezone = $timezone; |
||
1194 | } |
||
1195 | //note we need to loop through relations and set the timezone on those objects as well. |
||
1196 | foreach ( $this->_model_relations as $relation ) { |
||
1197 | $relation->set_timezone( $timezone ); |
||
1198 | } |
||
1199 | //and finally we do the same for any datetime fields |
||
1200 | foreach ( $this->_fields as $field ) { |
||
1201 | if ( $field instanceof EE_Datetime_Field ) { |
||
1202 | $field->set_timezone( $timezone ); |
||
1203 | } |
||
1204 | } |
||
1205 | } |
||
1206 | |||
1207 | |||
1208 | |||
1209 | /** |
||
1210 | * This just returns whatever is set for the current timezone. |
||
1211 | * |
||
1212 | * @access public |
||
1213 | * @return string |
||
1214 | */ |
||
1215 | public function get_timezone() { |
||
1216 | //first validate if timezone is set. If not, then let's set it be whatever is set on the model fields. |
||
1217 | if ( empty( $this->_timezone ) ) { |
||
1218 | foreach( $this->_fields as $field ) { |
||
1219 | if ( $field instanceof EE_Datetime_Field ) { |
||
1220 | $this->set_timezone($field->get_timezone()); |
||
1221 | break; |
||
1222 | } |
||
1223 | } |
||
1224 | } |
||
1225 | |||
1226 | //if timezone STILL empty then return the default timezone for the site. |
||
1227 | if ( empty( $this->_timezone ) ) { |
||
1228 | $this->set_timezone( EEH_DTT_Helper::get_timezone() ); |
||
1229 | } |
||
1230 | return $this->_timezone; |
||
1231 | } |
||
1232 | |||
1233 | |||
1234 | |||
1235 | /** |
||
1236 | * This returns the date formats set for the given field name and also ensures that |
||
1237 | * $this->_timezone property is set correctly. |
||
1238 | * |
||
1239 | * @since 4.6.x |
||
1240 | * @param string $field_name The name of the field the formats are being retrieved for. |
||
1241 | * @param bool $pretty Whether to return the pretty formats (true) or not (false). |
||
1242 | * @throws EE_Error If the given field_name is not of the EE_Datetime_Field type. |
||
1243 | * |
||
1244 | * @return array formats in an array with the date format first, and the time format last. |
||
1245 | */ |
||
1246 | public function get_formats_for( $field_name, $pretty = false ) { |
||
1247 | $field_settings = $this->field_settings_for( $field_name ); |
||
1248 | |||
1249 | //if not a valid EE_Datetime_Field then throw error |
||
1250 | if ( ! $field_settings instanceof EE_Datetime_Field ) { |
||
1251 | 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 ) ); |
||
1252 | } |
||
1253 | |||
1254 | //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on |
||
1255 | //the field. |
||
1256 | $this->_timezone = $field_settings->get_timezone(); |
||
1257 | |||
1258 | return array( $field_settings->get_date_format( $pretty ), $field_settings->get_time_format( $pretty ) ); |
||
1259 | } |
||
1260 | |||
1261 | |||
1262 | |||
1263 | /** |
||
1264 | * This returns the current time in a format setup for a query on this model. |
||
1265 | * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because |
||
1266 | * it will return: |
||
1267 | * - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for NOW |
||
1268 | * - or a unix timestamp (equivalent to time()) |
||
1269 | * |
||
1270 | * @since 4.6.x |
||
1271 | * @param string $field_name The field the current time is needed for. |
||
1272 | * @param bool $timestamp True means to return a unix timestamp. Otherwise a |
||
1273 | * formatted string matching the set format for the field in the set timezone will |
||
1274 | * be returned. |
||
1275 | * @param string $what Whether to return the string in just the time format, the date format, or both. |
||
1276 | * |
||
1277 | * @throws EE_Error If the given field_name is not of the EE_Datetime_Field type. |
||
1278 | * |
||
1279 | * @return int|string If the given field_name is not of the EE_Datetime_Field type, then an EE_Error |
||
1280 | * exception is triggered. |
||
1281 | */ |
||
1282 | public function current_time_for_query( $field_name, $timestamp = false, $what = 'both' ) { |
||
1283 | $formats = $this->get_formats_for( $field_name ); |
||
1284 | |||
1285 | $DateTime = new DateTime( "now", new DateTimeZone( $this->_timezone ) ); |
||
1286 | |||
1287 | if ( $timestamp ) { |
||
1288 | return $DateTime->format( 'U' ); |
||
1289 | } |
||
1290 | |||
1291 | //not returning timestamp, so return formatted string in timezone. |
||
1292 | switch( $what ) { |
||
1293 | case 'time' : |
||
1294 | return $DateTime->format( $formats[1] ); |
||
1295 | break; |
||
1296 | case 'date' : |
||
1297 | return $DateTime->format( $formats[0] ); |
||
1298 | break; |
||
1299 | default : |
||
1300 | return $DateTime->format( implode( ' ', $formats ) ); |
||
1301 | break; |
||
1302 | } |
||
1303 | } |
||
1304 | |||
1305 | |||
1306 | |||
1307 | /** |
||
1308 | * This receives a time string for a given field and ensures that it is setup to match what the internal settings |
||
1309 | * for the model are. Returns a DateTime object. |
||
1310 | * Note: a gotcha for when you send in unix timestamp. Remember a unix timestamp is already timezone agnostic, |
||
1311 | * (functionally the equivalent of UTC+0). So when you send it in, whatever timezone string you include is ignored. |
||
1312 | * |
||
1313 | * @param string $field_name The field being setup. |
||
1314 | * @param string $timestring The date time string being used. |
||
1315 | * @param string $incoming_format The format for the time string. |
||
1316 | * @param string $timezone By default, it is assumed the incoming time string is in timezone for |
||
1317 | * the blog. If this is not the case, then it can be specified here. If incoming format is |
||
1318 | * 'U', this is ignored. |
||
1319 | * @return DateTime |
||
1320 | * @throws \EE_Error |
||
1321 | */ |
||
1322 | public function convert_datetime_for_query( $field_name, $timestring, $incoming_format, $timezone = '' ) { |
||
1323 | |||
1324 | //just using this to ensure the timezone is set correctly internally |
||
1325 | $this->get_formats_for( $field_name ); |
||
1326 | |||
1327 | //load EEH_DTT_Helper |
||
1328 | $set_timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone; |
||
1329 | |||
1330 | $incomingDateTime = date_create_from_format( $incoming_format, $timestring, new DateTimeZone( $set_timezone ) ); |
||
1331 | |||
1332 | return $incomingDateTime->setTimezone( new DateTimeZone( $this->_timezone ) ); |
||
1333 | } |
||
1334 | |||
1335 | |||
1336 | |||
1337 | |||
1338 | /** |
||
1339 | * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects |
||
1340 | * @return EE_Table_Base[] |
||
1341 | */ |
||
1342 | public function get_tables(){ |
||
1343 | return $this->_tables; |
||
1344 | } |
||
1345 | |||
1346 | |||
1347 | |||
1348 | /** |
||
1349 | * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally |
||
1350 | * also updates all the model objects, where the criteria expressed in $query_params are met.. |
||
1351 | * 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, |
||
1352 | * it inserts an entry in the secondary table. |
||
1353 | * 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 |
||
1354 | * (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. |
||
1355 | * 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, |
||
1356 | * the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which are not specified) |
||
1357 | * |
||
1358 | *@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. |
||
1359 | * 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, |
||
1360 | * we'd use this method as follows: |
||
1361 | * EEM_Transaction::instance()->update( |
||
1362 | * array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'), |
||
1363 | * array(array('TXN_ID'=>34))); |
||
1364 | * @param array $query_params very much like EEM_Base::get_all's $query_params |
||
1365 | * 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 |
||
1366 | * 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, |
||
1367 | * 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 |
||
1368 | * 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 |
||
1369 | * 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 |
||
1370 | * escape HTML characters in the prepare_for_set method...) |
||
1371 | * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects |
||
1372 | * in this model's entity map according to $fields_n_values that match $query_params. This |
||
1373 | * obviously has some overhead, so you can disable it by setting this to FALSE, but |
||
1374 | * be aware that model objects being used could get out-of-sync with the database |
||
1375 | * @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) |
||
1376 | * @throws \EE_Error |
||
1377 | */ |
||
1378 | public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = TRUE){ |
||
1379 | if( ! is_array( $query_params ) ){ |
||
1380 | 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' ); |
||
1381 | $query_params = array(); |
||
1382 | } |
||
1383 | /** |
||
1384 | * Action called before a model update call has been made. |
||
1385 | * |
||
1386 | * @param EEM_Base $model |
||
1387 | * @param array $fields_n_values the updated fields and their new values |
||
1388 | * @param array $query_params @see EEM_Base::get_all() |
||
1389 | */ |
||
1390 | do_action( 'AHEE__EEM_Base__update__begin',$this, $fields_n_values, $query_params ); |
||
1391 | /** |
||
1392 | * Filters the fields about to be updated given the query parameters. You can provide the |
||
1393 | * $query_params to $this->get_all() to find exactly which records will be updated |
||
1394 | * @param array $fields_n_values fields and their new values |
||
1395 | * @param EEM_Base $model the model being queried |
||
1396 | * @param array $query_params see EEM_Base::get_all() |
||
1397 | */ |
||
1398 | $fields_n_values = (array)apply_filters( 'FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this, $query_params ); |
||
1399 | //need to verify that, for any entry we want to update, there are entries in each secondary table. |
||
1400 | //to do that, for each table, verify that it's PK isn't null. |
||
1401 | $tables= $this->get_tables(); |
||
1402 | |||
1403 | //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 |
||
1404 | //NOTE: we should make this code more efficient by NOT querying twice |
||
1405 | //before the real update, but that needs to first go through ALPHA testing |
||
1406 | //as it's dangerous. says Mike August 8 2014 |
||
1407 | |||
1408 | //we want to make sure the default_where strategy is ignored |
||
1409 | $this->_ignore_where_strategy = TRUE; |
||
1410 | $wpdb_select_results = $this->_get_all_wpdb_results($query_params); |
||
1411 | foreach( $wpdb_select_results as $wpdb_result ){ |
||
1412 | // type cast stdClass as array |
||
1413 | $wpdb_result = (array)$wpdb_result; |
||
1414 | //get the model object's PK, as we'll want this if we need to insert a row into secondary tables |
||
1415 | if( $this->has_primary_key_field() ){ |
||
1416 | $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ]; |
||
1417 | }else{ |
||
1418 | //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) |
||
1419 | $main_table_pk_value = null; |
||
1420 | } |
||
1421 | //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 |
||
1422 | //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 |
||
1423 | if(count($tables) > 1){ |
||
1424 | //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry |
||
1425 | //in that table, and so we'll want to insert one |
||
1426 | foreach($tables as $table_obj){ |
||
1427 | $this_table_pk_column = $table_obj->get_fully_qualified_pk_column(); |
||
1428 | //if there is no private key for this table on the results, it means there's no entry |
||
1429 | //in this table, right? so insert a row in the current table, using any fields available |
||
1430 | if( ! ( array_key_exists( $this_table_pk_column, $wpdb_result) && $wpdb_result[ $this_table_pk_column ] )){ |
||
1431 | $success = $this->_insert_into_specific_table($table_obj, $fields_n_values, $main_table_pk_value); |
||
1432 | //if we died here, report the error |
||
1433 | if( ! $success ) { |
||
1434 | return false; |
||
1435 | } |
||
1436 | } |
||
1437 | } |
||
1438 | } |
||
1439 | |||
1440 | // //and now check that if we have cached any models by that ID on the model, that |
||
1441 | // //they also get updated properly |
||
1442 | // $model_object = $this->get_from_entity_map( $main_table_pk_value ); |
||
1443 | // if( $model_object ){ |
||
1444 | // foreach( $fields_n_values as $field => $value ){ |
||
1445 | // $model_object->set($field, $value); |
||
1446 | //let's make sure default_where strategy is followed now |
||
1447 | $this->_ignore_where_strategy = FALSE; |
||
1448 | } |
||
1449 | //if we want to keep model objects in sync, AND |
||
1450 | //if this wasn't called from a model object (to update itself) |
||
1451 | //then we want to make sure we keep all the existing |
||
1452 | //model objects in sync with the db |
||
1453 | if( $keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object ){ |
||
1454 | if( $this->has_primary_key_field() ){ |
||
1455 | $model_objs_affected_ids = $this->get_col( $query_params ); |
||
1456 | }else{ |
||
1457 | //we need to select a bunch of columns and then combine them into the the "index primary key string"s |
||
1458 | $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A ); |
||
1459 | $model_objs_affected_ids = array(); |
||
1460 | foreach( $models_affected_key_columns as $row ){ |
||
1461 | $combined_index_key = $this->get_index_primary_key_string( $row ); |
||
1462 | $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key; |
||
1463 | } |
||
1464 | |||
1465 | } |
||
1466 | |||
1467 | if( ! $model_objs_affected_ids ){ |
||
1468 | //wait wait wait- if nothing was affected let's stop here |
||
1469 | return 0; |
||
1470 | } |
||
1471 | foreach( $model_objs_affected_ids as $id ){ |
||
1472 | $model_obj_in_entity_map = $this->get_from_entity_map( $id ); |
||
1473 | if( $model_obj_in_entity_map ){ |
||
1474 | foreach( $fields_n_values as $field => $new_value ){ |
||
1475 | $model_obj_in_entity_map->set( $field, $new_value ); |
||
1476 | } |
||
1477 | } |
||
1478 | } |
||
1479 | //if there is a primary key on this model, we can now do a slight optimization |
||
1480 | if( $this->has_primary_key_field() ){ |
||
1481 | //we already know what we want to update. So let's make the query simpler so it's a little more efficient |
||
1482 | $query_params = array( |
||
1483 | array( $this->primary_key_name() => array( 'IN', $model_objs_affected_ids ) ), |
||
1484 | 'limit' => count( $model_objs_affected_ids ), 'default_where_conditions' => 'none' ); |
||
1485 | } |
||
1486 | } |
||
1487 | |||
1488 | $model_query_info = $this->_create_model_query_info_carrier( $query_params ); |
||
1489 | $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. |
||
1490 | $rows_affected = $this->_do_wpdb_query('query', array( $SQL ) ); |
||
1491 | /** |
||
1492 | * Action called after a model update call has been made. |
||
1493 | * |
||
1494 | * @param EEM_Base $model |
||
1495 | * @param array $fields_n_values the updated fields and their new values |
||
1496 | * @param array $query_params @see EEM_Base::get_all() |
||
1497 | * @param int $rows_affected |
||
1498 | */ |
||
1499 | do_action( 'AHEE__EEM_Base__update__end',$this, $fields_n_values, $query_params, $rows_affected ); |
||
1500 | return $rows_affected;//how many supposedly got updated |
||
1501 | } |
||
1502 | |||
1503 | |||
1504 | |||
1505 | /** |
||
1506 | * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values |
||
1507 | * are teh values of the field specified (or by default the primary key field) |
||
1508 | * that matched the query params. Note that you should pass the name of the |
||
1509 | * model FIELD, not the database table's column name. |
||
1510 | * |
||
1511 | * @param array $query_params @see EEM_Base::get_all() |
||
1512 | * @param string $field_to_select |
||
1513 | * @return array just like $wpdb->get_col() |
||
1514 | * @throws \EE_Error |
||
1515 | */ |
||
1516 | public function get_col( $query_params = array(), $field_to_select = NULL ){ |
||
1517 | |||
1518 | if( $field_to_select ){ |
||
1519 | $field = $this->field_settings_for( $field_to_select ); |
||
1520 | }elseif( $this->has_primary_key_field ( ) ){ |
||
1521 | $field = $this->get_primary_key_field(); |
||
1522 | }else{ |
||
1523 | //no primary key, just grab the first column |
||
1524 | $field = reset( $this->field_settings()); |
||
1525 | } |
||
1526 | |||
1527 | |||
1528 | $model_query_info = $this->_create_model_query_info_carrier($query_params); |
||
1529 | $select_expressions = $field->get_qualified_column(); |
||
1530 | $SQL ="SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info); |
||
1531 | return $this->_do_wpdb_query('get_col', array( $SQL ) ); |
||
1532 | } |
||
1533 | |||
1534 | |||
1535 | |||
1536 | /** |
||
1537 | * Returns a single column value for a single row from the database |
||
1538 | * |
||
1539 | * @param array $query_params @see EEM_Base::get_all() |
||
1540 | * @param string $field_to_select @see EEM_Base::get_col() |
||
1541 | * @return string |
||
1542 | * @throws \EE_Error |
||
1543 | */ |
||
1544 | public function get_var( $query_params = array(), $field_to_select = NULL ) { |
||
1545 | $query_params[ 'limit' ] = 1; |
||
1546 | $col = $this->get_col( $query_params, $field_to_select ); |
||
1547 | if( ! empty( $col ) ) { |
||
1548 | return reset( $col ); |
||
1549 | }else{ |
||
1550 | return NULL; |
||
1551 | } |
||
1552 | } |
||
1553 | |||
1554 | |||
1555 | |||
1556 | /** |
||
1557 | * 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?',..." |
||
1558 | * Values are filtered through wpdb->prepare to avoid against SQL injection, but currently no further filtering is done |
||
1559 | * |
||
1560 | * @global $wpdb |
||
1561 | * @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 |
||
1562 | * @return string of SQL |
||
1563 | * @throws \EE_Error |
||
1564 | */ |
||
1565 | public function _construct_update_sql($fields_n_values){ |
||
1566 | /** @type WPDB $wpdb */ |
||
1567 | global $wpdb; |
||
1568 | $cols_n_values = array(); |
||
1569 | foreach($fields_n_values as $field_name => $value){ |
||
1570 | $field_obj = $this->field_settings_for($field_name); |
||
1571 | //if the value is NULL, we want to assign the value to that. |
||
1572 | //wpdb->prepare doesn't really handle that properly |
||
1573 | $prepared_value = $this->_prepare_value_or_use_default( $field_obj, $fields_n_values ); |
||
1574 | $value_sql = $prepared_value===NULL ? 'NULL' : $wpdb->prepare( $field_obj->get_wpdb_data_type(), $prepared_value ); |
||
1575 | $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql; |
||
1576 | } |
||
1577 | return implode(",",$cols_n_values); |
||
1578 | |||
1579 | } |
||
1580 | |||
1581 | |||
1582 | |||
1583 | /** |
||
1584 | * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value). |
||
1585 | * Performs a HARD delete, meaning the database row should always be removed, |
||
1586 | * not just have a flag field on it switched |
||
1587 | * Wrapper for EEM_Base::delete_permanently() |
||
1588 | * |
||
1589 | * @param mixed $id |
||
1590 | * @return boolean whether the row got deleted or not |
||
1591 | * @throws \EE_Error |
||
1592 | */ |
||
1593 | public function delete_permanently_by_ID( $id ) { |
||
1594 | return $this->delete_permanently( |
||
1595 | array( |
||
1596 | array( $this->get_primary_key_field()->get_name() => $id ), |
||
1597 | 'limit' => 1 |
||
1598 | ) |
||
1599 | ); |
||
1600 | } |
||
1601 | |||
1602 | |||
1603 | |||
1604 | /** |
||
1605 | * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value). |
||
1606 | * Wrapper for EEM_Base::delete() |
||
1607 | * |
||
1608 | * @param mixed $id |
||
1609 | * @return boolean whether the row got deleted or not |
||
1610 | * @throws \EE_Error |
||
1611 | */ |
||
1612 | public function delete_by_ID( $id ){ |
||
1613 | return $this->delete( |
||
1614 | array( |
||
1615 | array( $this->get_primary_key_field()->get_name() => $id ), |
||
1616 | 'limit' => 1 |
||
1617 | ) |
||
1618 | ); |
||
1619 | } |
||
1620 | |||
1621 | |||
1622 | |||
1623 | /** |
||
1624 | * Identical to delete_permanently, but does a "soft" delete if possible, |
||
1625 | * meaning if the model has a field that indicates its been "trashed" or |
||
1626 | * "soft deleted", we will just set that instead of actually deleting the rows. |
||
1627 | * |
||
1628 | * @see EEM_Base::delete_permanently |
||
1629 | * @param array $query_params |
||
1630 | * @param boolean $allow_blocking |
||
1631 | * @return int how many rows got deleted |
||
1632 | * @throws \EE_Error |
||
1633 | */ |
||
1634 | public function delete($query_params,$allow_blocking = true){ |
||
1635 | return $this->delete_permanently($query_params, $allow_blocking); |
||
1636 | } |
||
1637 | |||
1638 | |||
1639 | |||
1640 | /** |
||
1641 | * Deletes the model objects that meet the query params. Note: this method is overridden |
||
1642 | * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged |
||
1643 | * as archived, not actually deleted |
||
1644 | * |
||
1645 | * @param array $query_params very much like EEM_Base::get_all's $query_params |
||
1646 | * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info |
||
1647 | * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects |
||
1648 | * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB |
||
1649 | * @return int how many rows got deleted |
||
1650 | * @throws \EE_Error |
||
1651 | */ |
||
1652 | public function delete_permanently($query_params,$allow_blocking = true){ |
||
1700 | |||
1701 | |||
1702 | |||
1703 | /** |
||
1704 | * Checks all the relations that throw error messages when there are blocking related objects |
||
1705 | * for related model objects. If there are any related model objects on those relations, |
||
1706 | * adds an EE_Error, and return true |
||
1707 | * |
||
1708 | * @param EE_Base_Class|int $this_model_obj_or_id |
||
1709 | * @param EE_Base_Class $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which should be ignored when |
||
1710 | * determining whether there are related model objects which block this model object's deletion. Useful |
||
1711 | * if you know A is related to B and are considering deleting A, but want to see if A has any other objects |
||
1712 | * blocking its deletion before removing the relation between A and B |
||
1713 | * @return boolean |
||
1714 | * @throws \EE_Error |
||
1715 | */ |
||
1716 | public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null){ |
||
1717 | //first, if $ignore_this_model_obj was supplied, get its model |
||
1718 | if($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class){ |
||
1719 | $ignored_model = $ignore_this_model_obj->get_model(); |
||
1720 | }else{ |
||
1721 | $ignored_model = null; |
||
1722 | } |
||
1723 | //now check all the relations of $this_model_obj_or_id and see if there |
||
1724 | //are any related model objects blocking it? |
||
1725 | $is_blocked = false; |
||
1726 | foreach($this->_model_relations as $relation_name => $relation_obj){ |
||
1727 | if( $relation_obj->block_delete_if_related_models_exist()){ |
||
1728 | //if $ignore_this_model_obj was supplied, then for the query |
||
1729 | //on that model needs to be told to ignore $ignore_this_model_obj |
||
1730 | if($ignored_model && $relation_name === $ignored_model->get_this_model_name()){ |
||
1731 | $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id,array( |
||
1732 | array($ignored_model->get_primary_key_field()->get_name() => array('!=',$ignore_this_model_obj->ID())))); |
||
1733 | }else{ |
||
1745 | |||
1746 | |||
1747 | |||
1748 | /** |
||
1749 | * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as well. |
||
1750 | * @param array $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results() |
||
1751 | * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info |
||
1752 | * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects |
||
1753 | * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB |
||
1754 | * @throws EE_Error |
||
1755 | * @return string everything that comes after the WHERE statement. |
||
1756 | */ |
||
1757 | protected function _setup_ids_for_delete( $objects_for_deletion, $allow_blocking = true) { |
||
1824 | |||
1825 | |||
1826 | |||
1827 | /** |
||
1828 | * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all). |
||
1829 | * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's column |
||
1830 | * |
||
1831 | * @param array $query_params like EEM_Base::get_all's |
||
1832 | * @param string $field_to_count field on model to count by (not column name) |
||
1833 | * @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; |
||
1834 | * @return int |
||
1835 | * @throws \EE_Error |
||
1836 | */ |
||
1837 | public function count($query_params =array(),$field_to_count = NULL, $distinct = FALSE){ |
||
1853 | |||
1854 | |||
1855 | |||
1856 | /** |
||
1857 | * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful) |
||
1858 | * |
||
1859 | * @param array $query_params like EEM_Base::get_all |
||
1860 | * @param string $field_to_sum name of field (array key in $_fields array) |
||
1861 | * @return float |
||
1862 | * @throws \EE_Error |
||
1863 | */ |
||
1864 | public function sum($query_params, $field_to_sum = NULL){ |
||
1884 | |||
1885 | |||
1886 | |||
1887 | /** |
||
1888 | * Just calls the specified method on $wpdb with the given arguments |
||
1889 | * Consolidates a little extra error handling code |
||
1890 | * @param string $wpdb_method |
||
1891 | * @param array $arguments_to_provide |
||
1892 | * @throws EE_Error |
||
1893 | * @global wpdb $wpdb |
||
1894 | * @return mixed |
||
1895 | */ |
||
1896 | protected function _do_wpdb_query( $wpdb_method, $arguments_to_provide ){ |
||
1897 | //if we're in maintenance mode level 2, DON'T run any queries |
||
1898 | //because level 2 indicates the database needs updating and |
||
1899 | //is probably out of sync with the code |
||
1900 | if( ! EE_Maintenance_Mode::instance()->models_can_query()){ |
||
1901 | 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"))); |
||
1902 | } |
||
1903 | /** @type WPDB $wpdb */ |
||
1904 | global $wpdb; |
||
1905 | View Code Duplication | if( ! method_exists( $wpdb, $wpdb_method ) ){ |
|
1906 | throw new EE_Error( sprintf( __( 'There is no method named "%s" on Wordpress\' $wpdb object','event_espresso' ), $wpdb_method ) ); |
||
1907 | } |
||
1908 | if( WP_DEBUG ){ |
||
1909 | $old_show_errors_value = $wpdb->show_errors; |
||
1910 | $wpdb->show_errors( FALSE ); |
||
1911 | } |
||
1912 | $result = $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide ); |
||
1913 | $this->show_db_query_if_previously_requested( $wpdb->last_query ); |
||
1914 | if( WP_DEBUG ){ |
||
1915 | $wpdb->show_errors( $old_show_errors_value ); |
||
1916 | if( ! empty( $wpdb->last_error ) ){ |
||
1917 | throw new EE_Error( sprintf( __( 'WPDB Error: "%s"', 'event_espresso' ), $wpdb->last_error ) ); |
||
1918 | }elseif( $result === false ){ |
||
1919 | 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 ) ) ); |
||
1920 | } |
||
1921 | }elseif( $result === false ) { |
||
1922 | EE_Error::add_error( |
||
1923 | sprintf( |
||
1924 | __( 'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"', 'event_espresso' ), |
||
1925 | $wpdb_method, |
||
1926 | var_export( $arguments_to_provide, true ), |
||
1927 | $wpdb->last_error |
||
1928 | ), |
||
1929 | __FILE__, |
||
1930 | __FUNCTION__, |
||
1931 | __LINE__ |
||
1932 | ); |
||
1933 | } |
||
1934 | return $result; |
||
1935 | } |
||
1936 | |||
1937 | |||
1938 | |||
1939 | /** |
||
1940 | * Attempts to run the indicated WPDB method with the provided arguments, |
||
1941 | * and if there's an error tries to verify the DB is correct. Uses |
||
1942 | * the static property EEM_Base::$_db_verification_level to determine whether |
||
1943 | * we should try to fix the EE core db, the addons, or just give up |
||
1944 | * @param string $wpdb_method |
||
1945 | * @param array $arguments_to_provide |
||
1946 | * @return mixed |
||
1947 | */ |
||
1948 | private function _process_wpdb_query( $wpdb_method, $arguments_to_provide ) { |
||
1985 | |||
1986 | |||
1987 | |||
1988 | /** |
||
1989 | * Verifies the EE core database is up-to-date and records that we've done it on |
||
1990 | * EEM_Base::$_db_verification_level |
||
1991 | * @param string $wpdb_method |
||
1992 | * @param array $arguments_to_provide |
||
1993 | * @return string |
||
1994 | */ |
||
1995 | View Code Duplication | private function _verify_core_db( $wpdb_method, $arguments_to_provide ){ |
|
2009 | |||
2010 | |||
2011 | |||
2012 | /** |
||
2013 | * Verifies the EE addons' database is up-to-date and records that we've done it on |
||
2014 | * EEM_Base::$_db_verification_level |
||
2015 | * @param $wpdb_method |
||
2016 | * @param $arguments_to_provide |
||
2017 | * @return string |
||
2018 | */ |
||
2019 | View Code Duplication | private function _verify_addons_db( $wpdb_method, $arguments_to_provide ) { |
|
2033 | |||
2034 | |||
2035 | |||
2036 | /** |
||
2037 | * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts |
||
2038 | * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning |
||
2039 | * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING ..." |
||
2040 | * @param EE_Model_Query_Info_Carrier $model_query_info |
||
2041 | * @return string |
||
2042 | */ |
||
2043 | private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info){ |
||
2051 | |||
2052 | /** |
||
2053 | * Set to easily debug the next X queries ran from this model. |
||
2054 | * @param int $count |
||
2055 | */ |
||
2056 | public function show_next_x_db_queries($count = 1){ |
||
2059 | |||
2060 | |||
2061 | |||
2062 | /** |
||
2063 | * @param $sql_query |
||
2064 | */ |
||
2065 | public function show_db_query_if_previously_requested($sql_query){ |
||
2071 | |||
2072 | |||
2073 | |||
2074 | /** |
||
2075 | * Adds a relationship of the correct type between $modelObject and $otherModelObject. |
||
2076 | * There are the 3 cases: |
||
2077 | * '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. |
||
2078 | * '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. |
||
2079 | * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one. |
||
2080 | * 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 |
||
2081 | * |
||
2082 | * @param EE_Base_Class /int $thisModelObject |
||
2083 | * @param EE_Base_Class /int $id_or_obj EE_base_Class or ID of other Model Object |
||
2084 | * @param string $relationName , key in EEM_Base::_relations |
||
2085 | * 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') |
||
2086 | * @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. |
||
2087 | * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj |
||
2088 | * @throws \EE_Error |
||
2089 | */ |
||
2090 | public function add_relationship_to($id_or_obj,$other_model_id_or_obj, $relationName, $extra_join_model_fields_n_values = array()){ |
||
2094 | |||
2095 | |||
2096 | |||
2097 | /** |
||
2098 | * Removes a relationship of the correct type between $modelObject and $otherModelObject. |
||
2099 | * There are the 3 cases: |
||
2100 | * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an error |
||
2101 | * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws an error |
||
2102 | * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models. |
||
2103 | * |
||
2104 | * @param EE_Base_Class /int $id_or_obj |
||
2105 | * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object |
||
2106 | * @param string $relationName key in EEM_Base::_relations |
||
2107 | * @return boolean of success |
||
2108 | * @throws \EE_Error |
||
2109 | * @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. |
||
2110 | */ |
||
2111 | public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query= array() ){ |
||
2115 | |||
2116 | |||
2117 | |||
2118 | /** |
||
2119 | * @param mixed $id_or_obj |
||
2120 | * @param string $relationName |
||
2121 | * @param array $where_query_params |
||
2122 | * @param EE_Base_Class[] objects to which relations were removed |
||
2123 | * @return \EE_Base_Class[] |
||
2124 | * @throws \EE_Error |
||
2125 | */ |
||
2126 | public function remove_relations($id_or_obj,$relationName,$where_query_params = array()){ |
||
2130 | |||
2131 | |||
2132 | |||
2133 | /** |
||
2134 | * Gets all the related items of the specified $model_name, using $query_params. |
||
2135 | * Note: by default, we remove the "default query params" |
||
2136 | * because we want to get even deleted items etc. |
||
2137 | * |
||
2138 | * @param mixed $id_or_obj EE_Base_Class child or its ID |
||
2139 | * @param string $model_name like 'Event', 'Registration', etc. always singular |
||
2140 | * @param array $query_params like EEM_Base::get_all |
||
2141 | * @return EE_Base_Class[] |
||
2142 | * @throws \EE_Error |
||
2143 | */ |
||
2144 | public function get_all_related($id_or_obj, $model_name, $query_params = null){ |
||
2149 | |||
2150 | |||
2151 | |||
2152 | /** |
||
2153 | * Deletes all the model objects across the relation indicated by $model_name |
||
2154 | * which are related to $id_or_obj which meet the criteria set in $query_params. |
||
2155 | * However, if the model objects can't be deleted because of blocking related model objects, then |
||
2156 | * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens). |
||
2157 | * |
||
2158 | * @param EE_Base_Class|int|string $id_or_obj |
||
2159 | * @param string $model_name |
||
2160 | * @param array $query_params |
||
2161 | * @return int how many deleted |
||
2162 | * @throws \EE_Error |
||
2163 | */ |
||
2164 | public function delete_related($id_or_obj,$model_name, $query_params = array()){ |
||
2169 | |||
2170 | |||
2171 | |||
2172 | /** |
||
2173 | * Hard deletes all the model objects across the relation indicated by $model_name |
||
2174 | * which are related to $id_or_obj which meet the criteria set in $query_params. If |
||
2175 | * the model objects can't be hard deleted because of blocking related model objects, |
||
2176 | * just does a soft-delete on them instead. |
||
2177 | * |
||
2178 | * @param EE_Base_Class|int|string $id_or_obj |
||
2179 | * @param string $model_name |
||
2180 | * @param array $query_params |
||
2181 | * @return int how many deleted |
||
2182 | * @throws \EE_Error |
||
2183 | */ |
||
2184 | public function delete_related_permanently($id_or_obj,$model_name, $query_params = array()){ |
||
2189 | |||
2190 | |||
2191 | |||
2192 | /** |
||
2193 | * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default, |
||
2194 | * unless otherwise specified in the $query_params |
||
2195 | * |
||
2196 | * @param int /EE_Base_Class $id_or_obj |
||
2197 | * @param string $model_name like 'Event', or 'Registration' |
||
2198 | * @param array $query_params like EEM_Base::get_all's |
||
2199 | * @param string $field_to_count name of field to count by. By default, uses primary key |
||
2200 | * @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; |
||
2201 | * @return int |
||
2202 | * @throws \EE_Error |
||
2203 | */ |
||
2204 | public function count_related($id_or_obj,$model_name,$query_params = array(),$field_to_count = null, $distinct = FALSE){ |
||
2216 | |||
2217 | |||
2218 | |||
2219 | /** |
||
2220 | * Instead of getting the related model objects, simply sums up the values of the specified field. |
||
2221 | * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params |
||
2222 | * |
||
2223 | * @param int /EE_Base_Class $id_or_obj |
||
2224 | * @param string $model_name like 'Event', or 'Registration' |
||
2225 | * @param array $query_params like EEM_Base::get_all's |
||
2226 | * @param string $field_to_sum name of field to count by. By default, uses primary key |
||
2227 | * @return float |
||
2228 | * @throws \EE_Error |
||
2229 | */ |
||
2230 | public function sum_related($id_or_obj,$model_name,$query_params,$field_to_sum = null){ |
||
2246 | |||
2247 | |||
2248 | |||
2249 | /** |
||
2250 | * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given $modelObject |
||
2251 | * |
||
2252 | * @param int | EE_Base_Class $id_or_obj EE_Base_Class child or its ID |
||
2253 | * @param string $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events' |
||
2254 | * @param array $query_params like EEM_Base::get_all's |
||
2255 | * @return EE_Base_Class |
||
2256 | * @throws \EE_Error |
||
2257 | */ |
||
2258 | public function get_first_related( EE_Base_Class $id_or_obj, $other_model_name, $query_params ){ |
||
2268 | |||
2269 | /** |
||
2270 | * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event |
||
2271 | * @return string |
||
2272 | */ |
||
2273 | public function get_this_model_name(){ |
||
2276 | |||
2277 | /** |
||
2278 | * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field |
||
2279 | * @return EE_Any_Foreign_Model_Name_Field |
||
2280 | * @throws EE_Error |
||
2281 | */ |
||
2282 | public function get_field_containing_related_model_name(){ |
||
2293 | |||
2294 | |||
2295 | |||
2296 | /** |
||
2297 | * Inserts a new entry into the database, for each table. |
||
2298 | * |
||
2299 | * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this. |
||
2300 | * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map, |
||
2301 | * we also know there is no model object with the newly inserted item's ID at the moment (because |
||
2302 | * if there were, then they would already be in the DB and this would fail); and in the future if someone |
||
2303 | * creates a model object with this ID (or grabs it from the DB) then it will be added to the |
||
2304 | * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map |
||
2305 | * @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, |
||
2306 | * 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) |
||
2307 | * @return int new primary key on main table that got inserted |
||
2308 | * @throws EE_Error |
||
2309 | */ |
||
2310 | public function insert($field_n_values){ |
||
2338 | |||
2339 | |||
2340 | |||
2341 | /** |
||
2342 | * Checks that the result would satisfy the unique indexes on this model |
||
2343 | * |
||
2344 | * @param array $field_n_values |
||
2345 | * @param string $action |
||
2346 | * @return boolean |
||
2347 | * @throws \EE_Error |
||
2348 | */ |
||
2349 | protected function _satisfies_unique_indexes($field_n_values,$action = 'insert'){ |
||
2374 | |||
2375 | |||
2376 | |||
2377 | /** |
||
2378 | * Checks the database for an item that conflicts (ie, if this item were |
||
2379 | * saved to the DB would break some uniqueness requirement, like a primary key |
||
2380 | * or an index primary key set) with the item specified. $id_obj_or_fields_array |
||
2381 | * can be either an EE_Base_Class or an array of fields n values |
||
2382 | * @param EE_Base_Class|array $obj_or_fields_array |
||
2383 | * @param boolean $include_primary_key whether to use the model object's primary key when looking for conflicts |
||
2384 | * (ie, if false, we ignore the model object's primary key when finding "conflicts". |
||
2385 | * If true, it's also considered). Only works for INT primary key- STRING primary keys cannot be ignored |
||
2386 | * @throws EE_Error |
||
2387 | * @return EE_Base_Class |
||
2388 | */ |
||
2389 | public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true ){ |
||
2423 | |||
2424 | |||
2425 | |||
2426 | /** |
||
2427 | * Like count, but is optimized and returns a boolean instead of an int |
||
2428 | * |
||
2429 | * @param array $query_params |
||
2430 | * @return boolean |
||
2431 | * @throws \EE_Error |
||
2432 | */ |
||
2433 | public function exists($query_params){ |
||
2437 | |||
2438 | |||
2439 | |||
2440 | /** |
||
2441 | * Wrapper for exists, except ignores default query parameters so we're only considering ID |
||
2442 | * |
||
2443 | * @param int|string $id |
||
2444 | * @return boolean |
||
2445 | * @throws \EE_Error |
||
2446 | */ |
||
2447 | public function exists_by_ID($id){ |
||
2450 | |||
2451 | |||
2452 | |||
2453 | /** |
||
2454 | * Inserts a new row in $table, using the $cols_n_values which apply to that table. |
||
2455 | * If a $new_id is supplied and if $table is an EE_Other_Table, we assume |
||
2456 | * we need to add a foreign key column to point to $new_id (which should be the primary key's value |
||
2457 | * on the main table) |
||
2458 | * 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(). |
||
2459 | * @access protected |
||
2460 | * @param EE_Table_Base $table |
||
2461 | * @param array $fields_n_values each key should be in field's keys, and value should be an int, string or float |
||
2462 | * @param int $new_id for now we assume only int keys |
||
2463 | * @throws EE_Error |
||
2464 | * @global WPDB $wpdb only used to get the $wpdb->insert_id after performing an insert |
||
2465 | * @return int ID of new row inserted, or FALSE on failure |
||
2466 | */ |
||
2467 | protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0 ){ |
||
2511 | |||
2512 | |||
2513 | |||
2514 | /** |
||
2515 | * Prepare the $field_obj 's value in $fields_n_values for use in the database. |
||
2516 | * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL, |
||
2517 | * and there is no default, we pass it along. WPDB will take care of it) |
||
2518 | * |
||
2519 | * @param EE_Model_Field_Base $field_obj |
||
2520 | * @param array $fields_n_values |
||
2521 | * @return mixed string|int|float depending on what the table column will be expecting |
||
2522 | * @throws \EE_Error |
||
2523 | */ |
||
2524 | protected function _prepare_value_or_use_default( $field_obj, $fields_n_values ){ |
||
2534 | |||
2535 | |||
2536 | /** |
||
2537 | * 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, |
||
2538 | * and depending on $value_already_prepare_by_model_obj, may also call the field's prepare_for_set() method. |
||
2539 | * @param mixed $value value in the client code domain if $value_already_prepared_by_model_object is false, otherwise a value |
||
2540 | * in the model object's domain (see lengthy comment at top of file) |
||
2541 | * @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 |
||
2542 | * @return mixed a value ready for use in the database for insertions, updating, or in a where clause |
||
2543 | */ |
||
2544 | private function _prepare_value_for_use_in_db($value, $field){ |
||
2561 | |||
2562 | /** |
||
2563 | * Returns the main table on this model |
||
2564 | * @return EE_Primary_Table |
||
2565 | * @throws EE_Error |
||
2566 | */ |
||
2567 | protected function _get_main_table(){ |
||
2575 | |||
2576 | |||
2577 | |||
2578 | /** |
||
2579 | * table |
||
2580 | * returns EE_Primary_Table table name |
||
2581 | * |
||
2582 | * @return string |
||
2583 | * @throws \EE_Error |
||
2584 | */ |
||
2585 | public function table() { |
||
2588 | |||
2589 | /** |
||
2590 | * table |
||
2591 | * returns first EE_Secondary_Table table name |
||
2592 | * @return string |
||
2593 | */ |
||
2594 | public function second_table() { |
||
2599 | |||
2600 | |||
2601 | |||
2602 | /** |
||
2603 | * get_table_obj_by_alias |
||
2604 | * returns table name given it's alias |
||
2605 | * |
||
2606 | * @param string $table_alias |
||
2607 | * @return EE_Primary_Table | EE_Secondary_Table |
||
2608 | */ |
||
2609 | public function get_table_obj_by_alias( $table_alias = '' ) { |
||
2612 | |||
2613 | |||
2614 | |||
2615 | /** |
||
2616 | * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables |
||
2617 | * @return EE_Secondary_Table[] |
||
2618 | */ |
||
2619 | protected function _get_other_tables(){ |
||
2628 | |||
2629 | /** |
||
2630 | * Finds all the fields that correspond to the given table |
||
2631 | * @param string $table_alias, array key in EEM_Base::_tables |
||
2632 | * @return EE_Model_Field_Base[] |
||
2633 | */ |
||
2634 | public function _get_fields_for_table($table_alias){ |
||
2637 | |||
2638 | |||
2639 | |||
2640 | /** |
||
2641 | * Recurses through all the where parameters, and finds all the related models we'll need |
||
2642 | * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't need any |
||
2643 | * related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related Registration model. |
||
2644 | * If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the related Registration, Transaction, and Payment models. |
||
2645 | * |
||
2646 | * @param array $query_params like EEM_Base::get_all's $query_parameters['where'] |
||
2647 | * @return EE_Model_Query_Info_Carrier |
||
2648 | * @throws \EE_Error |
||
2649 | */ |
||
2650 | public function _extract_related_models_from_query($query_params){ |
||
2701 | |||
2702 | /** |
||
2703 | * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join) |
||
2704 | * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having'] |
||
2705 | * @param EE_Model_Query_Info_Carrier $model_query_info_carrier |
||
2706 | * @param string $query_param_type one of $this->_allowed_query_params |
||
2707 | * @throws EE_Error |
||
2708 | * @return \EE_Model_Query_Info_Carrier |
||
2709 | */ |
||
2710 | 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){ |
||
2745 | |||
2746 | |||
2747 | /** |
||
2748 | * For extracting related models from forced_joins, where the array values contain the info about what |
||
2749 | * models to join with. Eg an array like array('Attendee','Price.Price_Type'); |
||
2750 | * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having'] |
||
2751 | * @param EE_Model_Query_Info_Carrier $model_query_info_carrier |
||
2752 | * @param string $query_param_type one of $this->_allowed_query_params |
||
2753 | * @throws EE_Error |
||
2754 | * @return \EE_Model_Query_Info_Carrier |
||
2755 | */ |
||
2756 | 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){ |
||
2768 | |||
2769 | |||
2770 | |||
2771 | /** |
||
2772 | * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all) |
||
2773 | * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object |
||
2774 | * instead of directly constructing the SQL because often we need to extract info from the $query_params |
||
2775 | * but use them in a different order. Eg, we need to know what models we are querying |
||
2776 | * before we know what joins to perform. However, we need to know what data types correspond to which fields on other |
||
2777 | * models before we can finalize the where clause SQL. |
||
2778 | * @param array $query_params |
||
2779 | * @throws EE_Error |
||
2780 | * @return EE_Model_Query_Info_Carrier |
||
2781 | */ |
||
2782 | public function _create_model_query_info_carrier($query_params){ |
||
2973 | |||
2974 | |||
2975 | |||
2976 | /** |
||
2977 | * Gets the where conditions that should be imposed on the query based on the |
||
2978 | * context (eg reading frontend, backend, edit or delete). |
||
2979 | * |
||
2980 | * @param string $context one of EEM_Base::valid_cap_contexts() |
||
2981 | * @return array like EEM_Base::get_all() 's $query_params[0] |
||
2982 | * @throws \EE_Error |
||
2983 | */ |
||
2984 | public function caps_where_conditions( $context = self::caps_read ) { |
||
2996 | |||
2997 | /** |
||
2998 | * Verifies that $should_be_order_string is in $this->_allowed_order_values, |
||
2999 | * otherwise throws an exception |
||
3000 | * @param string $should_be_order_string |
||
3001 | * @return string either ASC, asc, DESC or desc |
||
3002 | * @throws EE_Error |
||
3003 | */ |
||
3004 | View Code Duplication | private function _extract_order($should_be_order_string){ |
|
3011 | |||
3012 | |||
3013 | |||
3014 | /** |
||
3015 | * Looks at all the models which are included in this query, and asks each |
||
3016 | * for their universal_where_params, and returns them in the same format as $query_params[0] (where), |
||
3017 | * so they can be merged |
||
3018 | * @param EE_Model_Query_Info_Carrier $query_info_carrier |
||
3019 | * @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. |
||
3020 | * 'other_models_only' means default where conditions from other models will be used, but not for this primary model. 'all', the default, means |
||
3021 | * default where conditions will apply as normal |
||
3022 | * @param array $where_query_params like EEM_Base::get_all's $query_params[0] |
||
3023 | * @throws EE_Error |
||
3024 | * @return array like $query_params[0], see EEM_Base::get_all for documentation |
||
3025 | */ |
||
3026 | 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()){ |
||
3061 | |||
3062 | |||
3063 | |||
3064 | /** |
||
3065 | * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden, |
||
3066 | * then we also add a special where condition which allows for that model's primary key |
||
3067 | * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name, |
||
3068 | * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL) |
||
3069 | * |
||
3070 | * @param array $default_where_conditions |
||
3071 | * @param array $provided_where_conditions |
||
3072 | * @param EEM_Base $model |
||
3073 | * @param string $model_relation_path like 'Transaction.Payment.' |
||
3074 | * @return array like EEM_Base::get_all's $query_params[0] |
||
3075 | * @throws \EE_Error |
||
3076 | */ |
||
3077 | private function _override_defaults_or_make_null_friendly($default_where_conditions,$provided_where_conditions,$model,$model_relation_path){ |
||
3098 | |||
3099 | /** |
||
3100 | * Uses the _default_where_conditions_strategy set during __construct() to get |
||
3101 | * default where conditions on all get_all, update, and delete queries done by this model. |
||
3102 | * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'), |
||
3103 | * NOT array('Event_CPT.post_type'=>'esp_event'). |
||
3104 | * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment." |
||
3105 | * @return array like EEM_Base::get_all's $query_params[0] (where conditions) |
||
3106 | */ |
||
3107 | private function _get_default_where_conditions($model_relation_path = null){ |
||
3113 | /** |
||
3114 | * Uses the _minimum_where_conditions_strategy set during __construct() to get |
||
3115 | * minimum where conditions on all get_all, update, and delete queries done by this model. |
||
3116 | * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'), |
||
3117 | * NOT array('Event_CPT.post_type'=>'esp_event'). |
||
3118 | * Similar to _get_default_where_conditions |
||
3119 | * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment." |
||
3120 | * @return array like EEM_Base::get_all's $query_params[0] (where conditions) |
||
3121 | */ |
||
3122 | protected function _get_minimum_where_conditions($model_relation_path = null){ |
||
3128 | |||
3129 | |||
3130 | |||
3131 | /** |
||
3132 | * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM. |
||
3133 | * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..." |
||
3134 | * |
||
3135 | * @param EE_Model_Query_Info_Carrier $model_query_info |
||
3136 | * @return string |
||
3137 | * @throws \EE_Error |
||
3138 | */ |
||
3139 | private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info){ |
||
3150 | |||
3151 | /** |
||
3152 | * Gets an array of columns to select for this model, which are necessary for it to create its objects. |
||
3153 | * So that's going to be the columns for all the fields on the model |
||
3154 | * @param string $model_relation_chain like 'Question.Question_Group.Event' |
||
3155 | * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'" |
||
3156 | */ |
||
3157 | public function _get_columns_to_select_for_this_model($model_relation_chain = ''){ |
||
3176 | |||
3177 | |||
3178 | |||
3179 | /** |
||
3180 | * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.', |
||
3181 | * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID' |
||
3182 | * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the SQL |
||
3183 | * for joining, and the data types |
||
3184 | * @param null|string $original_query_param |
||
3185 | * @param string $query_param like Registration.Transaction.TXN_ID |
||
3186 | * @param EE_Model_Query_Info_Carrier $passed_in_query_info |
||
3187 | * @param string $query_param_type like Registration.Transaction.TXN_ID |
||
3188 | * 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 |
||
3189 | * @param string $original_query_param what it originally was (eg Registration.Transaction.TXN_ID). If null, we assume it matches $query_param |
||
3190 | * @throws EE_Error |
||
3191 | * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it |
||
3192 | */ |
||
3193 | private function _extract_related_model_info_from_query_param( |
||
3270 | |||
3271 | |||
3272 | |||
3273 | /** |
||
3274 | * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name |
||
3275 | * and store it on $passed_in_query_info |
||
3276 | * |
||
3277 | * @param string $model_name |
||
3278 | * @param EE_Model_Query_Info_Carrier $passed_in_query_info |
||
3279 | * @param string $original_query_param used to extract the relation chain between the queried model and $model_name. |
||
3280 | * Eg, if we are querying Event, and are adding a join to 'Payment' with the original query param key 'Registration.Transaction.Payment.PAY_amount', |
||
3281 | * we want to extract 'Registration.Transaction.Payment', in case Payment wants to add default query params so that it will know |
||
3282 | * 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) |
||
3283 | * @return void |
||
3284 | * @throws \EE_Error |
||
3285 | */ |
||
3286 | private function _add_join_to_model($model_name, EE_Model_Query_Info_Carrier $passed_in_query_info,$original_query_param){ |
||
3307 | |||
3308 | |||
3309 | |||
3310 | /** |
||
3311 | * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc. |
||
3312 | * |
||
3313 | * @param array $where_params like EEM_Base::get_all |
||
3314 | * @return string of SQL |
||
3315 | * @throws \EE_Error |
||
3316 | */ |
||
3317 | private function _construct_where_clause($where_params){ |
||
3325 | |||
3326 | |||
3327 | |||
3328 | /** |
||
3329 | * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE', |
||
3330 | * and should be passed HAVING parameters, not WHERE parameters |
||
3331 | * |
||
3332 | * @param array $having_params |
||
3333 | * @return string |
||
3334 | * @throws \EE_Error |
||
3335 | */ |
||
3336 | private function _construct_having_clause($having_params){ |
||
3345 | |||
3346 | /** |
||
3347 | * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name. |
||
3348 | * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on EEM_Attendee. |
||
3349 | * @param string $field_name |
||
3350 | * @param string $model_name |
||
3351 | * @return EE_Model_Field_Base |
||
3352 | * @throws EE_Error |
||
3353 | */ |
||
3354 | protected function _get_field_on_model($field_name,$model_name){ |
||
3366 | |||
3367 | |||
3368 | |||
3369 | /** |
||
3370 | * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND Event_Meta.meta_value = 'foo'))" |
||
3371 | * @param array $where_params see EEM_Base::get_all for documentation |
||
3372 | * @param string $glue joins each subclause together. Should really only be " AND " or " OR "... |
||
3373 | * @throws EE_Error |
||
3374 | * @return string of SQL |
||
3375 | */ |
||
3376 | private function _construct_condition_clause_recursive($where_params, $glue = ' AND'){ |
||
3412 | |||
3413 | |||
3414 | |||
3415 | /** |
||
3416 | * Takes the input parameter and extract the table name (alias) and column name |
||
3417 | * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID |
||
3418 | * @throws EE_Error |
||
3419 | * @return string table alias and column name for SQL, eg "Transaction.TXN_ID" |
||
3420 | */ |
||
3421 | private function _deduce_column_name_from_query_param($query_param){ |
||
3435 | |||
3436 | /** |
||
3437 | * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition query |
||
3438 | * param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get overwritten |
||
3439 | * Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to |
||
3440 | * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively. |
||
3441 | * @param string $condition_query_param_key |
||
3442 | * @return string |
||
3443 | */ |
||
3444 | View Code Duplication | private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key){ |
|
3453 | |||
3454 | |||
3455 | |||
3456 | /** |
||
3457 | * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'" |
||
3458 | * @param mixed array | string $op_and_value |
||
3459 | * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types |
||
3460 | * @throws EE_Error |
||
3461 | * @return string |
||
3462 | */ |
||
3463 | private function _construct_op_and_value($op_and_value, $field_obj){ |
||
3464 | if ( is_array( $op_and_value ) ) { |
||
3465 | $operator = isset( $op_and_value[0] ) ? $this->_prepare_operator_for_sql( $op_and_value[0] ) : null; |
||
3466 | if ( ! $operator ) { |
||
3467 | $php_array_like_string = array(); |
||
3468 | foreach ( $op_and_value as $key => $value ) { |
||
3469 | $php_array_like_string[] = "$key=>$value"; |
||
3470 | } |
||
3471 | throw new EE_Error( |
||
3472 | sprintf( |
||
3473 | __( |
||
3474 | "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))", |
||
3475 | "event_espresso" |
||
3476 | ), |
||
3477 | implode( ",", $php_array_like_string ) |
||
3478 | ) |
||
3479 | ); |
||
3480 | } |
||
3481 | $value = isset( $op_and_value[1] ) ? $op_and_value[1] : null; |
||
3482 | } else { |
||
3483 | $operator = '='; |
||
3484 | $value = $op_and_value; |
||
3485 | } |
||
3486 | //check to see if the value is actually another field |
||
3487 | if ( is_array( $op_and_value ) && isset( $op_and_value[2] ) && $op_and_value[2] == true ) { |
||
3488 | return $operator . SP . $this->_deduce_column_name_from_query_param( $value ); |
||
3489 | } elseif ( in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) { |
||
3490 | //in this case, the value should be an array, or at least a comma-separated list |
||
3491 | //it will need to handle a little differently |
||
3492 | $cleaned_value = $this->_construct_in_value( $value, $field_obj ); |
||
3493 | //note: $cleaned_value has already been run through $wpdb->prepare() |
||
3494 | return $operator . SP . $cleaned_value; |
||
3495 | } elseif ( in_array( $operator, $this->_between_style_operators ) && is_array( $value ) ) { |
||
3496 | //the value should be an array with count of two. |
||
3497 | if ( count( $value ) !== 2 ) { |
||
3498 | throw new EE_Error( |
||
3499 | sprintf( |
||
3500 | __( |
||
3501 | "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.", |
||
3502 | 'event_espresso' |
||
3503 | ), |
||
3504 | "BETWEEN" |
||
3505 | ) |
||
3506 | ); |
||
3507 | } |
||
3508 | $cleaned_value = $this->_construct_between_value( $value, $field_obj ); |
||
3509 | return $operator . SP . $cleaned_value; |
||
3510 | View Code Duplication | } elseif ( in_array( $operator, $this->_null_style_operators ) ) { |
|
3511 | if ( $value !== null ) { |
||
3512 | throw new EE_Error( |
||
3513 | sprintf( |
||
3514 | __( |
||
3515 | "You attempted to give a value (%s) while using a NULL-style operator (%s). That isn't valid", |
||
3516 | "event_espresso" |
||
3517 | ), |
||
3518 | $value, |
||
3519 | $operator |
||
3520 | ) |
||
3521 | ); |
||
3522 | } |
||
3523 | return $operator; |
||
3524 | } elseif ( $operator === 'LIKE' && ! is_array( $value ) ) { |
||
3525 | //if the operator is 'LIKE', we want to allow percent signs (%) and not |
||
3526 | //remove other junk. So just treat it as a string. |
||
3527 | return $operator . SP . $this->_wpdb_prepare_using_field( $value, '%s' ); |
||
3528 | } elseif ( ! in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) { |
||
3529 | return $operator . SP . $this->_wpdb_prepare_using_field( $value, $field_obj ); |
||
3530 | View Code Duplication | } elseif ( in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) { |
|
3531 | throw new EE_Error( |
||
3532 | sprintf( |
||
3533 | __( |
||
3534 | "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))", |
||
3535 | 'event_espresso' |
||
3536 | ), |
||
3537 | $operator, |
||
3538 | $operator |
||
3539 | ) |
||
3540 | ); |
||
3541 | } elseif ( ! in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) { |
||
3542 | throw new EE_Error( |
||
3543 | sprintf( |
||
3544 | __( |
||
3545 | "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))", |
||
3546 | 'event_espresso' |
||
3547 | ), |
||
3548 | $operator, |
||
3549 | $operator |
||
3550 | ) |
||
3551 | ); |
||
3552 | } else { |
||
3553 | throw new EE_Error( |
||
3554 | sprintf( |
||
3555 | __( |
||
3556 | "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all", |
||
3557 | "event_espresso" |
||
3558 | ), |
||
3559 | http_build_query( $op_and_value ) |
||
3560 | ) |
||
3561 | ); |
||
3562 | } |
||
3563 | } |
||
3564 | |||
3565 | |||
3566 | |||
3567 | /** |
||
3568 | * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'" |
||
3569 | * |
||
3570 | * @param array $values |
||
3571 | * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg '%s' |
||
3572 | * @return string |
||
3573 | * @throws \EE_Error |
||
3574 | */ |
||
3575 | public function _construct_between_value( $values, $field_obj ) { |
||
3582 | |||
3583 | |||
3584 | |||
3585 | /** |
||
3586 | * Takes an array or a comma-separated list of $values and cleans them |
||
3587 | * according to $data_type using $wpdb->prepare, and then makes the list a |
||
3588 | * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would |
||
3589 | * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming |
||
3590 | * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0) |
||
3591 | * |
||
3592 | * @param mixed $values array or comma-separated string |
||
3593 | * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d' |
||
3594 | * @return string of SQL to follow an 'IN' or 'NOT IN' operator |
||
3595 | * @throws \EE_Error |
||
3596 | */ |
||
3597 | public function _construct_in_value($values, $field_obj){ |
||
3618 | |||
3619 | |||
3620 | |||
3621 | /** |
||
3622 | * |
||
3623 | * @param mixed $value |
||
3624 | * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d' |
||
3625 | * @throws EE_Error |
||
3626 | * @return false|null|string |
||
3627 | */ |
||
3628 | private function _wpdb_prepare_using_field($value,$field_obj){ |
||
3640 | |||
3641 | |||
3642 | |||
3643 | /** |
||
3644 | * Takes the input parameter and finds the model field that it indicates. |
||
3645 | * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID |
||
3646 | * @throws EE_Error |
||
3647 | * @return EE_Model_Field_Base |
||
3648 | */ |
||
3649 | protected function _deduce_field_from_query_param($query_param_name){ |
||
3673 | |||
3674 | |||
3675 | |||
3676 | /** |
||
3677 | * 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 |
||
3678 | * which corresponds to it |
||
3679 | * @param string $field_name |
||
3680 | * @throws EE_Error |
||
3681 | * @return string |
||
3682 | */ |
||
3683 | public function _get_qualified_column_for_field($field_name){ |
||
3692 | |||
3693 | |||
3694 | |||
3695 | /** |
||
3696 | * constructs the select use on special limit joins |
||
3697 | * 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). |
||
3698 | * |
||
3699 | * @param string $table_alias The table the select is being built for |
||
3700 | * @param mixed|string $limit The limit for this select |
||
3701 | * @return string The final select join element for the query. |
||
3702 | */ |
||
3703 | public function _construct_limit_join_select( $table_alias, $limit ) { |
||
3718 | |||
3719 | |||
3720 | |||
3721 | /** |
||
3722 | * Constructs the internal join if there are multiple tables, or simply the table's name and alias |
||
3723 | * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id" |
||
3724 | * |
||
3725 | * @return string SQL |
||
3726 | * @throws \EE_Error |
||
3727 | */ |
||
3728 | public function _construct_internal_join(){ |
||
3733 | |||
3734 | |||
3735 | |||
3736 | /** |
||
3737 | * Constructs the SQL for joining all the tables on this model. |
||
3738 | * Normally $alias should be the primary table's alias, but in cases where |
||
3739 | * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the primary table) |
||
3740 | * then we should provide that secondary table's alias. |
||
3741 | * Eg, with $alias being the primary table's alias, this will construct SQL like: |
||
3742 | * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk". |
||
3743 | * With $alias being a secondary table's alias, this will construct SQL like: |
||
3744 | * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk". |
||
3745 | * |
||
3746 | * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause) |
||
3747 | * @return string |
||
3748 | */ |
||
3749 | public function _construct_internal_join_to_table_with_alias($alias_prefixed){ |
||
3767 | |||
3768 | /** |
||
3769 | * Gets an array for storing all the data types on the next-to-be-executed-query. |
||
3770 | * 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) |
||
3771 | * @return array |
||
3772 | */ |
||
3773 | public function _get_data_types(){ |
||
3782 | |||
3783 | |||
3784 | |||
3785 | /** |
||
3786 | * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular) |
||
3787 | * @param string $model_name |
||
3788 | * @throws EE_Error |
||
3789 | * @return EEM_Base |
||
3790 | */ |
||
3791 | public function get_related_model_obj($model_name){ |
||
3798 | |||
3799 | |||
3800 | /** |
||
3801 | * Returns the array of EE_ModelRelations for this model. |
||
3802 | * @return EE_Model_Relation_Base[] |
||
3803 | */ |
||
3804 | public function relation_settings(){ |
||
3807 | |||
3808 | /** |
||
3809 | * Gets all related models that this model BELONGS TO. Handy to know sometimes |
||
3810 | * because without THOSE models, this model probably doesn't have much purpose. |
||
3811 | * (Eg, without an event, datetimes have little purpose.) |
||
3812 | * @return EE_Belongs_To_Relation[] |
||
3813 | */ |
||
3814 | public function belongs_to_relations(){ |
||
3823 | |||
3824 | |||
3825 | |||
3826 | /** |
||
3827 | * Returns the specified EE_Model_Relation, or throws an exception |
||
3828 | * @param string $relation_name name of relation, key in $this->_relatedModels |
||
3829 | * @throws EE_Error |
||
3830 | * @return EE_Model_Relation_Base |
||
3831 | */ |
||
3832 | public function related_settings_for($relation_name){ |
||
3846 | |||
3847 | |||
3848 | |||
3849 | /** |
||
3850 | * A convenience method for getting a specific field's settings, instead of getting all field settings for all fields |
||
3851 | * @param string $fieldName |
||
3852 | * @throws EE_Error |
||
3853 | * @return EE_Model_Field_Base |
||
3854 | */ |
||
3855 | View Code Duplication | public function field_settings_for($fieldName){ |
|
3862 | |||
3863 | /** |
||
3864 | * Checks if this field exists on this model |
||
3865 | * @param string $fieldName a key in the model's _field_settings array |
||
3866 | * @return boolean |
||
3867 | */ |
||
3868 | public function has_field($fieldName){ |
||
3876 | |||
3877 | /** |
||
3878 | * Returns whether or not this model has a relation to the specified model |
||
3879 | * @param string $relation_name possibly one of the keys in the relation_settings array |
||
3880 | * @return boolean |
||
3881 | */ |
||
3882 | public function has_relation($relation_name){ |
||
3890 | |||
3891 | |||
3892 | /** |
||
3893 | * gets the field object of type 'primary_key' from the fieldsSettings attribute. |
||
3894 | * Eg, on EE_Answer that would be ANS_ID field object |
||
3895 | * @param $field_obj |
||
3896 | * @return EE_Model_Field_Base |
||
3897 | */ |
||
3898 | public function is_primary_key_field( $field_obj ){ |
||
3901 | |||
3902 | |||
3903 | |||
3904 | /** |
||
3905 | * gets the field object of type 'primary_key' from the fieldsSettings attribute. |
||
3906 | * Eg, on EE_Answer that would be ANS_ID field object |
||
3907 | * @return EE_Model_Field_Base |
||
3908 | * @throws EE_Error |
||
3909 | */ |
||
3910 | public function get_primary_key_field(){ |
||
3924 | |||
3925 | |||
3926 | |||
3927 | /** |
||
3928 | * Returns whether or not not there is a primary key on this model. |
||
3929 | * Internally does some caching. |
||
3930 | * @return boolean |
||
3931 | */ |
||
3932 | public function has_primary_key_field(){ |
||
3943 | |||
3944 | |||
3945 | |||
3946 | /** |
||
3947 | * Finds the first field of type $field_class_name. |
||
3948 | * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field, EE_Foreign_Key_Field, etc |
||
3949 | * @return EE_Model_Field_Base or null if none is found |
||
3950 | */ |
||
3951 | public function get_a_field_of_type($field_class_name){ |
||
3959 | |||
3960 | |||
3961 | /** |
||
3962 | * Gets a foreign key field pointing to model. |
||
3963 | * @param string $model_name eg Event, Registration, not EEM_Event |
||
3964 | * @return EE_Foreign_Key_Field_Base |
||
3965 | * @throws EE_Error |
||
3966 | */ |
||
3967 | public function get_foreign_key_to($model_name){ |
||
3984 | |||
3985 | |||
3986 | |||
3987 | /** |
||
3988 | * Gets the actual table for the table alias |
||
3989 | * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe |
||
3990 | * a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'. Either one works |
||
3991 | * @return EE_Table_Base |
||
3992 | */ |
||
3993 | public function get_table_for_alias($table_alias){ |
||
3997 | |||
3998 | |||
3999 | |||
4000 | /** |
||
4001 | * Returns a flat array of all field son this model, instead of organizing them |
||
4002 | * by table_alias as they are in the constructor. |
||
4003 | * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields |
||
4004 | * @return EE_Model_Field_Base[] where the keys are the field's name |
||
4005 | */ |
||
4006 | public function field_settings($include_db_only_fields = false){ |
||
4032 | |||
4033 | |||
4034 | |||
4035 | /** |
||
4036 | * cycle though array of attendees and create objects out of each item |
||
4037 | * |
||
4038 | * @access private |
||
4039 | * @param array $rows of results of $wpdb->get_results($query,ARRAY_A) |
||
4040 | * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not, numerically indexed) |
||
4041 | * @throws \EE_Error |
||
4042 | */ |
||
4043 | protected function _create_objects( $rows = array() ) { |
||
4104 | |||
4105 | |||
4106 | |||
4107 | /** |
||
4108 | * The purpose of this method is to allow us to create a model object that is not in the db that holds default values. |
||
4109 | * 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!). |
||
4110 | * |
||
4111 | * @return EE_Base_Class single EE_Base_Class object with default values for the properties. |
||
4112 | */ |
||
4113 | public function create_default_object() { |
||
4126 | |||
4127 | |||
4128 | |||
4129 | /** |
||
4130 | * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value |
||
4131 | * or an stdClass where each property is the name of a column, |
||
4132 | * @return EE_Base_Class |
||
4133 | * @throws \EE_Error |
||
4134 | */ |
||
4135 | public function instantiate_class_from_array_or_object($cols_n_values){ |
||
4176 | /** |
||
4177 | * Gets the model object from the entity map if it exists |
||
4178 | * @param int|string $id the ID of the model object |
||
4179 | * @return EE_Base_Class |
||
4180 | */ |
||
4181 | public function get_from_entity_map( $id ){ |
||
4184 | |||
4185 | |||
4186 | |||
4187 | /** |
||
4188 | * add_to_entity_map |
||
4189 | * |
||
4190 | * Adds the object to the model's entity mappings |
||
4191 | * Effectively tells the models "Hey, this model object is the most up-to-date representation of the data, |
||
4192 | * and for the remainder of the request, it's even more up-to-date than what's in the database. |
||
4193 | * So, if the database doesn't agree with what's in the entity mapper, ignore the database" |
||
4194 | * If the database gets updated directly and you want the entity mapper to reflect that change, |
||
4195 | * then this method should be called immediately after the update query |
||
4196 | * |
||
4197 | * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id). This is so |
||
4198 | * on multisite, the entity map is specific to the query being done for a specific site. |
||
4199 | * |
||
4200 | * @param EE_Base_Class $object |
||
4201 | * @throws EE_Error |
||
4202 | * @return \EE_Base_Class |
||
4203 | */ |
||
4204 | public function add_to_entity_map( EE_Base_Class $object) { |
||
4222 | |||
4223 | /** |
||
4224 | * Public wrapper for _deduce_fields_n_values_from_cols_n_values. |
||
4225 | * |
||
4226 | * Given an array where keys are column (or column alias) names and values, |
||
4227 | * returns an array of their corresponding field names and database values |
||
4228 | * @param array $cols_n_values |
||
4229 | * @return array |
||
4230 | */ |
||
4231 | public function deduce_fields_n_values_from_cols_n_values( $cols_n_values ) { |
||
4234 | |||
4235 | |||
4236 | /** |
||
4237 | * _deduce_fields_n_values_from_cols_n_values |
||
4238 | * |
||
4239 | * Given an array where keys are column (or column alias) names and values, |
||
4240 | * returns an array of their corresponding field names and database values |
||
4241 | * |
||
4242 | * @param string $cols_n_values |
||
4243 | * @return array |
||
4244 | */ |
||
4245 | protected function _deduce_fields_n_values_from_cols_n_values( $cols_n_values ){ |
||
4272 | |||
4273 | |||
4274 | |||
4275 | /** |
||
4276 | * @param $cols_n_values |
||
4277 | * @param $qualified_column |
||
4278 | * @param $regular_column |
||
4279 | * @return null |
||
4280 | */ |
||
4281 | protected function _get_column_value_with_table_alias_or_not( $cols_n_values, $qualified_column, $regular_column ){ |
||
4293 | |||
4294 | |||
4295 | |||
4296 | /** |
||
4297 | * refresh_entity_map_from_db |
||
4298 | * Makes sure the model object in the entity map at $id assumes the values |
||
4299 | * of the database (opposite of EE_base_Class::save()) |
||
4300 | * |
||
4301 | * @param int|string $id |
||
4302 | * @return EE_Base_Class |
||
4303 | * @throws \EE_Error |
||
4304 | */ |
||
4305 | public function refresh_entity_map_from_db( $id ){ |
||
4326 | |||
4327 | |||
4328 | |||
4329 | /** |
||
4330 | * refresh_entity_map_with |
||
4331 | * Leaves the entry in the entity map alone, but updates it to match the provided |
||
4332 | * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map). |
||
4333 | * This is useful if you have a model object you want to make authoritative over what's in the entity map currently. |
||
4334 | * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative |
||
4335 | * |
||
4336 | * @param int|string $id |
||
4337 | * @param EE_Base_Class $replacing_model_obj |
||
4338 | * @return \EE_Base_Class |
||
4339 | * @throws \EE_Error |
||
4340 | */ |
||
4341 | public function refresh_entity_map_with( $id, $replacing_model_obj ) { |
||
4362 | |||
4363 | |||
4364 | |||
4365 | /** |
||
4366 | * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that |
||
4367 | * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so |
||
4368 | * require_once($this->_getClassName().".class.php"); |
||
4369 | * @return string |
||
4370 | */ |
||
4371 | private function _get_class_name(){ |
||
4374 | |||
4375 | |||
4376 | |||
4377 | /** |
||
4378 | * Get the name of the items this model represents, for the quantity specified. Eg, |
||
4379 | * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise |
||
4380 | * it would be 'Events'. |
||
4381 | * @param int $quantity |
||
4382 | * @return string |
||
4383 | */ |
||
4384 | public function item_name($quantity = 1){ |
||
4387 | |||
4388 | |||
4389 | |||
4390 | /** |
||
4391 | * Very handy general function to allow for plugins to extend any child of EE_TempBase. |
||
4392 | * 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) |
||
4393 | * and passed the method's name and arguments. |
||
4394 | * Instead of requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that happen?) |
||
4395 | * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function) |
||
4396 | * 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. |
||
4397 | * Example: in functions.php (or in a plugin): |
||
4398 | * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); |
||
4399 | * function my_callback($previousReturnValue,EE_TempBase $object,$argsArray){ |
||
4400 | * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray); |
||
4401 | * return $previousReturnValue.$returnString; |
||
4402 | * } |
||
4403 | * require('EEM_Answer.model.php'); |
||
4404 | * $answer=EEM_Answer::instance(); |
||
4405 | * echo $answer->my_callback('monkeys',100); |
||
4406 | * //will output "you called my_callback! and passed args:monkeys,100" |
||
4407 | * @param string $methodName name of method which was called on a child of EE_TempBase, but which |
||
4408 | * @param array $args array of original arguments passed to the function |
||
4409 | * @throws EE_Error |
||
4410 | * @return mixed whatever the plugin which calls add_filter decides |
||
4411 | */ |
||
4412 | View Code Duplication | public function __call($methodName,$args){ |
|
4429 | |||
4430 | |||
4431 | |||
4432 | /** |
||
4433 | * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model. |
||
4434 | * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class. |
||
4435 | * |
||
4436 | * @param EE_Base_Class|string|int $base_class_obj_or_id either: |
||
4437 | * the EE_Base_Class object that corresponds to this Model, |
||
4438 | * the object's class name |
||
4439 | * or object's ID |
||
4440 | * @param boolean $ensure_is_in_db if set, we will also verify this model object |
||
4441 | * exists in the database. If it does not, we add it |
||
4442 | * @throws EE_Error |
||
4443 | * @return EE_Base_Class |
||
4444 | */ |
||
4445 | public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ){ |
||
4486 | |||
4487 | |||
4488 | |||
4489 | /** |
||
4490 | * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id |
||
4491 | * is a value of the this model's primary key. If it's an EE_Base_Class child, |
||
4492 | * returns it ID. |
||
4493 | * @param EE_Base_Class|int|string $base_class_obj_or_id |
||
4494 | * @return int|string depending on the type of this model object's ID |
||
4495 | * @throws EE_Error |
||
4496 | */ |
||
4497 | public function ensure_is_ID($base_class_obj_or_id){ |
||
4513 | |||
4514 | |||
4515 | |||
4516 | /** |
||
4517 | * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc) |
||
4518 | * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have |
||
4519 | * been sanitized and converted into the appropriate domain. |
||
4520 | * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by the model |
||
4521 | * object/model field) is when making a method call from WITHIN a model object, which has direct access to its sanitized |
||
4522 | * values. |
||
4523 | * Note: after changing this setting, you should set it back to its previous value (using get_assumption_concerning_values_already_prepared_by_model_object()) |
||
4524 | * eg. |
||
4525 | * $EVT = EEM_Event::instance(); $old_setting = $EVT->get_assumption_concerning_values_already_prepared_by_model_object(); |
||
4526 | * $EVT->assume_values_already_prepared_by_model_object(true); |
||
4527 | * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey'))); |
||
4528 | * $EVT->assume_values_already_prepared_by_model_object($old_setting); |
||
4529 | * @param int $values_already_prepared like one of the constants on EEM_Base |
||
4530 | * @return void |
||
4531 | */ |
||
4532 | public function assume_values_already_prepared_by_model_object($values_already_prepared = self::not_prepared_by_model_object){ |
||
4535 | /** |
||
4536 | * Read comments for assume_values_already_prepared_by_model_object() |
||
4537 | * @return int |
||
4538 | */ |
||
4539 | public function get_assumption_concerning_values_already_prepared_by_model_object(){ |
||
4542 | |||
4543 | /** |
||
4544 | * Gets all the indexes on this model |
||
4545 | * @return EE_Index[] |
||
4546 | */ |
||
4547 | public function indexes(){ |
||
4550 | /** |
||
4551 | * Gets all the Unique Indexes on this model |
||
4552 | * @return EE_Unique_Index[] |
||
4553 | */ |
||
4554 | public function unique_indexes(){ |
||
4563 | |||
4564 | |||
4565 | |||
4566 | /** |
||
4567 | * Gets all the fields which, when combined, make the primary key. |
||
4568 | * This is usually just an array with 1 element (the primary key), but in cases |
||
4569 | * where there is no primary key, it's a combination of fields as defined |
||
4570 | * on a primary index |
||
4571 | * |
||
4572 | * @return EE_Model_Field_Base[] indexed by the field's name |
||
4573 | * @throws \EE_Error |
||
4574 | */ |
||
4575 | public function get_combined_primary_key_fields(){ |
||
4583 | |||
4584 | |||
4585 | |||
4586 | |||
4587 | /** |
||
4588 | * Used to build a primary key string (when the model has no primary key), |
||
4589 | * which can be used a unique string to identify this model object. |
||
4590 | * |
||
4591 | * @param array $cols_n_values keys are field names, values are their values |
||
4592 | * @return string |
||
4593 | * @throws \EE_Error |
||
4594 | */ |
||
4595 | public function get_index_primary_key_string($cols_n_values){ |
||
4599 | |||
4600 | |||
4601 | |||
4602 | /** |
||
4603 | * Gets the field values from the primary key string |
||
4604 | * |
||
4605 | * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string() |
||
4606 | * @param string $index_primary_key_string |
||
4607 | * @return null|array |
||
4608 | * @throws \EE_Error |
||
4609 | */ |
||
4610 | public function parse_index_primary_key_string( $index_primary_key_string) { |
||
4622 | |||
4623 | |||
4624 | |||
4625 | /** |
||
4626 | * verifies that an array of key-value pairs for model fields has a key |
||
4627 | * for each field comprising the primary key index |
||
4628 | * |
||
4629 | * @param array $key_vals |
||
4630 | * @return boolean |
||
4631 | * @throws \EE_Error |
||
4632 | */ |
||
4633 | public function has_all_combined_primary_key_fields( $key_vals ) { |
||
4642 | |||
4643 | |||
4644 | /** |
||
4645 | * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array. |
||
4646 | * We consider something to be a copy if all the attributes match (except the ID, of course). |
||
4647 | * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs |
||
4648 | * @param array $query_params like EEM_Base::get_all's query_params. |
||
4649 | * @throws EE_Error |
||
4650 | * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed) |
||
4651 | */ |
||
4652 | public function get_all_copies($model_object_or_attributes_array, $query_params = array()){ |
||
4673 | |||
4674 | |||
4675 | |||
4676 | /** |
||
4677 | * Gets the first copy we find. See get_all_copies for more details |
||
4678 | * |
||
4679 | * @param mixed EE_Base_Class | array $model_object_or_attributes_array |
||
4680 | * @param array $query_params |
||
4681 | * @return EE_Base_Class |
||
4682 | * @throws \EE_Error |
||
4683 | */ |
||
4684 | View Code Duplication | public function get_one_copy($model_object_or_attributes_array,$query_params = array()){ |
|
4697 | |||
4698 | |||
4699 | |||
4700 | /** |
||
4701 | * Updates the item with the specified id. Ignores default query parameters because |
||
4702 | * we have specified the ID, and its assumed we KNOW what we're doing |
||
4703 | * |
||
4704 | * @param array $fields_n_values keys are field names, values are their new values |
||
4705 | * @param int|string $id the value of the primary key to update |
||
4706 | * @return int number of rows updated |
||
4707 | * @throws \EE_Error |
||
4708 | */ |
||
4709 | public function update_by_ID($fields_n_values,$id){ |
||
4714 | |||
4715 | |||
4716 | |||
4717 | /** |
||
4718 | * Changes an operator which was supplied to the models into one usable in SQL |
||
4719 | * @param string $operator_supplied |
||
4720 | * @return string an operator which can be used in SQL |
||
4721 | * @throws EE_Error |
||
4722 | */ |
||
4723 | private function _prepare_operator_for_sql($operator_supplied){ |
||
4731 | |||
4732 | |||
4733 | |||
4734 | /** |
||
4735 | * Gets an array where keys are the primary keys and values are their 'names' |
||
4736 | * (as determined by the model object's name() function, which is often overridden) |
||
4737 | * |
||
4738 | * @param array $query_params like get_all's |
||
4739 | * @return string[] |
||
4740 | * @throws \EE_Error |
||
4741 | */ |
||
4742 | public function get_all_names($query_params = array()){ |
||
4750 | |||
4751 | |||
4752 | |||
4753 | /** |
||
4754 | * Gets an array of primary keys from the model objects. If you acquired the model objects |
||
4755 | * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because |
||
4756 | * this is duplicated effort and reduces efficiency) you would be better to use |
||
4757 | * array_keys() on $model_objects. |
||
4758 | * |
||
4759 | * @param \EE_Base_Class[] $model_objects |
||
4760 | * @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 |
||
4761 | * @return array |
||
4762 | * @throws \EE_Error |
||
4763 | */ |
||
4764 | public function get_IDs( $model_objects, $filter_out_empty_ids = false) { |
||
4798 | |||
4799 | /** |
||
4800 | * Returns the string used in capabilities relating to this model. If there |
||
4801 | * are no capabilities that relate to this model returns false |
||
4802 | * @return string|false |
||
4803 | */ |
||
4804 | public function cap_slug(){ |
||
4807 | |||
4808 | |||
4809 | |||
4810 | /** |
||
4811 | * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions). |
||
4812 | * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts()) |
||
4813 | * only returns the cap restrictions array in that context (ie, the array |
||
4814 | * at that key) |
||
4815 | * |
||
4816 | * @param string $context |
||
4817 | * @return EE_Default_Where_Conditions[] indexed by associated capability |
||
4818 | * @throws \EE_Error |
||
4819 | */ |
||
4820 | public function cap_restrictions( $context = EEM_Base::caps_read ) { |
||
4842 | |||
4843 | /** |
||
4844 | * Indicating whether or not this model thinks its a wp core model |
||
4845 | * @return boolean |
||
4846 | */ |
||
4847 | public function is_wp_core_model(){ |
||
4850 | |||
4851 | |||
4852 | |||
4853 | /** |
||
4854 | * Gets all the caps that are missing which impose a restriction on |
||
4855 | * queries made in this context |
||
4856 | * |
||
4857 | * @param string $context one of EEM_Base::caps_ constants |
||
4858 | * @return EE_Default_Where_Conditions[] indexed by capability name |
||
4859 | * @throws \EE_Error |
||
4860 | */ |
||
4861 | public function caps_missing( $context = EEM_Base::caps_read ) { |
||
4871 | |||
4872 | /** |
||
4873 | * Gets the mapping from capability contexts to action strings used in capability names |
||
4874 | * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually |
||
4875 | * one of 'read', 'edit', or 'delete' |
||
4876 | */ |
||
4877 | public function cap_contexts_to_cap_action_map() { |
||
4880 | |||
4881 | |||
4882 | |||
4883 | /** |
||
4884 | * Gets the action string for the specified capability context |
||
4885 | * @param string $context |
||
4886 | * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values |
||
4887 | * @throws \EE_Error |
||
4888 | */ |
||
4889 | public function cap_action_for_context( $context ) { |
||
4906 | |||
4907 | /** |
||
4908 | * Returns all the capability contexts which are valid when querying models |
||
4909 | * @return array |
||
4910 | */ |
||
4911 | static public function valid_cap_contexts() { |
||
4919 | |||
4920 | |||
4921 | |||
4922 | /** |
||
4923 | * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception |
||
4924 | * @param string $context |
||
4925 | * @return bool |
||
4926 | * @throws \EE_Error |
||
4927 | */ |
||
4928 | static public function verify_is_valid_cap_context( $context ) { |
||
4943 | |||
4944 | /** |
||
4945 | * Clears all the models field caches. This is only useful when a sub-class |
||
4946 | * might have added a field or something and these caches might be invalidated |
||
4947 | */ |
||
4948 | protected function _invalidate_field_caches() { |
||
4953 | |||
4954 | |||
4955 | |||
4956 | |||
4957 | } |
||
4958 |
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.