Completed
Branch BUG-8957-add-countries (d46858)
by
unknown
31:05 queued 15:34
created

EEM_Term_Relationship::insert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
	exit( 'No direct script access allowed' );
3
}
4
require_once( EE_MODELS . 'EEM_Base.model.php' );
5
6
7
8
/**
9
 * Attendee Model
10
 *
11
 * @package               Event Espresso
12
 * @subpackage            includes/models/
13
 * @author                Michael Nelson
14
 */
15
class EEM_Term_Relationship extends EEM_Base {
16
17
	// private instance of the Attendee object
18
	protected static $_instance = null;
19
20
21
22
	/**
23
	 * EEM_Term_Relationship constructor.
24
	 *
25
	 * @param string $timezone
26
	 */
27
	protected function __construct( $timezone = null ) {
28
		$this->singular_item = __( 'Term Relationship', 'event_espresso' );
29
		$this->plural_item = __( 'Term Relationships', 'event_espresso' );
30
		$this->_tables = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Term_Relationship...('term_relationships')) of type array<string,object<EE_P...ct<EE_Primary_Table>"}> is incompatible with the declared type array<integer,object<EE_Table_Base>> of property $_tables.

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

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

Loading history...
31
			'Term_Relationship' => new EE_Primary_Table( 'term_relationships' ),
32
		);
33
		$models_this_can_attach_to = array_keys( EE_Registry::instance()->cpt_models() );
34
		$this->_fields = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Term_Relationship...espresso'), false, 0))) of type array<string,array<strin...E_Integer_Field>\"}>"}> is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_fields.

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

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

Loading history...
35
			'Term_Relationship' => array(
36
				'object_id'        => new EE_Foreign_Key_Int_Field(
37
					'object_id',
38
					__( 'Object(Post) ID', 'event_espresso' ),
39
					false,
40
					0,
41
					$models_this_can_attach_to
0 ignored issues
show
Documentation introduced by
$models_this_can_attach_to is of type array<integer,integer|string>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
42
				),
43
				'term_taxonomy_id' => new EE_Foreign_Key_Int_Field(
44
					'term_taxonomy_id',
45
					__(
46
						'Term (in context of a taxonomy) ID',
47
						'event_espresso'
48
					),
49
					false,
50
					0,
51
					'Term_Taxonomy'
52
				),
53
				'term_order'       => new EE_Integer_Field(
54
					'term_order', __( 'Term Order', 'event_espresso' ), false, 0
55
				),
56
			),
57
		);
58
		$this->_model_relations = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Term_Taxonomy' =>..._Belongs_To_Relation()) of type array<string,object<EE_B...Belongs_To_Relation>"}> is incompatible with the declared type array<integer,object<EE_Model_Relation_Base>> of property $_model_relations.

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

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

Loading history...
59
			'Term_Taxonomy' => new EE_Belongs_To_Relation(),
60
		);
61
		foreach ( $models_this_can_attach_to as $model_name ) {
62
			$this->_model_relations[ $model_name ] = new EE_Belongs_To_Relation();
63
		}
64
		$this->_indexes = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('PRIMARY' => new \..., 'term_taxonomy_id'))) of type array<string,object<EE_P...E_Primary_Key_Index>"}> is incompatible with the declared type array<integer,object<EE_Index>> of property $_indexes.

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

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

Loading history...
65
			'PRIMARY' => new EE_Primary_Key_Index( array( 'object_id', 'term_taxonomy_id' ) ),
66
		);
67
		$path_to_event_model = 'Event.';
68
		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Event_Related_Public(
69
			$path_to_event_model
70
		);
71
		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
72
			$path_to_event_model
73
		);
74
		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Event_Related_Protected(
75
			$path_to_event_model
76
		);
77
		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Event_Related_Protected(
78
			$path_to_event_model, EEM_Base::caps_edit
79
		);
80
		$path_to_tax_model = 'Term_Taxonomy.';
81
		//add cap restrictions for editing term relations to the "ee_assign_*"
82
		//and for deleting term relations too
83
		$cap_contexts_affected = array( EEM_Base::caps_edit, EEM_Base::caps_delete );
84
		foreach ( $cap_contexts_affected as $cap_context_affected ) {
85
			$this->_cap_restrictions[ $cap_context_affected ]['ee_assign_event_category'] = new EE_Default_Where_Conditions(
86
				array(
87
					$path_to_tax_model . 'taxonomy*ee_assign_event_category' => array(
88
						'!=',
89
						'espresso_event_categories',
90
					),
91
				)
92
			);
93
			$this->_cap_restrictions[ $cap_context_affected ]['ee_assign_venue_category'] = new EE_Default_Where_Conditions(
94
				array(
95
					$path_to_tax_model . 'taxonomy*ee_assign_venue_category' => array(
96
						'!=',
97
						'espresso_venue_categories',
98
					),
99
				)
100
			);
101
			$this->_cap_restrictions[ $cap_context_affected ]['ee_assign_event_type'] = new EE_Default_Where_Conditions(
102
				array(
103
					$path_to_tax_model . 'taxonomy*ee_assign_event_type' => array( '!=', 'espresso_event_type' ),
104
				)
105
			);
106
		}
107
		parent::__construct( $timezone );
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 27 can also be of type string; however, EEM_Base::__construct() does only seem to accept null, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

Loading history...
108
		add_filter(
109
			'FHEE__Read__create_model_query_params',
110
			array( 'EEM_Term_Relationship', 'rest_api_query_params' ),
111
			10,
112
			3
113
		);
114
	}
115
116
117
118
	/**
119
	 * Makes sure all term-taxonomy counts are correct
120
	 *
121
	 * @param int   $term_taxonomy_id the id of the term taxonomy to update. If NULL, updates ALL
122
	 * @global wpdb $wpdb
123
	 * @return int the number of rows affected
124
	 */
125
	public function update_term_taxonomy_counts( $term_taxonomy_id = null ) {
126
		//because this uses a subquery and sometimes assigning to column to be another column's
127
		//value, we just write the SQL directly.
128
		global $wpdb;
129
		if ( $term_taxonomy_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $term_taxonomy_id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
130
			$second_operand = $wpdb->prepare( '%d', $term_taxonomy_id );
131
		} else {
132
			$second_operand = 'tr.term_taxonomy_id';
133
		}
134
		$rows_affected = $this->_do_wpdb_query(
135
			'query',
136
			array(
137
				"
138
UPDATE {$wpdb->term_taxonomy} AS tt SET count = (
139
	select count(*) as proper_count from {$wpdb->term_relationships} AS tr WHERE tt.term_taxonomy_id = $second_operand
140
)",
141
			)
142
		);
143
		return $rows_affected;
144
	}
145
146
147
148
	/**
149
	 * Overrides the parent to also make sure term-taxonomy counts are up-to-date after
150
	 * inserting
151
	 *
152
	 * @param array $field_n_values @see EEM_Base::insert
153
	 * @return boolean
154
	 */
155
	public function insert( $field_n_values ) {
156
		$return = parent::insert( $field_n_values );
157
		if ( isset( $field_n_values['term_taxonomy_id'] ) ) {
158
			$this->update_term_taxonomy_counts( $field_n_values['term_taxonomy_id'] );
159
		}
160
		return $return;
161
	}
162
163
164
165
	/**
166
	 * Overrides parent so that after an update, we also check the term_taxonomy_counts are
167
	 * all ok
168
	 *
169
	 * @param array   $fields_n_values         see EEM_Base::update
170
	 * @param array   $query_params            @see EEM_Base::get_all
171
	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
172
	 *                                         in this model's entity map according to $fields_n_values that match
173
	 *                                         $query_params. This obviously has some overhead, so you can disable it
174
	 *                                         by setting this to FALSE, but be aware that model objects being used
175
	 *                                         could get out-of-sync with the database
176
	 * @return int
177
	 */
178
	public function update( $fields_n_values, $query_params, $keep_model_objs_in_sync = true ) {
179
		$count = parent::update( $fields_n_values, $query_params, $keep_model_objs_in_sync );
180
		if ( $count ) {
181
			$this->update_term_taxonomy_counts();
182
		}
183
		return $count;
184
	}
185
186
187
188
	/**
189
	 * Overrides parent so that after running this, we also double-check
190
	 * the term taxonomy counts are up-to-date
191
	 *
192
	 * @param array   $query_params @see EEM_Base::get_all
193
	 * @param boolean $allow_blocking
194
	 * @return int @see EEM_Base::delete
195
	 */
196
	public function delete( $query_params, $allow_blocking = true ) {
197
		$count = parent::delete( $query_params, $allow_blocking );
198
		if ( $count ) {
199
			$this->update_term_taxonomy_counts();
200
		}
201
		return $count;
202
	}
203
204
205
206
	/**
207
	 * Makes sure that during REST API queries, we only return term relationships
208
	 * for term taxonomies which should be shown in the rest api
209
	 *
210
	 * @param array    $model_query_params
211
	 * @param array    $querystring_query_params
212
	 * @param EEM_Base $model
213
	 * @return array
214
	 */
215 View Code Duplication
	public static function rest_api_query_params( $model_query_params, $querystring_query_params, $model ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
216
		if ( $model === EEM_Term_Relationship::instance() ) {
217
			$taxonomies = get_taxonomies( array( 'show_in_rest' => true ) );
218
			if ( ! empty( $taxonomies ) ) {
219
				$model_query_params[0]['Term_Taxonomy.taxonomy'] = array( 'IN', $taxonomies );
220
			}
221
		}
222
		return $model_query_params;
223
	}
224
225
226
}
227
// End of file EEM_Term_Relationship.model.php
228
// Location: /includes/models/EEM_Term_Relationship.model.php