Completed
Branch master (8de7dd)
by
unknown
06:29
created
core/db_models/EEM_Price_Type.model.php 1 patch
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -9,204 +9,204 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_Price_Type extends EEM_Soft_Delete_Base
11 11
 {
12
-    /**
13
-     * constants for price base types. In the DB, we decided to store the price base type
14
-     * as an integer. So, to avoid just having magic numbers everwhere (eg, querying for
15
-     * all price types with PBT_ID = 2), we define these constants, to make code more understandable.
16
-     * So, as an example, to query for all price types that are a tax, we'd do
17
-     * EEM_PRice_Type::instance()->get_all(array(array('PBT_ID'=>EEM_Price_Type::base_type_tax)))
18
-     * instead of
19
-     * EEM_Price_Type::instance()->get_all(array(array('PBT_ID'=>2)))
20
-     * Although the 2nd is shorter, it's much less obvious what it's doing. Also, should these magic IDs ever
21
-     * change, we can continue to use the constant, by simply change its value.
22
-     */
23
-    const base_type_base_price = 1;
24
-
25
-    const base_type_discount   = 2;
26
-
27
-    const base_type_surcharge  = 3;
28
-
29
-    const base_type_tax        = 4;
30
-
31
-
32
-    protected static ?EEM_Price_Type $_instance = null;
33
-
34
-    /**
35
-     * keys are one of the base_type_* constants above, and values are the text-representation of the base type.
36
-     *
37
-     * @var string[]
38
-     */
39
-    public array $base_types;
40
-
41
-    /**
42
-     * An array of the price type objects
43
-     */
44
-    public ?array $type = null;
45
-
46
-
47
-    /**
48
-     * return an array of Base types. Keys are INTs which are used in the database,
49
-     * values are text-representations of the base type.
50
-     *
51
-     * @return array
52
-     */
53
-    public function get_base_types(): array
54
-    {
55
-        return $this->base_types;
56
-    }
57
-
58
-
59
-    /**
60
-     * Gets the name of the base
61
-     *
62
-     * @param int $base_type_int
63
-     * @return string
64
-     */
65
-    public function get_base_type_name(int $base_type_int): string
66
-    {
67
-        return $this->base_types[ $base_type_int ];
68
-    }
69
-
70
-
71
-    /**
72
-     * private constructor to prevent direct creation
73
-     *
74
-     * @param string|null $timezone
75
-     * @return void
76
-     * @throws EE_Error
77
-     */
78
-    protected function __construct(?string $timezone = '')
79
-    {
80
-        $this->base_types    = [
81
-            EEM_Price_Type::base_type_base_price => esc_html__('Price', 'event_espresso'),
82
-            EEM_Price_Type::base_type_discount   => esc_html__('Discount', 'event_espresso'),
83
-            EEM_Price_Type::base_type_surcharge  => esc_html__('Surcharge', 'event_espresso'),
84
-            EEM_Price_Type::base_type_tax        => esc_html__('Tax', 'event_espresso'),
85
-        ];
86
-        $this->singular_item = esc_html__('Price Type', 'event_espresso');
87
-        $this->plural_item   = esc_html__('Price Types', 'event_espresso');
88
-
89
-        $this->_tables          = [
90
-            'Price_Type' => new EE_Primary_Table('esp_price_type', 'PRT_ID'),
91
-        ];
92
-        $this->_fields          = [
93
-            'Price_Type' => [
94
-                'PRT_ID'         => new EE_Primary_Key_Int_Field(
95
-                    'PRT_ID',
96
-                    esc_html__('Price Type ID', 'event_espresso')
97
-                ),
98
-                'PRT_name'       => new EE_Plain_Text_Field(
99
-                    'PRT_name',
100
-                    esc_html__('Price Type Name', 'event_espresso'),
101
-                    false,
102
-                    ''
103
-                ),
104
-                'PBT_ID'         => new EE_Enum_Integer_Field(
105
-                    'PBT_ID',
106
-                    esc_html__(
107
-                        'Price Base type ID, 1 = Price , 2 = Discount , 3 = Surcharge , 4 = Tax',
108
-                        'event_espresso'
109
-                    ),
110
-                    false,
111
-                    EEM_Price_Type::base_type_base_price,
112
-                    $this->base_types
113
-                ),
114
-                'PRT_is_percent' => new EE_Boolean_Field(
115
-                    'PRT_is_percent',
116
-                    esc_html__(
117
-                        'Flag indicating price is a percentage',
118
-                        'event_espresso'
119
-                    ),
120
-                    false,
121
-                    false
122
-                ),
123
-                'PRT_order'      => new EE_Integer_Field(
124
-                    'PRT_order',
125
-                    esc_html__(
126
-                        'Order in which price should be applied. ',
127
-                        'event_espresso'
128
-                    ),
129
-                    false,
130
-                    0
131
-                ),
132
-                'PRT_deleted'    => new EE_Trashed_Flag_Field(
133
-                    'PRT_deleted',
134
-                    esc_html__(
135
-                        'Flag indicating price type has been trashed',
136
-                        'event_espresso'
137
-                    ),
138
-                    false,
139
-                    false
140
-                ),
141
-                'PRT_wp_user'    => new EE_WP_User_Field(
142
-                    'PRT_wp_user',
143
-                    esc_html__('Price Type Creator ID', 'event_espresso'),
144
-                    false
145
-                ),
146
-            ],
147
-        ];
148
-        $this->_model_relations = [
149
-            'Price'   => new EE_Has_Many_Relation(),
150
-            'WP_User' => new EE_Belongs_To_Relation(),
151
-        ];
152
-        // this model is generally available for reading
153
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
154
-        // all price types are "default" in terms of capability names
155
-        $this->_caps_slug = 'default_price_types';
156
-        parent::__construct($timezone);
157
-    }
158
-
159
-
160
-    /**
161
-     * instantiate a new price type object with blank/empty properties
162
-     *
163
-     * @return EE_Price_Type
164
-     * @throws EE_Error
165
-     * @throws ReflectionException
166
-     */
167
-    public function get_new_price_type(): EE_Price_Type
168
-    {
169
-        return EE_Price_Type::new_instance();
170
-    }
171
-
172
-
173
-    /**
174
-     * @param array $query_params
175
-     * @param bool  $allow_blocking   if TRUE, matched objects will only be deleted if there is no related model info
176
-     *                                that blocks it (ie, there' sno other data that depends on this data);
177
-     *                                if false, deletes regardless of other objects which may depend on it.
178
-     *                                Its generally advisable to always leave this as TRUE,
179
-     *                                otherwise you could easily corrupt your DB
180
-     * @return int
181
-     * @throws EE_Error
182
-     * @throws ReflectionException
183
-     */
184
-    public function delete_permanently($query_params = [], $allow_blocking = true): int
185
-    {
186
-        $would_be_deleted_price_types    = $this->get_all_deleted_and_undeleted($query_params);
187
-        $would_be_deleted_price_type_ids = array_keys($would_be_deleted_price_types);
188
-
189
-        $ID = $query_params[0][ $this->get_primary_key_field()->get_name() ];
190
-
191
-        // check if any prices use this price type
192
-        $prc_query_params = [['PRT_ID' => ['IN', $would_be_deleted_price_type_ids]]];
193
-        if ($prices = $this->get_all_related($ID, 'Price', $prc_query_params)) {
194
-            $prices_names_and_ids = [];
195
-            foreach ($prices as $price) {
196
-                /* @var $price EE_Price */
197
-                $prices_names_and_ids[] = $price->name() . "(" . $price->ID() . ")";
198
-            }
199
-            $msg = sprintf(
200
-                esc_html__(
201
-                    'The Price Type(s) could not be deleted because there are existing Prices that currently use this Price Type.  If you still wish to delete this Price Type, then either delete those Prices or change them to use other Price Types.The prices are: %s',
202
-                    'event_espresso'
203
-                ),
204
-                implode(",", $prices_names_and_ids)
205
-            );
206
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
207
-            return false;
208
-        }
209
-
210
-        return parent::delete_permanently($query_params);
211
-    }
12
+	/**
13
+	 * constants for price base types. In the DB, we decided to store the price base type
14
+	 * as an integer. So, to avoid just having magic numbers everwhere (eg, querying for
15
+	 * all price types with PBT_ID = 2), we define these constants, to make code more understandable.
16
+	 * So, as an example, to query for all price types that are a tax, we'd do
17
+	 * EEM_PRice_Type::instance()->get_all(array(array('PBT_ID'=>EEM_Price_Type::base_type_tax)))
18
+	 * instead of
19
+	 * EEM_Price_Type::instance()->get_all(array(array('PBT_ID'=>2)))
20
+	 * Although the 2nd is shorter, it's much less obvious what it's doing. Also, should these magic IDs ever
21
+	 * change, we can continue to use the constant, by simply change its value.
22
+	 */
23
+	const base_type_base_price = 1;
24
+
25
+	const base_type_discount   = 2;
26
+
27
+	const base_type_surcharge  = 3;
28
+
29
+	const base_type_tax        = 4;
30
+
31
+
32
+	protected static ?EEM_Price_Type $_instance = null;
33
+
34
+	/**
35
+	 * keys are one of the base_type_* constants above, and values are the text-representation of the base type.
36
+	 *
37
+	 * @var string[]
38
+	 */
39
+	public array $base_types;
40
+
41
+	/**
42
+	 * An array of the price type objects
43
+	 */
44
+	public ?array $type = null;
45
+
46
+
47
+	/**
48
+	 * return an array of Base types. Keys are INTs which are used in the database,
49
+	 * values are text-representations of the base type.
50
+	 *
51
+	 * @return array
52
+	 */
53
+	public function get_base_types(): array
54
+	{
55
+		return $this->base_types;
56
+	}
57
+
58
+
59
+	/**
60
+	 * Gets the name of the base
61
+	 *
62
+	 * @param int $base_type_int
63
+	 * @return string
64
+	 */
65
+	public function get_base_type_name(int $base_type_int): string
66
+	{
67
+		return $this->base_types[ $base_type_int ];
68
+	}
69
+
70
+
71
+	/**
72
+	 * private constructor to prevent direct creation
73
+	 *
74
+	 * @param string|null $timezone
75
+	 * @return void
76
+	 * @throws EE_Error
77
+	 */
78
+	protected function __construct(?string $timezone = '')
79
+	{
80
+		$this->base_types    = [
81
+			EEM_Price_Type::base_type_base_price => esc_html__('Price', 'event_espresso'),
82
+			EEM_Price_Type::base_type_discount   => esc_html__('Discount', 'event_espresso'),
83
+			EEM_Price_Type::base_type_surcharge  => esc_html__('Surcharge', 'event_espresso'),
84
+			EEM_Price_Type::base_type_tax        => esc_html__('Tax', 'event_espresso'),
85
+		];
86
+		$this->singular_item = esc_html__('Price Type', 'event_espresso');
87
+		$this->plural_item   = esc_html__('Price Types', 'event_espresso');
88
+
89
+		$this->_tables          = [
90
+			'Price_Type' => new EE_Primary_Table('esp_price_type', 'PRT_ID'),
91
+		];
92
+		$this->_fields          = [
93
+			'Price_Type' => [
94
+				'PRT_ID'         => new EE_Primary_Key_Int_Field(
95
+					'PRT_ID',
96
+					esc_html__('Price Type ID', 'event_espresso')
97
+				),
98
+				'PRT_name'       => new EE_Plain_Text_Field(
99
+					'PRT_name',
100
+					esc_html__('Price Type Name', 'event_espresso'),
101
+					false,
102
+					''
103
+				),
104
+				'PBT_ID'         => new EE_Enum_Integer_Field(
105
+					'PBT_ID',
106
+					esc_html__(
107
+						'Price Base type ID, 1 = Price , 2 = Discount , 3 = Surcharge , 4 = Tax',
108
+						'event_espresso'
109
+					),
110
+					false,
111
+					EEM_Price_Type::base_type_base_price,
112
+					$this->base_types
113
+				),
114
+				'PRT_is_percent' => new EE_Boolean_Field(
115
+					'PRT_is_percent',
116
+					esc_html__(
117
+						'Flag indicating price is a percentage',
118
+						'event_espresso'
119
+					),
120
+					false,
121
+					false
122
+				),
123
+				'PRT_order'      => new EE_Integer_Field(
124
+					'PRT_order',
125
+					esc_html__(
126
+						'Order in which price should be applied. ',
127
+						'event_espresso'
128
+					),
129
+					false,
130
+					0
131
+				),
132
+				'PRT_deleted'    => new EE_Trashed_Flag_Field(
133
+					'PRT_deleted',
134
+					esc_html__(
135
+						'Flag indicating price type has been trashed',
136
+						'event_espresso'
137
+					),
138
+					false,
139
+					false
140
+				),
141
+				'PRT_wp_user'    => new EE_WP_User_Field(
142
+					'PRT_wp_user',
143
+					esc_html__('Price Type Creator ID', 'event_espresso'),
144
+					false
145
+				),
146
+			],
147
+		];
148
+		$this->_model_relations = [
149
+			'Price'   => new EE_Has_Many_Relation(),
150
+			'WP_User' => new EE_Belongs_To_Relation(),
151
+		];
152
+		// this model is generally available for reading
153
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
154
+		// all price types are "default" in terms of capability names
155
+		$this->_caps_slug = 'default_price_types';
156
+		parent::__construct($timezone);
157
+	}
158
+
159
+
160
+	/**
161
+	 * instantiate a new price type object with blank/empty properties
162
+	 *
163
+	 * @return EE_Price_Type
164
+	 * @throws EE_Error
165
+	 * @throws ReflectionException
166
+	 */
167
+	public function get_new_price_type(): EE_Price_Type
168
+	{
169
+		return EE_Price_Type::new_instance();
170
+	}
171
+
172
+
173
+	/**
174
+	 * @param array $query_params
175
+	 * @param bool  $allow_blocking   if TRUE, matched objects will only be deleted if there is no related model info
176
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
177
+	 *                                if false, deletes regardless of other objects which may depend on it.
178
+	 *                                Its generally advisable to always leave this as TRUE,
179
+	 *                                otherwise you could easily corrupt your DB
180
+	 * @return int
181
+	 * @throws EE_Error
182
+	 * @throws ReflectionException
183
+	 */
184
+	public function delete_permanently($query_params = [], $allow_blocking = true): int
185
+	{
186
+		$would_be_deleted_price_types    = $this->get_all_deleted_and_undeleted($query_params);
187
+		$would_be_deleted_price_type_ids = array_keys($would_be_deleted_price_types);
188
+
189
+		$ID = $query_params[0][ $this->get_primary_key_field()->get_name() ];
190
+
191
+		// check if any prices use this price type
192
+		$prc_query_params = [['PRT_ID' => ['IN', $would_be_deleted_price_type_ids]]];
193
+		if ($prices = $this->get_all_related($ID, 'Price', $prc_query_params)) {
194
+			$prices_names_and_ids = [];
195
+			foreach ($prices as $price) {
196
+				/* @var $price EE_Price */
197
+				$prices_names_and_ids[] = $price->name() . "(" . $price->ID() . ")";
198
+			}
199
+			$msg = sprintf(
200
+				esc_html__(
201
+					'The Price Type(s) could not be deleted because there are existing Prices that currently use this Price Type.  If you still wish to delete this Price Type, then either delete those Prices or change them to use other Price Types.The prices are: %s',
202
+					'event_espresso'
203
+				),
204
+				implode(",", $prices_names_and_ids)
205
+			);
206
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
207
+			return false;
208
+		}
209
+
210
+		return parent::delete_permanently($query_params);
211
+	}
212 212
 }
Please login to merge, or discard this patch.
core/db_models/EEM_State.model.php 2 patches
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -9,205 +9,205 @@
 block discarded – undo
9 9
  */
10 10
 class EEM_State extends EEM_Base
11 11
 {
12
-    protected static ?EEM_State $_instance = null;
13
-
14
-    // array of all states
15
-    private static ?array $_all_states = null;
16
-
17
-    // array of all active states
18
-    private static ?array $_active_states = null;
19
-
20
-
21
-    /**
22
-     * @param string|null $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct(?string $timezone = '')
26
-    {
27
-        $this->singular_item = esc_html__('State/Province', 'event_espresso');
28
-        $this->plural_item   = esc_html__('States/Provinces', 'event_espresso');
29
-
30
-        $this->_tables = [
31
-            'State' => new EE_Primary_Table('esp_state', 'STA_ID'),
32
-        ];
33
-
34
-        $this->_fields          = [
35
-            'State' => [
36
-                'STA_ID'     => new EE_Primary_Key_Int_Field('STA_ID', esc_html__('State ID', 'event_espresso')),
37
-                'CNT_ISO'    => new EE_Foreign_Key_String_Field(
38
-                    'CNT_ISO',
39
-                    esc_html__('Country ISO Code', 'event_espresso'),
40
-                    false,
41
-                    null,
42
-                    'Country'
43
-                ),
44
-                'STA_abbrev' => new EE_Plain_Text_Field(
45
-                    'STA_abbrev',
46
-                    esc_html__('State Abbreviation', 'event_espresso'),
47
-                    false,
48
-                    ''
49
-                ),
50
-                'STA_name'   => new EE_Plain_Text_Field(
51
-                    'STA_name',
52
-                    esc_html__('State Name', 'event_espresso'),
53
-                    false,
54
-                    ''
55
-                ),
56
-                'STA_active' => new EE_Boolean_Field(
57
-                    'STA_active',
58
-                    esc_html__('State Active Flag', 'event_espresso'),
59
-                    false,
60
-                    false
61
-                ),
62
-            ],
63
-        ];
64
-        $this->_model_relations = [
65
-            'Attendee' => new EE_Has_Many_Relation(),
66
-            'Country'  => new EE_Belongs_To_Relation(),
67
-            'Venue'    => new EE_Has_Many_Relation(),
68
-        ];
69
-        // this model is generally available for reading
70
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
71
-        // @todo: only show STA_active
72
-        parent::__construct($timezone);
73
-    }
74
-
75
-
76
-    public function reset_cached_states()
77
-    {
78
-        EEM_State::$_active_states = [];
79
-        EEM_State::$_all_states    = [];
80
-    }
81
-
82
-
83
-    /**
84
-     * @return array
85
-     * @throws EE_Error
86
-     * @throws ReflectionException
87
-     */
88
-    public function get_all_states(): array
89
-    {
90
-        if (self::$_all_states === null) {
91
-            self::$_all_states = $this->get_all(['order_by' => ['STA_name' => 'ASC'], 'limit' => [0, 99999]]);
92
-        }
93
-        return self::$_all_states;
94
-    }
95
-
96
-
97
-    /**
98
-     * @param array $countries
99
-     * @param bool  $flush_cache
100
-     * @return array
101
-     * @throws EE_Error
102
-     * @throws ReflectionException
103
-     */
104
-    public function get_all_active_states(array $countries = [], bool $flush_cache = false): array
105
-    {
106
-        if (self::$_active_states === null || $flush_cache || ! empty($countries)) {
107
-            $countries            = is_array($countries) && ! empty($countries)
108
-                ? $countries
109
-                : EEM_Country::instance()->get_all_active_countries();
110
-            self::$_active_states = $this->get_all(
111
-                [
112
-                    ['STA_active' => true, 'CNT_ISO' => ['IN', array_keys($countries)]],
113
-                    'order_by'   => ['STA_name' => 'ASC'],
114
-                    'limit'      => [0, 99999],
115
-                    'force_join' => ['Country'],
116
-                ]
117
-            );
118
-        }
119
-        return self::$_active_states;
120
-    }
121
-
122
-
123
-    /**
124
-     *  get_all_states_of_active_countries
125
-     *
126
-     * @return array
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function get_all_states_of_active_countries(): array
131
-    {
132
-        if (
133
-            $states = $this->get_all(
134
-                [
135
-                    ['Country.CNT_active' => true, 'STA_active' => true],
136
-                    'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
137
-                ]
138
-            )
139
-        ) {
140
-            return $states;
141
-        }
142
-        return [];
143
-    }
144
-
145
-
146
-    /**
147
-     *  get_all_states_of_active_countries
148
-     *
149
-     * @param array $countries
150
-     * @return array
151
-     * @throws EE_Error
152
-     * @throws ReflectionException
153
-     */
154
-    public function get_all_active_states_for_these_countries(array $countries): array
155
-    {
156
-        if (! $countries) {
157
-            return [];
158
-        }
159
-        return $this->get_all(
160
-            [
161
-                ['Country.CNT_ISO' => ['IN', array_keys($countries)], 'STA_active' => true],
162
-                'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
163
-            ]
164
-        );
165
-    }
166
-
167
-
168
-    /**
169
-     *  get_all_states_of_active_countries
170
-     *
171
-     * @param array $countries
172
-     * @return array
173
-     * @throws EE_Error
174
-     * @throws ReflectionException
175
-     */
176
-    public function get_all_states_for_these_countries(array $countries): array
177
-    {
178
-        if (! $countries) {
179
-            return [];
180
-        }
181
-        return $this->get_all(
182
-            [
183
-                ['Country.CNT_ISO' => ['IN', array_keys($countries)]],
184
-                'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
185
-            ]
186
-        );
187
-    }
188
-
189
-
190
-    /**
191
-     * Gets the state's name by its ID
192
-     *
193
-     * @param int $state_ID
194
-     * @return string
195
-     * @throws EE_Error
196
-     * @throws ReflectionException
197
-     */
198
-    public function get_state_name_by_ID(int $state_ID): string
199
-    {
200
-        if (
201
-            self::$_all_states
202
-            && isset(self::$_all_states[ $state_ID ])
203
-            && self::$_all_states[ $state_ID ] instanceof EE_State
204
-        ) {
205
-            return self::$_all_states[ $state_ID ]->name();
206
-        }
207
-        $names = $this->get_col([['STA_ID' => $state_ID], 'limit' => 1], 'STA_name');
208
-        if (is_array($names) && ! empty($names)) {
209
-            return reset($names);
210
-        }
211
-        return '';
212
-    }
12
+	protected static ?EEM_State $_instance = null;
13
+
14
+	// array of all states
15
+	private static ?array $_all_states = null;
16
+
17
+	// array of all active states
18
+	private static ?array $_active_states = null;
19
+
20
+
21
+	/**
22
+	 * @param string|null $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct(?string $timezone = '')
26
+	{
27
+		$this->singular_item = esc_html__('State/Province', 'event_espresso');
28
+		$this->plural_item   = esc_html__('States/Provinces', 'event_espresso');
29
+
30
+		$this->_tables = [
31
+			'State' => new EE_Primary_Table('esp_state', 'STA_ID'),
32
+		];
33
+
34
+		$this->_fields          = [
35
+			'State' => [
36
+				'STA_ID'     => new EE_Primary_Key_Int_Field('STA_ID', esc_html__('State ID', 'event_espresso')),
37
+				'CNT_ISO'    => new EE_Foreign_Key_String_Field(
38
+					'CNT_ISO',
39
+					esc_html__('Country ISO Code', 'event_espresso'),
40
+					false,
41
+					null,
42
+					'Country'
43
+				),
44
+				'STA_abbrev' => new EE_Plain_Text_Field(
45
+					'STA_abbrev',
46
+					esc_html__('State Abbreviation', 'event_espresso'),
47
+					false,
48
+					''
49
+				),
50
+				'STA_name'   => new EE_Plain_Text_Field(
51
+					'STA_name',
52
+					esc_html__('State Name', 'event_espresso'),
53
+					false,
54
+					''
55
+				),
56
+				'STA_active' => new EE_Boolean_Field(
57
+					'STA_active',
58
+					esc_html__('State Active Flag', 'event_espresso'),
59
+					false,
60
+					false
61
+				),
62
+			],
63
+		];
64
+		$this->_model_relations = [
65
+			'Attendee' => new EE_Has_Many_Relation(),
66
+			'Country'  => new EE_Belongs_To_Relation(),
67
+			'Venue'    => new EE_Has_Many_Relation(),
68
+		];
69
+		// this model is generally available for reading
70
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
71
+		// @todo: only show STA_active
72
+		parent::__construct($timezone);
73
+	}
74
+
75
+
76
+	public function reset_cached_states()
77
+	{
78
+		EEM_State::$_active_states = [];
79
+		EEM_State::$_all_states    = [];
80
+	}
81
+
82
+
83
+	/**
84
+	 * @return array
85
+	 * @throws EE_Error
86
+	 * @throws ReflectionException
87
+	 */
88
+	public function get_all_states(): array
89
+	{
90
+		if (self::$_all_states === null) {
91
+			self::$_all_states = $this->get_all(['order_by' => ['STA_name' => 'ASC'], 'limit' => [0, 99999]]);
92
+		}
93
+		return self::$_all_states;
94
+	}
95
+
96
+
97
+	/**
98
+	 * @param array $countries
99
+	 * @param bool  $flush_cache
100
+	 * @return array
101
+	 * @throws EE_Error
102
+	 * @throws ReflectionException
103
+	 */
104
+	public function get_all_active_states(array $countries = [], bool $flush_cache = false): array
105
+	{
106
+		if (self::$_active_states === null || $flush_cache || ! empty($countries)) {
107
+			$countries            = is_array($countries) && ! empty($countries)
108
+				? $countries
109
+				: EEM_Country::instance()->get_all_active_countries();
110
+			self::$_active_states = $this->get_all(
111
+				[
112
+					['STA_active' => true, 'CNT_ISO' => ['IN', array_keys($countries)]],
113
+					'order_by'   => ['STA_name' => 'ASC'],
114
+					'limit'      => [0, 99999],
115
+					'force_join' => ['Country'],
116
+				]
117
+			);
118
+		}
119
+		return self::$_active_states;
120
+	}
121
+
122
+
123
+	/**
124
+	 *  get_all_states_of_active_countries
125
+	 *
126
+	 * @return array
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function get_all_states_of_active_countries(): array
131
+	{
132
+		if (
133
+			$states = $this->get_all(
134
+				[
135
+					['Country.CNT_active' => true, 'STA_active' => true],
136
+					'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
137
+				]
138
+			)
139
+		) {
140
+			return $states;
141
+		}
142
+		return [];
143
+	}
144
+
145
+
146
+	/**
147
+	 *  get_all_states_of_active_countries
148
+	 *
149
+	 * @param array $countries
150
+	 * @return array
151
+	 * @throws EE_Error
152
+	 * @throws ReflectionException
153
+	 */
154
+	public function get_all_active_states_for_these_countries(array $countries): array
155
+	{
156
+		if (! $countries) {
157
+			return [];
158
+		}
159
+		return $this->get_all(
160
+			[
161
+				['Country.CNT_ISO' => ['IN', array_keys($countries)], 'STA_active' => true],
162
+				'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
163
+			]
164
+		);
165
+	}
166
+
167
+
168
+	/**
169
+	 *  get_all_states_of_active_countries
170
+	 *
171
+	 * @param array $countries
172
+	 * @return array
173
+	 * @throws EE_Error
174
+	 * @throws ReflectionException
175
+	 */
176
+	public function get_all_states_for_these_countries(array $countries): array
177
+	{
178
+		if (! $countries) {
179
+			return [];
180
+		}
181
+		return $this->get_all(
182
+			[
183
+				['Country.CNT_ISO' => ['IN', array_keys($countries)]],
184
+				'order_by' => ['Country.CNT_name' => 'ASC', 'STA_name' => 'ASC'],
185
+			]
186
+		);
187
+	}
188
+
189
+
190
+	/**
191
+	 * Gets the state's name by its ID
192
+	 *
193
+	 * @param int $state_ID
194
+	 * @return string
195
+	 * @throws EE_Error
196
+	 * @throws ReflectionException
197
+	 */
198
+	public function get_state_name_by_ID(int $state_ID): string
199
+	{
200
+		if (
201
+			self::$_all_states
202
+			&& isset(self::$_all_states[ $state_ID ])
203
+			&& self::$_all_states[ $state_ID ] instanceof EE_State
204
+		) {
205
+			return self::$_all_states[ $state_ID ]->name();
206
+		}
207
+		$names = $this->get_col([['STA_ID' => $state_ID], 'limit' => 1], 'STA_name');
208
+		if (is_array($names) && ! empty($names)) {
209
+			return reset($names);
210
+		}
211
+		return '';
212
+	}
213 213
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -12,10 +12,10 @@  discard block
 block discarded – undo
12 12
     protected static ?EEM_State $_instance = null;
13 13
 
14 14
     // array of all states
15
-    private static ?array $_all_states = null;
15
+    private static ? array $_all_states = null;
16 16
 
17 17
     // array of all active states
18
-    private static ?array $_active_states = null;
18
+    private static ? array $_active_states = null;
19 19
 
20 20
 
21 21
     /**
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
             'State' => new EE_Primary_Table('esp_state', 'STA_ID'),
32 32
         ];
33 33
 
34
-        $this->_fields          = [
34
+        $this->_fields = [
35 35
             'State' => [
36 36
                 'STA_ID'     => new EE_Primary_Key_Int_Field('STA_ID', esc_html__('State ID', 'event_espresso')),
37 37
                 'CNT_ISO'    => new EE_Foreign_Key_String_Field(
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
             'Venue'    => new EE_Has_Many_Relation(),
68 68
         ];
69 69
         // this model is generally available for reading
70
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
70
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
         // @todo: only show STA_active
72 72
         parent::__construct($timezone);
73 73
     }
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
      */
154 154
     public function get_all_active_states_for_these_countries(array $countries): array
155 155
     {
156
-        if (! $countries) {
156
+        if ( ! $countries) {
157 157
             return [];
158 158
         }
159 159
         return $this->get_all(
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
      */
176 176
     public function get_all_states_for_these_countries(array $countries): array
177 177
     {
178
-        if (! $countries) {
178
+        if ( ! $countries) {
179 179
             return [];
180 180
         }
181 181
         return $this->get_all(
@@ -199,10 +199,10 @@  discard block
 block discarded – undo
199 199
     {
200 200
         if (
201 201
             self::$_all_states
202
-            && isset(self::$_all_states[ $state_ID ])
203
-            && self::$_all_states[ $state_ID ] instanceof EE_State
202
+            && isset(self::$_all_states[$state_ID])
203
+            && self::$_all_states[$state_ID] instanceof EE_State
204 204
         ) {
205
-            return self::$_all_states[ $state_ID ]->name();
205
+            return self::$_all_states[$state_ID]->name();
206 206
         }
207 207
         $names = $this->get_col([['STA_ID' => $state_ID], 'limit' => 1], 'STA_name');
208 208
         if (is_array($names) && ! empty($names)) {
Please login to merge, or discard this patch.
core/db_models/EEM_CPT_Base.model.php 2 patches
Indentation   +560 added lines, -560 removed lines patch added patch discarded remove patch
@@ -14,564 +14,564 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
16 16
 {
17
-    const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
-
19
-    /**
20
-     * @var string post_status_publish - the wp post status for published cpts
21
-     */
22
-    const post_status_publish = 'publish';
23
-
24
-    /**
25
-     * @var string post_status_future - the wp post status for scheduled cpts
26
-     */
27
-    const post_status_future = 'future';
28
-
29
-    /**
30
-     * @var string post_status_draft - the wp post status for draft cpts
31
-     */
32
-    const post_status_draft = 'draft';
33
-
34
-    /**
35
-     * @var string post_status_pending - the wp post status for pending cpts
36
-     */
37
-    const post_status_pending = 'pending';
38
-
39
-    /**
40
-     * @var string post_status_private - the wp post status for private cpts
41
-     */
42
-    const post_status_private = 'private';
43
-
44
-    /**
45
-     * @var string post_status_trashed - the wp post status for trashed cpts
46
-     */
47
-    const post_status_trashed = 'trash';
48
-
49
-    /**
50
-     * This is an array of custom statuses for the given CPT model (modified by children)
51
-     * format:
52
-     * array(
53
-     *        'status_name' => array(
54
-     *            'label' => esc_html__('Status Name', 'event_espresso'),
55
-     *            'public' => TRUE //whether a public status or not.
56
-     *        )
57
-     * )
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_custom_stati = [];
62
-
63
-
64
-    /**
65
-     * @param string|null $timezone
66
-     * @throws EE_Error
67
-     */
68
-    protected function __construct(?string $timezone = '')
69
-    {
70
-        // adds a relationship to Term_Taxonomy for all these models. For this to work
71
-        // Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
72
-        // eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
73
-        // with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
74
-        // must also be new EE_HABTM_Relation('Term_Relationship');
75
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
76
-        $primary_table_name                      = null;
77
-        // add  the common _status field to all CPT primary tables.
78
-        foreach ($this->_tables as $alias => $table_obj) {
79
-            if ($table_obj instanceof EE_Primary_Table) {
80
-                $primary_table_name = $alias;
81
-            }
82
-        }
83
-        // set default wp post statuses if child has not already set.
84
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
86
-                'post_status',
87
-                esc_html__("Event Status", "event_espresso"),
88
-                false,
89
-                'draft'
90
-            );
91
-        }
92
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
94
-                'to_ping',
95
-                esc_html__('To Ping', 'event_espresso'),
96
-                false,
97
-                ''
98
-            );
99
-        }
100
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
102
-                'pinged',
103
-                esc_html__('Pinged', 'event_espresso'),
104
-                false,
105
-                ''
106
-            );
107
-        }
108
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
110
-                'comment_status',
111
-                esc_html__('Comment Status', 'event_espresso'),
112
-                false,
113
-                'open'
114
-            );
115
-        }
116
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
118
-                'ping_status',
119
-                esc_html__('Ping Status', 'event_espresso'),
120
-                false,
121
-                'open'
122
-            );
123
-        }
124
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126
-                'post_content_filtered',
127
-                esc_html__('Post Content Filtered', 'event_espresso'),
128
-                false,
129
-                ''
130
-            );
131
-        }
132
-        if (! isset($this->_model_relations['Post_Meta'])) {
133
-            // don't block deletes though because we want to maintain the current behaviour
134
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135
-        }
136
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137
-            // nothing was set during child constructor, so set default
138
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139
-        }
140
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141
-            // nothing was set during child constructor, so set default
142
-            // it's ok for child classes to specify this, but generally this is more DRY
143
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
144
-        }
145
-        parent::__construct($timezone);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return array
151
-     */
152
-    public function public_event_stati()
153
-    {
154
-        // @see wp-includes/post.php
155
-        return get_post_stati(['public' => true]);
156
-    }
157
-
158
-
159
-    /**
160
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
161
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
162
-     *
163
-     * @return string
164
-     * @throws EE_Error
165
-     */
166
-    public function deleted_field_name(): string
167
-    {
168
-        throw new EE_Error(
169
-            sprintf(
170
-                esc_html__(
171
-                    '%1$s should not call deleted_field_name()! It should instead use post_status_field_name',
172
-                    "event_espresso"
173
-                ),
174
-                get_called_class()
175
-            )
176
-        );
177
-    }
178
-
179
-
180
-    /**
181
-     * Gets the field's name that sets the post status
182
-     *
183
-     * @return string
184
-     * @throws EE_Error
185
-     */
186
-    public function post_status_field_name()
187
-    {
188
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
189
-        if ($field) {
190
-            return $field->get_name();
191
-        } else {
192
-            throw new EE_Error(
193
-                sprintf(
194
-                    esc_html__(
195
-                        'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
196
-                        'event_espresso'
197
-                    ),
198
-                    get_called_class(),
199
-                    get_called_class()
200
-                )
201
-            );
202
-        }
203
-    }
204
-
205
-
206
-    /**
207
-     * Alters the query params so that only trashed/soft-deleted items are considered
208
-     *
209
-     * @param array $query_params @see
210
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
-     * @return array @see
212
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
-     */
214
-    protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
215
-    {
216
-        $post_status_field_name                     = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
-        return $query_params;
219
-    }
220
-
221
-
222
-    /**
223
-     * Alters the query params so each item's deleted status is ignored.
224
-     *
225
-     * @param array $query_params
226
-     * @return array
227
-     */
228
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included(array $query_params): array
229
-    {
230
-        $query_params['default_where_conditions'] = 'minimum';
231
-        return $query_params;
232
-    }
233
-
234
-
235
-    /**
236
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
-     *
238
-     * @param boolean $delete true to indicate deletion, false to indicate restoration
239
-     * @param array   $query_params
240
-     * @return int
241
-     * @throws EE_Error
242
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
243
-     */
244
-    public function delete_or_restore(bool $delete = true, array $query_params = []): int
245
-    {
246
-        $post_status_field_name = $this->post_status_field_name();
247
-        $query_params           = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
-        $new_status             = $delete ? self::post_status_trashed : 'draft';
249
-        return (int) $this->update([$post_status_field_name => $new_status], $query_params);
250
-    }
251
-
252
-
253
-    /**
254
-     * meta_table
255
-     * returns first EE_Secondary_Table table name
256
-     *
257
-     * @access public
258
-     * @return string
259
-     */
260
-    public function meta_table()
261
-    {
262
-        $meta_table = $this->_get_other_tables();
263
-        $meta_table = reset($meta_table);
264
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
265
-    }
266
-
267
-
268
-    /**
269
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
270
-     *
271
-     * @param bool $all  triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
272
-     *                   db only fields)
273
-     * @return array
274
-     */
275
-    public function get_meta_table_fields($all = false)
276
-    {
277
-        $all_fields = $fields_to_return = [];
278
-        foreach ($this->_tables as $alias => $table_obj) {
279
-            if ($table_obj instanceof EE_Secondary_Table) {
280
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281
-            }
282
-        }
283
-        if (! $all) {
284
-            foreach ($all_fields as $name => $obj) {
285
-                if ($obj instanceof EE_DB_Only_Field_Base) {
286
-                    continue;
287
-                }
288
-                $fields_to_return[] = $name;
289
-            }
290
-        } else {
291
-            $fields_to_return = array_keys($all_fields);
292
-        }
293
-        return $fields_to_return;
294
-    }
295
-
296
-
297
-    /**
298
-     * Adds an event category with the specified name and description to the specified
299
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
300
-     * and adds an entry in the term_relationship if necessary.
301
-     *
302
-     * @param EE_CPT_Base $cpt_model_object
303
-     * @param string      $category_name (used to derive the term slug too)
304
-     * @param string      $category_description
305
-     * @param int         $parent_term_taxonomy_id
306
-     * @return EE_Term_Taxonomy
307
-     */
308
-    public function add_event_category(
309
-        EE_CPT_Base $cpt_model_object,
310
-        $category_name,
311
-        $category_description = '',
312
-        $parent_term_taxonomy_id = null
313
-    ) {
314
-        // create term
315
-        require_once(EE_MODELS . 'EEM_Term.model.php');
316
-        // first, check for a term by the same name or slug
317
-        $category_slug = sanitize_title($category_name);
318
-        $term          = EEM_Term::instance()->get_one(
319
-            [
320
-                [
321
-                    'OR'                     => [
322
-                        'name' => $category_name,
323
-                        'slug' => $category_slug,
324
-                    ],
325
-                    'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
326
-                ],
327
-            ]
328
-        );
329
-        if (! $term) {
330
-            $term = EE_Term::new_instance(
331
-                [
332
-                    'name' => $category_name,
333
-                    'slug' => $category_slug,
334
-                ]
335
-            );
336
-            $term->save();
337
-        }
338
-        // make sure there's a term-taxonomy entry too
339
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
340
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341
-            [
342
-                [
343
-                    'term_id'  => $term->ID(),
344
-                    'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
345
-                ],
346
-            ]
347
-        );
348
-        /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if (! $term_taxonomy) {
350
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(
351
-                [
352
-                    'term_id'     => $term->ID(),
353
-                    'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
354
-                    'description' => $category_description,
355
-                    'term_count'  => 1,
356
-                    'parent'      => $parent_term_taxonomy_id,
357
-                ]
358
-            );
359
-            $term_taxonomy->save();
360
-        } else {
361
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
362
-            $term_taxonomy->save();
363
-        }
364
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
365
-    }
366
-
367
-
368
-    /**
369
-     * Removed the category specified by name as having a relation to this event.
370
-     * Does not remove the term or term_taxonomy.
371
-     *
372
-     * @param EE_CPT_Base $cpt_model_object_event
373
-     * @param string      $category_name name of the event category (term)
374
-     * @return EE_Base_Class
375
-     */
376
-    public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
377
-    {
378
-        // find the term_taxonomy by that name
379
-        $term_taxonomy = $this->get_first_related(
380
-            $cpt_model_object_event,
381
-            'Term_Taxonomy',
382
-            [['Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY]]
383
-        );
384
-        /** @var $term_taxonomy EE_Term_Taxonomy */
385
-        if ($term_taxonomy) {
386
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
387
-            $term_taxonomy->save();
388
-        }
389
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
390
-    }
391
-
392
-
393
-    /**
394
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
395
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
396
-     *
397
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
398
-     * @access public
399
-     * @param int          $id   the ID for the cpt we want the feature image for
400
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
401
-     *                           representing width and height in pixels (i.e. array(32,32) ).
402
-     * @param string|array $attr Optional. Query string or array of attributes.
403
-     * @return string HTML image element
404
-     */
405
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
406
-    {
407
-        return get_the_post_thumbnail($id, $size, $attr);
408
-    }
409
-
410
-
411
-    /**
412
-     * Just a handy way to get the list of post statuses currently registered with WP.
413
-     *
414
-     * @return array
415
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
416
-     */
417
-    public function get_post_statuses()
418
-    {
419
-        global $wp_post_statuses;
420
-        $statuses = [];
421
-        foreach ($wp_post_statuses as $post_status => $args_object) {
422
-            $statuses[ $post_status ] = $args_object->label;
423
-        }
424
-        return $statuses;
425
-    }
426
-
427
-
428
-    /**
429
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
430
-     *
431
-     * @return array array of statuses.
432
-     */
433
-    public function get_status_array()
434
-    {
435
-        $statuses = $this->get_post_statuses();
436
-        // first the global filter
437
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438
-        // now the class specific filter
439
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
440
-        return $statuses;
441
-    }
442
-
443
-
444
-    /**
445
-     * this returns the post statuses that are NOT the default wordpress status
446
-     *
447
-     * @return array
448
-     */
449
-    public function get_custom_post_statuses()
450
-    {
451
-        $new_stati = [];
452
-        foreach ($this->_custom_stati as $status => $props) {
453
-            $new_stati[ $status ] = $props['label'];
454
-        }
455
-        return $new_stati;
456
-    }
457
-
458
-
459
-    /**
460
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
461
-     * are a row from the posts table. If we're missing any fields required for the model,
462
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
463
-     * make sure you are attaching all the model's fields onto the post)
464
-     *
465
-     * @param WP_Post|array $post
466
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
467
-     */
468
-    public function instantiate_class_from_post_object_orig($post)
469
-    {
470
-        $post                               = (array) $post;
471
-        $has_all_necessary_fields_for_table = true;
472
-        // check if the post has fields on the meta table already
473
-        foreach ($this->_get_other_tables() as $table_obj) {
474
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475
-            foreach ($fields_for_that_table as $field_obj) {
476
-                if (
477
-                    ! isset($post[ $field_obj->get_table_column() ])
478
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
479
-                ) {
480
-                    $has_all_necessary_fields_for_table = false;
481
-                }
482
-            }
483
-        }
484
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if (! $has_all_necessary_fields_for_table) {
486
-            return $this->get_one_by_ID($post['ID']);
487
-        } else {
488
-            return $this->instantiate_class_from_array_or_object($post);
489
-        }
490
-    }
491
-
492
-
493
-    /**
494
-     * @param null $post
495
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
496
-     */
497
-    public function instantiate_class_from_post_object($post = null)
498
-    {
499
-        if (empty($post)) {
500
-            global $post;
501
-        }
502
-        $post                         = (array) $post;
503
-        $tables_needing_to_be_queried = [];
504
-        // check if the post has fields on the meta table already
505
-        foreach ($this->get_tables() as $table_obj) {
506
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507
-            foreach ($fields_for_that_table as $field_obj) {
508
-                if (
509
-                    ! isset($post[ $field_obj->get_table_column() ])
510
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
511
-                ) {
512
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
513
-                }
514
-            }
515
-        }
516
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
517
-        if ($tables_needing_to_be_queried) {
518
-            if (
519
-                count($tables_needing_to_be_queried) == 1
520
-                && reset($tables_needing_to_be_queried)
521
-                   instanceof
522
-                   EE_Secondary_Table
523
-            ) {
524
-                // so we're only missing data from a secondary table. Well that's not too hard to query for
525
-                $table_to_query = reset($tables_needing_to_be_queried);
526
-                $missing_data   = $this->_do_wpdb_query(
527
-                    'get_row',
528
-                    [
529
-                        'SELECT * FROM '
530
-                        . $table_to_query->get_table_name()
531
-                        . ' WHERE '
532
-                        . $table_to_query->get_fk_on_table()
533
-                        . ' = '
534
-                        . $post['ID'],
535
-                        ARRAY_A,
536
-                    ]
537
-                );
538
-                if (! empty($missing_data)) {
539
-                    $post = array_merge($post, $missing_data);
540
-                }
541
-            } else {
542
-                return $this->get_one_by_ID($post['ID']);
543
-            }
544
-        }
545
-        return $this->instantiate_class_from_array_or_object($post);
546
-    }
547
-
548
-
549
-    /**
550
-     * Gets the post type associated with this
551
-     *
552
-     * @return string
553
-     * @throws EE_Error
554
-     */
555
-    public function post_type()
556
-    {
557
-        $post_type_field = null;
558
-        foreach ($this->field_settings(true) as $field_obj) {
559
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
560
-                $post_type_field = $field_obj;
561
-                break;
562
-            }
563
-        }
564
-        if ($post_type_field == null) {
565
-            throw new EE_Error(
566
-                sprintf(
567
-                    esc_html__(
568
-                        "CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
569
-                        "event_espresso"
570
-                    ),
571
-                    get_class($this)
572
-                )
573
-            );
574
-        }
575
-        return $post_type_field->get_default_value();
576
-    }
17
+	const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
+
19
+	/**
20
+	 * @var string post_status_publish - the wp post status for published cpts
21
+	 */
22
+	const post_status_publish = 'publish';
23
+
24
+	/**
25
+	 * @var string post_status_future - the wp post status for scheduled cpts
26
+	 */
27
+	const post_status_future = 'future';
28
+
29
+	/**
30
+	 * @var string post_status_draft - the wp post status for draft cpts
31
+	 */
32
+	const post_status_draft = 'draft';
33
+
34
+	/**
35
+	 * @var string post_status_pending - the wp post status for pending cpts
36
+	 */
37
+	const post_status_pending = 'pending';
38
+
39
+	/**
40
+	 * @var string post_status_private - the wp post status for private cpts
41
+	 */
42
+	const post_status_private = 'private';
43
+
44
+	/**
45
+	 * @var string post_status_trashed - the wp post status for trashed cpts
46
+	 */
47
+	const post_status_trashed = 'trash';
48
+
49
+	/**
50
+	 * This is an array of custom statuses for the given CPT model (modified by children)
51
+	 * format:
52
+	 * array(
53
+	 *        'status_name' => array(
54
+	 *            'label' => esc_html__('Status Name', 'event_espresso'),
55
+	 *            'public' => TRUE //whether a public status or not.
56
+	 *        )
57
+	 * )
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_custom_stati = [];
62
+
63
+
64
+	/**
65
+	 * @param string|null $timezone
66
+	 * @throws EE_Error
67
+	 */
68
+	protected function __construct(?string $timezone = '')
69
+	{
70
+		// adds a relationship to Term_Taxonomy for all these models. For this to work
71
+		// Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
72
+		// eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
73
+		// with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
74
+		// must also be new EE_HABTM_Relation('Term_Relationship');
75
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
76
+		$primary_table_name                      = null;
77
+		// add  the common _status field to all CPT primary tables.
78
+		foreach ($this->_tables as $alias => $table_obj) {
79
+			if ($table_obj instanceof EE_Primary_Table) {
80
+				$primary_table_name = $alias;
81
+			}
82
+		}
83
+		// set default wp post statuses if child has not already set.
84
+		if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
+			$this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
86
+				'post_status',
87
+				esc_html__("Event Status", "event_espresso"),
88
+				false,
89
+				'draft'
90
+			);
91
+		}
92
+		if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
+			$this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
94
+				'to_ping',
95
+				esc_html__('To Ping', 'event_espresso'),
96
+				false,
97
+				''
98
+			);
99
+		}
100
+		if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
+			$this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
102
+				'pinged',
103
+				esc_html__('Pinged', 'event_espresso'),
104
+				false,
105
+				''
106
+			);
107
+		}
108
+		if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
+			$this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
110
+				'comment_status',
111
+				esc_html__('Comment Status', 'event_espresso'),
112
+				false,
113
+				'open'
114
+			);
115
+		}
116
+		if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
+			$this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
118
+				'ping_status',
119
+				esc_html__('Ping Status', 'event_espresso'),
120
+				false,
121
+				'open'
122
+			);
123
+		}
124
+		if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
+			$this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126
+				'post_content_filtered',
127
+				esc_html__('Post Content Filtered', 'event_espresso'),
128
+				false,
129
+				''
130
+			);
131
+		}
132
+		if (! isset($this->_model_relations['Post_Meta'])) {
133
+			// don't block deletes though because we want to maintain the current behaviour
134
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135
+		}
136
+		if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137
+			// nothing was set during child constructor, so set default
138
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139
+		}
140
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141
+			// nothing was set during child constructor, so set default
142
+			// it's ok for child classes to specify this, but generally this is more DRY
143
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
144
+		}
145
+		parent::__construct($timezone);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return array
151
+	 */
152
+	public function public_event_stati()
153
+	{
154
+		// @see wp-includes/post.php
155
+		return get_post_stati(['public' => true]);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
161
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
162
+	 *
163
+	 * @return string
164
+	 * @throws EE_Error
165
+	 */
166
+	public function deleted_field_name(): string
167
+	{
168
+		throw new EE_Error(
169
+			sprintf(
170
+				esc_html__(
171
+					'%1$s should not call deleted_field_name()! It should instead use post_status_field_name',
172
+					"event_espresso"
173
+				),
174
+				get_called_class()
175
+			)
176
+		);
177
+	}
178
+
179
+
180
+	/**
181
+	 * Gets the field's name that sets the post status
182
+	 *
183
+	 * @return string
184
+	 * @throws EE_Error
185
+	 */
186
+	public function post_status_field_name()
187
+	{
188
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
189
+		if ($field) {
190
+			return $field->get_name();
191
+		} else {
192
+			throw new EE_Error(
193
+				sprintf(
194
+					esc_html__(
195
+						'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
196
+						'event_espresso'
197
+					),
198
+					get_called_class(),
199
+					get_called_class()
200
+				)
201
+			);
202
+		}
203
+	}
204
+
205
+
206
+	/**
207
+	 * Alters the query params so that only trashed/soft-deleted items are considered
208
+	 *
209
+	 * @param array $query_params @see
210
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
+	 * @return array @see
212
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
+	 */
214
+	protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
215
+	{
216
+		$post_status_field_name                     = $this->post_status_field_name();
217
+		$query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
+		return $query_params;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Alters the query params so each item's deleted status is ignored.
224
+	 *
225
+	 * @param array $query_params
226
+	 * @return array
227
+	 */
228
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included(array $query_params): array
229
+	{
230
+		$query_params['default_where_conditions'] = 'minimum';
231
+		return $query_params;
232
+	}
233
+
234
+
235
+	/**
236
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
+	 *
238
+	 * @param boolean $delete true to indicate deletion, false to indicate restoration
239
+	 * @param array   $query_params
240
+	 * @return int
241
+	 * @throws EE_Error
242
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
243
+	 */
244
+	public function delete_or_restore(bool $delete = true, array $query_params = []): int
245
+	{
246
+		$post_status_field_name = $this->post_status_field_name();
247
+		$query_params           = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
+		$new_status             = $delete ? self::post_status_trashed : 'draft';
249
+		return (int) $this->update([$post_status_field_name => $new_status], $query_params);
250
+	}
251
+
252
+
253
+	/**
254
+	 * meta_table
255
+	 * returns first EE_Secondary_Table table name
256
+	 *
257
+	 * @access public
258
+	 * @return string
259
+	 */
260
+	public function meta_table()
261
+	{
262
+		$meta_table = $this->_get_other_tables();
263
+		$meta_table = reset($meta_table);
264
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
265
+	}
266
+
267
+
268
+	/**
269
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
270
+	 *
271
+	 * @param bool $all  triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
272
+	 *                   db only fields)
273
+	 * @return array
274
+	 */
275
+	public function get_meta_table_fields($all = false)
276
+	{
277
+		$all_fields = $fields_to_return = [];
278
+		foreach ($this->_tables as $alias => $table_obj) {
279
+			if ($table_obj instanceof EE_Secondary_Table) {
280
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281
+			}
282
+		}
283
+		if (! $all) {
284
+			foreach ($all_fields as $name => $obj) {
285
+				if ($obj instanceof EE_DB_Only_Field_Base) {
286
+					continue;
287
+				}
288
+				$fields_to_return[] = $name;
289
+			}
290
+		} else {
291
+			$fields_to_return = array_keys($all_fields);
292
+		}
293
+		return $fields_to_return;
294
+	}
295
+
296
+
297
+	/**
298
+	 * Adds an event category with the specified name and description to the specified
299
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
300
+	 * and adds an entry in the term_relationship if necessary.
301
+	 *
302
+	 * @param EE_CPT_Base $cpt_model_object
303
+	 * @param string      $category_name (used to derive the term slug too)
304
+	 * @param string      $category_description
305
+	 * @param int         $parent_term_taxonomy_id
306
+	 * @return EE_Term_Taxonomy
307
+	 */
308
+	public function add_event_category(
309
+		EE_CPT_Base $cpt_model_object,
310
+		$category_name,
311
+		$category_description = '',
312
+		$parent_term_taxonomy_id = null
313
+	) {
314
+		// create term
315
+		require_once(EE_MODELS . 'EEM_Term.model.php');
316
+		// first, check for a term by the same name or slug
317
+		$category_slug = sanitize_title($category_name);
318
+		$term          = EEM_Term::instance()->get_one(
319
+			[
320
+				[
321
+					'OR'                     => [
322
+						'name' => $category_name,
323
+						'slug' => $category_slug,
324
+					],
325
+					'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
326
+				],
327
+			]
328
+		);
329
+		if (! $term) {
330
+			$term = EE_Term::new_instance(
331
+				[
332
+					'name' => $category_name,
333
+					'slug' => $category_slug,
334
+				]
335
+			);
336
+			$term->save();
337
+		}
338
+		// make sure there's a term-taxonomy entry too
339
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
340
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341
+			[
342
+				[
343
+					'term_id'  => $term->ID(),
344
+					'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
345
+				],
346
+			]
347
+		);
348
+		/** @var $term_taxonomy EE_Term_Taxonomy */
349
+		if (! $term_taxonomy) {
350
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(
351
+				[
352
+					'term_id'     => $term->ID(),
353
+					'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
354
+					'description' => $category_description,
355
+					'term_count'  => 1,
356
+					'parent'      => $parent_term_taxonomy_id,
357
+				]
358
+			);
359
+			$term_taxonomy->save();
360
+		} else {
361
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
362
+			$term_taxonomy->save();
363
+		}
364
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
365
+	}
366
+
367
+
368
+	/**
369
+	 * Removed the category specified by name as having a relation to this event.
370
+	 * Does not remove the term or term_taxonomy.
371
+	 *
372
+	 * @param EE_CPT_Base $cpt_model_object_event
373
+	 * @param string      $category_name name of the event category (term)
374
+	 * @return EE_Base_Class
375
+	 */
376
+	public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
377
+	{
378
+		// find the term_taxonomy by that name
379
+		$term_taxonomy = $this->get_first_related(
380
+			$cpt_model_object_event,
381
+			'Term_Taxonomy',
382
+			[['Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY]]
383
+		);
384
+		/** @var $term_taxonomy EE_Term_Taxonomy */
385
+		if ($term_taxonomy) {
386
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
387
+			$term_taxonomy->save();
388
+		}
389
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
390
+	}
391
+
392
+
393
+	/**
394
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
395
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
396
+	 *
397
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
398
+	 * @access public
399
+	 * @param int          $id   the ID for the cpt we want the feature image for
400
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
401
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
402
+	 * @param string|array $attr Optional. Query string or array of attributes.
403
+	 * @return string HTML image element
404
+	 */
405
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
406
+	{
407
+		return get_the_post_thumbnail($id, $size, $attr);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Just a handy way to get the list of post statuses currently registered with WP.
413
+	 *
414
+	 * @return array
415
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
416
+	 */
417
+	public function get_post_statuses()
418
+	{
419
+		global $wp_post_statuses;
420
+		$statuses = [];
421
+		foreach ($wp_post_statuses as $post_status => $args_object) {
422
+			$statuses[ $post_status ] = $args_object->label;
423
+		}
424
+		return $statuses;
425
+	}
426
+
427
+
428
+	/**
429
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
430
+	 *
431
+	 * @return array array of statuses.
432
+	 */
433
+	public function get_status_array()
434
+	{
435
+		$statuses = $this->get_post_statuses();
436
+		// first the global filter
437
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438
+		// now the class specific filter
439
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
440
+		return $statuses;
441
+	}
442
+
443
+
444
+	/**
445
+	 * this returns the post statuses that are NOT the default wordpress status
446
+	 *
447
+	 * @return array
448
+	 */
449
+	public function get_custom_post_statuses()
450
+	{
451
+		$new_stati = [];
452
+		foreach ($this->_custom_stati as $status => $props) {
453
+			$new_stati[ $status ] = $props['label'];
454
+		}
455
+		return $new_stati;
456
+	}
457
+
458
+
459
+	/**
460
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
461
+	 * are a row from the posts table. If we're missing any fields required for the model,
462
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
463
+	 * make sure you are attaching all the model's fields onto the post)
464
+	 *
465
+	 * @param WP_Post|array $post
466
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
467
+	 */
468
+	public function instantiate_class_from_post_object_orig($post)
469
+	{
470
+		$post                               = (array) $post;
471
+		$has_all_necessary_fields_for_table = true;
472
+		// check if the post has fields on the meta table already
473
+		foreach ($this->_get_other_tables() as $table_obj) {
474
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475
+			foreach ($fields_for_that_table as $field_obj) {
476
+				if (
477
+					! isset($post[ $field_obj->get_table_column() ])
478
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
479
+				) {
480
+					$has_all_necessary_fields_for_table = false;
481
+				}
482
+			}
483
+		}
484
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
485
+		if (! $has_all_necessary_fields_for_table) {
486
+			return $this->get_one_by_ID($post['ID']);
487
+		} else {
488
+			return $this->instantiate_class_from_array_or_object($post);
489
+		}
490
+	}
491
+
492
+
493
+	/**
494
+	 * @param null $post
495
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
496
+	 */
497
+	public function instantiate_class_from_post_object($post = null)
498
+	{
499
+		if (empty($post)) {
500
+			global $post;
501
+		}
502
+		$post                         = (array) $post;
503
+		$tables_needing_to_be_queried = [];
504
+		// check if the post has fields on the meta table already
505
+		foreach ($this->get_tables() as $table_obj) {
506
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507
+			foreach ($fields_for_that_table as $field_obj) {
508
+				if (
509
+					! isset($post[ $field_obj->get_table_column() ])
510
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
511
+				) {
512
+					$tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
513
+				}
514
+			}
515
+		}
516
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
517
+		if ($tables_needing_to_be_queried) {
518
+			if (
519
+				count($tables_needing_to_be_queried) == 1
520
+				&& reset($tables_needing_to_be_queried)
521
+				   instanceof
522
+				   EE_Secondary_Table
523
+			) {
524
+				// so we're only missing data from a secondary table. Well that's not too hard to query for
525
+				$table_to_query = reset($tables_needing_to_be_queried);
526
+				$missing_data   = $this->_do_wpdb_query(
527
+					'get_row',
528
+					[
529
+						'SELECT * FROM '
530
+						. $table_to_query->get_table_name()
531
+						. ' WHERE '
532
+						. $table_to_query->get_fk_on_table()
533
+						. ' = '
534
+						. $post['ID'],
535
+						ARRAY_A,
536
+					]
537
+				);
538
+				if (! empty($missing_data)) {
539
+					$post = array_merge($post, $missing_data);
540
+				}
541
+			} else {
542
+				return $this->get_one_by_ID($post['ID']);
543
+			}
544
+		}
545
+		return $this->instantiate_class_from_array_or_object($post);
546
+	}
547
+
548
+
549
+	/**
550
+	 * Gets the post type associated with this
551
+	 *
552
+	 * @return string
553
+	 * @throws EE_Error
554
+	 */
555
+	public function post_type()
556
+	{
557
+		$post_type_field = null;
558
+		foreach ($this->field_settings(true) as $field_obj) {
559
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
560
+				$post_type_field = $field_obj;
561
+				break;
562
+			}
563
+		}
564
+		if ($post_type_field == null) {
565
+			throw new EE_Error(
566
+				sprintf(
567
+					esc_html__(
568
+						"CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
569
+						"event_espresso"
570
+					),
571
+					get_class($this)
572
+				)
573
+			);
574
+		}
575
+		return $post_type_field->get_default_value();
576
+	}
577 577
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -81,63 +81,63 @@  discard block
 block discarded – undo
81 81
             }
82 82
         }
83 83
         // set default wp post statuses if child has not already set.
84
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
84
+        if ( ! isset($this->_fields[$primary_table_name]['status'])) {
85
+            $this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field(
86 86
                 'post_status',
87 87
                 esc_html__("Event Status", "event_espresso"),
88 88
                 false,
89 89
                 'draft'
90 90
             );
91 91
         }
92
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
92
+        if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
93
+            $this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field(
94 94
                 'to_ping',
95 95
                 esc_html__('To Ping', 'event_espresso'),
96 96
                 false,
97 97
                 ''
98 98
             );
99 99
         }
100
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
100
+        if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
101
+            $this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field(
102 102
                 'pinged',
103 103
                 esc_html__('Pinged', 'event_espresso'),
104 104
                 false,
105 105
                 ''
106 106
             );
107 107
         }
108
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
108
+        if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
109
+            $this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field(
110 110
                 'comment_status',
111 111
                 esc_html__('Comment Status', 'event_espresso'),
112 112
                 false,
113 113
                 'open'
114 114
             );
115 115
         }
116
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
116
+        if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
117
+            $this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field(
118 118
                 'ping_status',
119 119
                 esc_html__('Ping Status', 'event_espresso'),
120 120
                 false,
121 121
                 'open'
122 122
             );
123 123
         }
124
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
124
+        if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
125
+            $this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126 126
                 'post_content_filtered',
127 127
                 esc_html__('Post Content Filtered', 'event_espresso'),
128 128
                 false,
129 129
                 ''
130 130
             );
131 131
         }
132
-        if (! isset($this->_model_relations['Post_Meta'])) {
132
+        if ( ! isset($this->_model_relations['Post_Meta'])) {
133 133
             // don't block deletes though because we want to maintain the current behaviour
134 134
             $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135 135
         }
136
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
136
+        if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137 137
             // nothing was set during child constructor, so set default
138 138
             $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139 139
         }
140
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
140
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141 141
             // nothing was set during child constructor, so set default
142 142
             // it's ok for child classes to specify this, but generally this is more DRY
143 143
             $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
     protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
215 215
     {
216 216
         $post_status_field_name                     = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
217
+        $query_params[0][$post_status_field_name] = self::post_status_trashed;
218 218
         return $query_params;
219 219
     }
220 220
 
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
                 $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281 281
             }
282 282
         }
283
-        if (! $all) {
283
+        if ( ! $all) {
284 284
             foreach ($all_fields as $name => $obj) {
285 285
                 if ($obj instanceof EE_DB_Only_Field_Base) {
286 286
                     continue;
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
         $parent_term_taxonomy_id = null
313 313
     ) {
314 314
         // create term
315
-        require_once(EE_MODELS . 'EEM_Term.model.php');
315
+        require_once(EE_MODELS.'EEM_Term.model.php');
316 316
         // first, check for a term by the same name or slug
317 317
         $category_slug = sanitize_title($category_name);
318 318
         $term          = EEM_Term::instance()->get_one(
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
                 ],
327 327
             ]
328 328
         );
329
-        if (! $term) {
329
+        if ( ! $term) {
330 330
             $term = EE_Term::new_instance(
331 331
                 [
332 332
                     'name' => $category_name,
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
             $term->save();
337 337
         }
338 338
         // make sure there's a term-taxonomy entry too
339
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
339
+        require_once(EE_MODELS.'EEM_Term_Taxonomy.model.php');
340 340
         $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341 341
             [
342 342
                 [
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
             ]
347 347
         );
348 348
         /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if (! $term_taxonomy) {
349
+        if ( ! $term_taxonomy) {
350 350
             $term_taxonomy = EE_Term_Taxonomy::new_instance(
351 351
                 [
352 352
                     'term_id'     => $term->ID(),
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
         global $wp_post_statuses;
420 420
         $statuses = [];
421 421
         foreach ($wp_post_statuses as $post_status => $args_object) {
422
-            $statuses[ $post_status ] = $args_object->label;
422
+            $statuses[$post_status] = $args_object->label;
423 423
         }
424 424
         return $statuses;
425 425
     }
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
         // first the global filter
437 437
         $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438 438
         // now the class specific filter
439
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
439
+        $statuses = apply_filters('FHEE_EEM_'.get_class($this).'__get_status_array', $statuses);
440 440
         return $statuses;
441 441
     }
442 442
 
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
     {
451 451
         $new_stati = [];
452 452
         foreach ($this->_custom_stati as $status => $props) {
453
-            $new_stati[ $status ] = $props['label'];
453
+            $new_stati[$status] = $props['label'];
454 454
         }
455 455
         return $new_stati;
456 456
     }
@@ -474,15 +474,15 @@  discard block
 block discarded – undo
474 474
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475 475
             foreach ($fields_for_that_table as $field_obj) {
476 476
                 if (
477
-                    ! isset($post[ $field_obj->get_table_column() ])
478
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
477
+                    ! isset($post[$field_obj->get_table_column()])
478
+                    && ! isset($post[$field_obj->get_qualified_column()])
479 479
                 ) {
480 480
                     $has_all_necessary_fields_for_table = false;
481 481
                 }
482 482
             }
483 483
         }
484 484
         // if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if (! $has_all_necessary_fields_for_table) {
485
+        if ( ! $has_all_necessary_fields_for_table) {
486 486
             return $this->get_one_by_ID($post['ID']);
487 487
         } else {
488 488
             return $this->instantiate_class_from_array_or_object($post);
@@ -506,10 +506,10 @@  discard block
 block discarded – undo
506 506
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507 507
             foreach ($fields_for_that_table as $field_obj) {
508 508
                 if (
509
-                    ! isset($post[ $field_obj->get_table_column() ])
510
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
509
+                    ! isset($post[$field_obj->get_table_column()])
510
+                    && ! isset($post[$field_obj->get_qualified_column()])
511 511
                 ) {
512
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
512
+                    $tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
513 513
                 }
514 514
             }
515 515
         }
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
                         ARRAY_A,
536 536
                     ]
537 537
                 );
538
-                if (! empty($missing_data)) {
538
+                if ( ! empty($missing_data)) {
539 539
                     $post = array_merge($post, $missing_data);
540 540
                 }
541 541
             } else {
Please login to merge, or discard this patch.
core/db_models/EEM_Soft_Delete_Base.model.php 2 patches
Indentation   +389 added lines, -389 removed lines patch added patch discarded remove patch
@@ -28,393 +28,393 @@
 block discarded – undo
28 28
  */
29 29
 abstract class EEM_Soft_Delete_Base extends EEM_Base
30 30
 {
31
-    /**
32
-     * @param string|null $timezone
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct(?string $timezone = '')
36
-    {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
-            $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
-        }
40
-        parent::__construct($timezone);
41
-    }
42
-
43
-
44
-    /**
45
-     * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
-     *
47
-     * @return string
48
-     * @throws EE_Error
49
-     */
50
-    public function deleted_field_name(): string
51
-    {
52
-        $field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
-        if ($field) {
54
-            return $field->get_name();
55
-        }
56
-
57
-        throw new EE_Error(
58
-            sprintf(
59
-                esc_html__(
60
-                    'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
61
-                    'event_espresso'
62
-                ),
63
-                get_class($this),
64
-                get_class($this)
65
-            )
66
-        );
67
-    }
68
-
69
-
70
-    /**
71
-     * Gets one item that's been deleted, according to $query_params
72
-     *
73
-     * @param array $query_params
74
-     * @return EE_Soft_Delete_Base_Class|null
75
-     * @throws EE_Error
76
-     * @throws ReflectionException
77
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
78
-     */
79
-    public function get_one_deleted(array $query_params = []): ?EE_Soft_Delete_Base_Class
80
-    {
81
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
82
-        return $this->get_one($query_params);
83
-    }
84
-
85
-
86
-    /**
87
-     * Gets one item from the DB, regardless of whether it's been soft-deleted or not
88
-     *
89
-     * @param array $query_params like EEM_base::get_all's $query_params
90
-     * @return EE_Soft_Delete_Base_Class|null
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function get_one_deleted_or_undeleted(array $query_params = []): ?EE_Soft_Delete_Base_Class
95
-    {
96
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
97
-        return $this->get_one($query_params);
98
-    }
99
-
100
-
101
-    /**
102
-     * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
103
-     *
104
-     * @param int|string $id
105
-     * @return EE_Soft_Delete_Base_Class|null
106
-     * @throws EE_Error
107
-     * @throws ReflectionException
108
-     */
109
-    public function get_one_by_ID_but_ignore_deleted($id): ?EE_Soft_Delete_Base_Class
110
-    {
111
-        return $this->get_one(
112
-            $this->alter_query_params_to_restrict_by_ID(
113
-                $id,
114
-                ['default_where_conditions' => 'default']
115
-            )
116
-        );
117
-    }
118
-
119
-
120
-    /**
121
-     * Counts all the deleted/trashed items
122
-     *
123
-     * @param array  $query_params
124
-     * @param string $field_to_count
125
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
126
-     *                             that by the setting $distinct to TRUE;
127
-     * @return int
128
-     * @throws EE_Error
129
-     * @throws ReflectionException
130
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
131
-     */
132
-    public function count_deleted(array $query_params = [], string $field_to_count = '', bool $distinct = false): int
133
-    {
134
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
135
-        return $this->count($query_params, $field_to_count, $distinct);
136
-    }
137
-
138
-
139
-    /**
140
-     * Alters the query params so that only trashed/soft-deleted items are considered
141
-     *
142
-     * @param array $query_params
143
-     * @return array
144
-     * @throws EE_Error
145
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
146
-     */
147
-    protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
148
-    {
149
-        $deletedFlagFieldName                     = $this->deleted_field_name();
150
-        $query_params[0][ $deletedFlagFieldName ] = true;
151
-        return $query_params;
152
-    }
153
-
154
-
155
-    /**
156
-     * Alters the query params so that only trashed/soft-deleted items are considered
157
-     *
158
-     * @param array $query_params
159
-     * @return array
160
-     * @throws EE_Error
161
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
162
-     */
163
-    public function alter_query_params_so_only_trashed_items_included(array $query_params): array
164
-    {
165
-        return $this->_alter_query_params_so_only_trashed_items_included($query_params);
166
-    }
167
-
168
-
169
-    /**
170
-     * Alters the query params so each item's deleted status is ignored.
171
-     *
172
-     * @param array $query_params
173
-     * @return array
174
-     */
175
-    public function alter_query_params_so_deleted_and_undeleted_items_included(array $query_params = []): array
176
-    {
177
-        return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
178
-    }
179
-
180
-
181
-    /**
182
-     * Alters the query params so each item's deleted status is ignored.
183
-     *
184
-     * @param array $query_params
185
-     * @return array
186
-     */
187
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included(array $query_params): array
188
-    {
189
-        if (! isset($query_params['default_where_conditions'])) {
190
-            $query_params['default_where_conditions'] = 'minimum';
191
-        }
192
-        return $query_params;
193
-    }
194
-
195
-
196
-    /**
197
-     * Counts all deleted and undeleted items
198
-     *
199
-     * @param array  $query_params
200
-     * @param string $field_to_count
201
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
202
-     *                             that by the setting $distinct to TRUE;
203
-     * @return int
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
207
-     */
208
-    public function count_deleted_and_undeleted(
209
-        array $query_params = [],
210
-        string $field_to_count = '',
211
-        bool $distinct = false
212
-    ): int {
213
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
214
-        return $this->count($query_params, $field_to_count, $distinct);
215
-    }
216
-
217
-
218
-    /**
219
-     * Sum all the deleted items.
220
-     *
221
-     * @param array  $query_params
222
-     * @param string $field_to_sum
223
-     * @return float
224
-     * @throws EE_Error
225
-     * @throws ReflectionException
226
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
227
-     */
228
-    public function sum_deleted(array $query_params = [], string $field_to_sum = ''): float
229
-    {
230
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
231
-        return $this->sum($query_params, $field_to_sum);
232
-    }
233
-
234
-
235
-    /**
236
-     * Sums all the deleted and undeleted items.
237
-     *
238
-     * @param array  $query_params
239
-     * @param string $field_to_sum
240
-     * @return float
241
-     * @throws EE_Error
242
-     * @throws ReflectionException
243
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
244
-     */
245
-    public function sum_deleted_and_undeleted(array $query_params = [], string $field_to_sum = ''): float
246
-    {
247
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
-        return $this->sum($query_params, $field_to_sum);
249
-    }
250
-
251
-
252
-    /**
253
-     * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
254
-     * whether they've been soft-deleted or not
255
-     *
256
-     * @param array $query_params
257
-     * @return EE_Soft_Delete_Base_Class[]
258
-     * @throws EE_Error
259
-     * @throws ReflectionException
260
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
261
-     */
262
-    public function get_all_deleted_and_undeleted(array $query_params = []): array
263
-    {
264
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
265
-        return $this->get_all($query_params);
266
-    }
267
-
268
-
269
-    /**
270
-     * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
271
-     *
272
-     * @param array $query_params
273
-     * @return EE_Soft_Delete_Base_Class[]
274
-     * @throws EE_Error
275
-     * @throws ReflectionException
276
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
277
-     */
278
-    public function get_all_deleted(array $query_params = []): array
279
-    {
280
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
281
-        return $this->get_all($query_params);
282
-    }
283
-
284
-
285
-    /**
286
-     * Permanently deletes the selected rows.
287
-     * When selecting rows for deletion, ignores whether they've been soft-deleted or not.
288
-     * (ie, you don't have to soft-delete objects before you can permanently delete them).
289
-     * Because this will cause a real deletion, related models may block this deletion
290
-     * (ie, add an error and abort the delete process)
291
-     *
292
-     * @param array   $query_params
293
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
294
-     *                                that blocks it (ie, there' sno other data that depends on this data);
295
-     *                                if false, deletes regardless of other objects which may depend on it.
296
-     *                                It's generally advisable to always leave this as TRUE,
297
-     *                                otherwise you could easily corrupt your DB
298
-     * @return int                    number of rows deleted
299
-     * @throws EE_Error
300
-     * @throws ReflectionException
301
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
302
-     */
303
-    public function delete_permanently($query_params, $allow_blocking = true): int
304
-    {
305
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
306
-        return parent::delete_permanently($query_params, $allow_blocking);
307
-    }
308
-
309
-
310
-    /**
311
-     * Restores a particular item by its ID (primary key). Ignores the fact whether the item
312
-     * has been soft-deleted or not.
313
-     *
314
-     * @param mixed $ID int if primary key is an int, string otherwise
315
-     * @return int success
316
-     * @throws EE_Error
317
-     * @throws ReflectionException
318
-     */
319
-    public function restore_by_ID($ID = false): int
320
-    {
321
-        return $this->delete_or_restore_by_ID(false, $ID);
322
-    }
323
-
324
-
325
-    /**
326
-     * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
327
-     * this function will ignore whether the items have been soft-deleted or not.
328
-     *
329
-     * @param boolean    $delete true for delete, false for restore
330
-     * @param int|string $ID     int if primary key is an int, string otherwise
331
-     * @return int
332
-     * @throws EE_Error
333
-     * @throws ReflectionException
334
-     */
335
-    public function delete_or_restore_by_ID(bool $delete = true, $ID = 0): int
336
-    {
337
-        // returns false if entity doesn't have an ID or if delete/restore action failed
338
-        return $ID ? $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID)) : 0;
339
-    }
340
-
341
-
342
-    /**
343
-     * Overrides parent's 'delete' method to instead do a soft delete on all rows that
344
-     * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
345
-     * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
346
-     * dependencies
347
-     *
348
-     * @param array $query_params
349
-     * @param bool  $block_deletes
350
-     * @return int
351
-     * @throws EE_Error
352
-     * @throws ReflectionException
353
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
354
-     */
355
-    public function delete($query_params = [], $block_deletes = false): int
356
-    {
357
-        // no matter what, we WON'T block soft deletes.
358
-        return $this->delete_or_restore(true, $query_params);
359
-    }
360
-
361
-
362
-    /**
363
-     * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
364
-     * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
365
-     * have been soft-deleted or not.
366
-     *
367
-     * @param array $query_params
368
-     * @return int
369
-     * @throws EE_Error
370
-     * @throws ReflectionException
371
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
372
-     */
373
-    public function restore(array $query_params = []): int
374
-    {
375
-        return $this->delete_or_restore(false, $query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
381
-     *
382
-     * @param boolean $delete true to indicate deletion, false to indicate restoration
383
-     * @param array   $query_params
384
-     * @return int
385
-     * @throws EE_Error
386
-     * @throws ReflectionException
387
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
388
-     */
389
-    public function delete_or_restore(bool $delete = true, array $query_params = []): int
390
-    {
391
-        $deletedFlagFieldName = $this->deleted_field_name();
392
-        $query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
393
-        return (int) $this->update([$deletedFlagFieldName => $delete], $query_params);
394
-    }
395
-
396
-
397
-    /**
398
-     * Updates all the items of this model which match the $query params, regardless of whether
399
-     * they've been soft-deleted or not
400
-     *
401
-     * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
402
-     * @param array   $query_params            like EEM_base::get_all's $query_params
403
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
404
-     *                                         in this model's entity map according to $fields_n_values that match
405
-     *                                         $query_params. This obviously has some overhead, so you can disable it
406
-     *                                         by setting this to FALSE, but be aware that model objects being used
407
-     *                                         could get out-of-sync with the database
408
-     * @return int number of items updated
409
-     * @throws EE_Error
410
-     * @throws ReflectionException
411
-     */
412
-    public function update_deleted_and_undeleted(
413
-        array $fields_n_values,
414
-        array $query_params,
415
-        bool $keep_model_objs_in_sync = true
416
-    ): int {
417
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
418
-        return (int) $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
419
-    }
31
+	/**
32
+	 * @param string|null $timezone
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct(?string $timezone = '')
36
+	{
37
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
+			$this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
+		}
40
+		parent::__construct($timezone);
41
+	}
42
+
43
+
44
+	/**
45
+	 * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
+	 *
47
+	 * @return string
48
+	 * @throws EE_Error
49
+	 */
50
+	public function deleted_field_name(): string
51
+	{
52
+		$field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
+		if ($field) {
54
+			return $field->get_name();
55
+		}
56
+
57
+		throw new EE_Error(
58
+			sprintf(
59
+				esc_html__(
60
+					'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
61
+					'event_espresso'
62
+				),
63
+				get_class($this),
64
+				get_class($this)
65
+			)
66
+		);
67
+	}
68
+
69
+
70
+	/**
71
+	 * Gets one item that's been deleted, according to $query_params
72
+	 *
73
+	 * @param array $query_params
74
+	 * @return EE_Soft_Delete_Base_Class|null
75
+	 * @throws EE_Error
76
+	 * @throws ReflectionException
77
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
78
+	 */
79
+	public function get_one_deleted(array $query_params = []): ?EE_Soft_Delete_Base_Class
80
+	{
81
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
82
+		return $this->get_one($query_params);
83
+	}
84
+
85
+
86
+	/**
87
+	 * Gets one item from the DB, regardless of whether it's been soft-deleted or not
88
+	 *
89
+	 * @param array $query_params like EEM_base::get_all's $query_params
90
+	 * @return EE_Soft_Delete_Base_Class|null
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function get_one_deleted_or_undeleted(array $query_params = []): ?EE_Soft_Delete_Base_Class
95
+	{
96
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
97
+		return $this->get_one($query_params);
98
+	}
99
+
100
+
101
+	/**
102
+	 * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
103
+	 *
104
+	 * @param int|string $id
105
+	 * @return EE_Soft_Delete_Base_Class|null
106
+	 * @throws EE_Error
107
+	 * @throws ReflectionException
108
+	 */
109
+	public function get_one_by_ID_but_ignore_deleted($id): ?EE_Soft_Delete_Base_Class
110
+	{
111
+		return $this->get_one(
112
+			$this->alter_query_params_to_restrict_by_ID(
113
+				$id,
114
+				['default_where_conditions' => 'default']
115
+			)
116
+		);
117
+	}
118
+
119
+
120
+	/**
121
+	 * Counts all the deleted/trashed items
122
+	 *
123
+	 * @param array  $query_params
124
+	 * @param string $field_to_count
125
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
126
+	 *                             that by the setting $distinct to TRUE;
127
+	 * @return int
128
+	 * @throws EE_Error
129
+	 * @throws ReflectionException
130
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
131
+	 */
132
+	public function count_deleted(array $query_params = [], string $field_to_count = '', bool $distinct = false): int
133
+	{
134
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
135
+		return $this->count($query_params, $field_to_count, $distinct);
136
+	}
137
+
138
+
139
+	/**
140
+	 * Alters the query params so that only trashed/soft-deleted items are considered
141
+	 *
142
+	 * @param array $query_params
143
+	 * @return array
144
+	 * @throws EE_Error
145
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
146
+	 */
147
+	protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
148
+	{
149
+		$deletedFlagFieldName                     = $this->deleted_field_name();
150
+		$query_params[0][ $deletedFlagFieldName ] = true;
151
+		return $query_params;
152
+	}
153
+
154
+
155
+	/**
156
+	 * Alters the query params so that only trashed/soft-deleted items are considered
157
+	 *
158
+	 * @param array $query_params
159
+	 * @return array
160
+	 * @throws EE_Error
161
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
162
+	 */
163
+	public function alter_query_params_so_only_trashed_items_included(array $query_params): array
164
+	{
165
+		return $this->_alter_query_params_so_only_trashed_items_included($query_params);
166
+	}
167
+
168
+
169
+	/**
170
+	 * Alters the query params so each item's deleted status is ignored.
171
+	 *
172
+	 * @param array $query_params
173
+	 * @return array
174
+	 */
175
+	public function alter_query_params_so_deleted_and_undeleted_items_included(array $query_params = []): array
176
+	{
177
+		return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
178
+	}
179
+
180
+
181
+	/**
182
+	 * Alters the query params so each item's deleted status is ignored.
183
+	 *
184
+	 * @param array $query_params
185
+	 * @return array
186
+	 */
187
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included(array $query_params): array
188
+	{
189
+		if (! isset($query_params['default_where_conditions'])) {
190
+			$query_params['default_where_conditions'] = 'minimum';
191
+		}
192
+		return $query_params;
193
+	}
194
+
195
+
196
+	/**
197
+	 * Counts all deleted and undeleted items
198
+	 *
199
+	 * @param array  $query_params
200
+	 * @param string $field_to_count
201
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
202
+	 *                             that by the setting $distinct to TRUE;
203
+	 * @return int
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
207
+	 */
208
+	public function count_deleted_and_undeleted(
209
+		array $query_params = [],
210
+		string $field_to_count = '',
211
+		bool $distinct = false
212
+	): int {
213
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
214
+		return $this->count($query_params, $field_to_count, $distinct);
215
+	}
216
+
217
+
218
+	/**
219
+	 * Sum all the deleted items.
220
+	 *
221
+	 * @param array  $query_params
222
+	 * @param string $field_to_sum
223
+	 * @return float
224
+	 * @throws EE_Error
225
+	 * @throws ReflectionException
226
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
227
+	 */
228
+	public function sum_deleted(array $query_params = [], string $field_to_sum = ''): float
229
+	{
230
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
231
+		return $this->sum($query_params, $field_to_sum);
232
+	}
233
+
234
+
235
+	/**
236
+	 * Sums all the deleted and undeleted items.
237
+	 *
238
+	 * @param array  $query_params
239
+	 * @param string $field_to_sum
240
+	 * @return float
241
+	 * @throws EE_Error
242
+	 * @throws ReflectionException
243
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
244
+	 */
245
+	public function sum_deleted_and_undeleted(array $query_params = [], string $field_to_sum = ''): float
246
+	{
247
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
+		return $this->sum($query_params, $field_to_sum);
249
+	}
250
+
251
+
252
+	/**
253
+	 * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
254
+	 * whether they've been soft-deleted or not
255
+	 *
256
+	 * @param array $query_params
257
+	 * @return EE_Soft_Delete_Base_Class[]
258
+	 * @throws EE_Error
259
+	 * @throws ReflectionException
260
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
261
+	 */
262
+	public function get_all_deleted_and_undeleted(array $query_params = []): array
263
+	{
264
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
265
+		return $this->get_all($query_params);
266
+	}
267
+
268
+
269
+	/**
270
+	 * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
271
+	 *
272
+	 * @param array $query_params
273
+	 * @return EE_Soft_Delete_Base_Class[]
274
+	 * @throws EE_Error
275
+	 * @throws ReflectionException
276
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
277
+	 */
278
+	public function get_all_deleted(array $query_params = []): array
279
+	{
280
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
281
+		return $this->get_all($query_params);
282
+	}
283
+
284
+
285
+	/**
286
+	 * Permanently deletes the selected rows.
287
+	 * When selecting rows for deletion, ignores whether they've been soft-deleted or not.
288
+	 * (ie, you don't have to soft-delete objects before you can permanently delete them).
289
+	 * Because this will cause a real deletion, related models may block this deletion
290
+	 * (ie, add an error and abort the delete process)
291
+	 *
292
+	 * @param array   $query_params
293
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
294
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
295
+	 *                                if false, deletes regardless of other objects which may depend on it.
296
+	 *                                It's generally advisable to always leave this as TRUE,
297
+	 *                                otherwise you could easily corrupt your DB
298
+	 * @return int                    number of rows deleted
299
+	 * @throws EE_Error
300
+	 * @throws ReflectionException
301
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
302
+	 */
303
+	public function delete_permanently($query_params, $allow_blocking = true): int
304
+	{
305
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
306
+		return parent::delete_permanently($query_params, $allow_blocking);
307
+	}
308
+
309
+
310
+	/**
311
+	 * Restores a particular item by its ID (primary key). Ignores the fact whether the item
312
+	 * has been soft-deleted or not.
313
+	 *
314
+	 * @param mixed $ID int if primary key is an int, string otherwise
315
+	 * @return int success
316
+	 * @throws EE_Error
317
+	 * @throws ReflectionException
318
+	 */
319
+	public function restore_by_ID($ID = false): int
320
+	{
321
+		return $this->delete_or_restore_by_ID(false, $ID);
322
+	}
323
+
324
+
325
+	/**
326
+	 * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
327
+	 * this function will ignore whether the items have been soft-deleted or not.
328
+	 *
329
+	 * @param boolean    $delete true for delete, false for restore
330
+	 * @param int|string $ID     int if primary key is an int, string otherwise
331
+	 * @return int
332
+	 * @throws EE_Error
333
+	 * @throws ReflectionException
334
+	 */
335
+	public function delete_or_restore_by_ID(bool $delete = true, $ID = 0): int
336
+	{
337
+		// returns false if entity doesn't have an ID or if delete/restore action failed
338
+		return $ID ? $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID)) : 0;
339
+	}
340
+
341
+
342
+	/**
343
+	 * Overrides parent's 'delete' method to instead do a soft delete on all rows that
344
+	 * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
345
+	 * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
346
+	 * dependencies
347
+	 *
348
+	 * @param array $query_params
349
+	 * @param bool  $block_deletes
350
+	 * @return int
351
+	 * @throws EE_Error
352
+	 * @throws ReflectionException
353
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
354
+	 */
355
+	public function delete($query_params = [], $block_deletes = false): int
356
+	{
357
+		// no matter what, we WON'T block soft deletes.
358
+		return $this->delete_or_restore(true, $query_params);
359
+	}
360
+
361
+
362
+	/**
363
+	 * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
364
+	 * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
365
+	 * have been soft-deleted or not.
366
+	 *
367
+	 * @param array $query_params
368
+	 * @return int
369
+	 * @throws EE_Error
370
+	 * @throws ReflectionException
371
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
372
+	 */
373
+	public function restore(array $query_params = []): int
374
+	{
375
+		return $this->delete_or_restore(false, $query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
381
+	 *
382
+	 * @param boolean $delete true to indicate deletion, false to indicate restoration
383
+	 * @param array   $query_params
384
+	 * @return int
385
+	 * @throws EE_Error
386
+	 * @throws ReflectionException
387
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
388
+	 */
389
+	public function delete_or_restore(bool $delete = true, array $query_params = []): int
390
+	{
391
+		$deletedFlagFieldName = $this->deleted_field_name();
392
+		$query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
393
+		return (int) $this->update([$deletedFlagFieldName => $delete], $query_params);
394
+	}
395
+
396
+
397
+	/**
398
+	 * Updates all the items of this model which match the $query params, regardless of whether
399
+	 * they've been soft-deleted or not
400
+	 *
401
+	 * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
402
+	 * @param array   $query_params            like EEM_base::get_all's $query_params
403
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
404
+	 *                                         in this model's entity map according to $fields_n_values that match
405
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
406
+	 *                                         by setting this to FALSE, but be aware that model objects being used
407
+	 *                                         could get out-of-sync with the database
408
+	 * @return int number of items updated
409
+	 * @throws EE_Error
410
+	 * @throws ReflectionException
411
+	 */
412
+	public function update_deleted_and_undeleted(
413
+		array $fields_n_values,
414
+		array $query_params,
415
+		bool $keep_model_objs_in_sync = true
416
+	): int {
417
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
418
+		return (int) $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
419
+	}
420 420
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
      */
35 35
     protected function __construct(?string $timezone = '')
36 36
     {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
37
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38 38
             $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39 39
         }
40 40
         parent::__construct($timezone);
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
     protected function _alter_query_params_so_only_trashed_items_included(array $query_params): array
148 148
     {
149 149
         $deletedFlagFieldName                     = $this->deleted_field_name();
150
-        $query_params[0][ $deletedFlagFieldName ] = true;
150
+        $query_params[0][$deletedFlagFieldName] = true;
151 151
         return $query_params;
152 152
     }
153 153
 
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
      */
187 187
     protected function _alter_query_params_so_deleted_and_undeleted_items_included(array $query_params): array
188 188
     {
189
-        if (! isset($query_params['default_where_conditions'])) {
189
+        if ( ! isset($query_params['default_where_conditions'])) {
190 190
             $query_params['default_where_conditions'] = 'minimum';
191 191
         }
192 192
         return $query_params;
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6687 added lines, -6687 removed lines patch added patch discarded remove patch
@@ -39,6696 +39,6696 @@
 block discarded – undo
39 39
  */
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42
-    /**
43
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
-     * They almost always WILL NOT, but it's not necessarily a requirement.
46
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
-     *
48
-     * @var boolean
49
-     */
50
-    private $_values_already_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we assume
54
-     * the data is just like form input that needs to have the model fields'
55
-     * prepare_for_set and prepare_for_use_in_db called on it
56
-     */
57
-    const not_prepared_by_model_object = 0;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we
61
-     * assume this value is coming from a model object and doesn't need to have
62
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
63
-     */
64
-    const prepared_by_model_object = 1;
65
-
66
-    /**
67
-     * when $_values_already_prepared_by_model_object equals this, we assume
68
-     * the values are already to be used in the database (ie no processing is done
69
-     * on them by the model's fields)
70
-     */
71
-    const prepared_for_use_in_db = 2;
72
-
73
-
74
-    protected $singular_item = 'Item';
75
-
76
-    protected $plural_item   = 'Items';
77
-
78
-    /**
79
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
-     */
81
-    protected $_tables;
82
-
83
-    /**
84
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
-     *
88
-     * @var EE_Model_Field_Base[][] $_fields
89
-     */
90
-    protected $_fields;
91
-
92
-    /**
93
-     * array of different kinds of relations
94
-     *
95
-     * @var EE_Model_Relation_Base[] $_model_relations
96
-     */
97
-    protected $_model_relations = [];
98
-
99
-    /**
100
-     * @var EE_Index[] $_indexes
101
-     */
102
-    protected $_indexes = [];
103
-
104
-    /**
105
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
106
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
-     * by setting the same columns as used in these queries in the query yourself.
108
-     *
109
-     * @var EE_Default_Where_Conditions
110
-     */
111
-    protected $_default_where_conditions_strategy;
112
-
113
-    /**
114
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
-     * This is particularly useful when you want something between 'none' and 'default'
116
-     *
117
-     * @var EE_Default_Where_Conditions
118
-     */
119
-    protected $_minimum_where_conditions_strategy;
120
-
121
-    /**
122
-     * String describing how to find the "owner" of this model's objects.
123
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
-     * But when there isn't, this indicates which related model, or transiently-related model,
125
-     * has the foreign key to the wp_users table.
126
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
-     * related to events, and events have a foreign key to wp_users.
128
-     * On EEM_Transaction, this would be 'Transaction.Event'
129
-     *
130
-     * @var string
131
-     */
132
-    protected $_model_chain_to_wp_user = '';
133
-
134
-    /**
135
-     * String describing how to find the model with a password controlling access to this model. This property has the
136
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
-     * This value is the path of models to follow to arrive at the model with the password field.
138
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
-     * model with a password that should affect reading this on the front-end.
140
-     * Eg this is an empty string for the Event model because it has a password.
141
-     * This is null for the Registration model, because its event's password has no bearing on whether
142
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
-     * should hide tickets for datetimes for events that have a password set.
145
-     *
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = [
178
-        self::caps_read       => [],
179
-        self::caps_read_admin => [],
180
-        self::caps_edit       => [],
181
-        self::caps_delete     => [],
182
-    ];
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = [];
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in the capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = [
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    ];
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = [];
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     *
298
-     * @var boolean
299
-     */
300
-    protected $_wp_core_model = false;
301
-
302
-    /**
303
-     * @var bool stores whether this model has a password field or not.
304
-     * null until initialized by hasPasswordField()
305
-     */
306
-    protected $has_password_field;
307
-
308
-    /**
309
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
-     */
311
-    protected $password_field;
312
-
313
-    /**
314
-     *    List of valid operators that can be used for querying.
315
-     * The keys are all operators we'll accept, the values are the real SQL
316
-     * operators used
317
-     *
318
-     * @var array
319
-     */
320
-    protected $_valid_operators = [
321
-        '='           => '=',
322
-        '<='          => '<=',
323
-        '<'           => '<',
324
-        '>='          => '>=',
325
-        '>'           => '>',
326
-        '!='          => '!=',
327
-        'LIKE'        => 'LIKE',
328
-        'like'        => 'LIKE',
329
-        'NOT_LIKE'    => 'NOT LIKE',
330
-        'not_like'    => 'NOT LIKE',
331
-        'NOT LIKE'    => 'NOT LIKE',
332
-        'not like'    => 'NOT LIKE',
333
-        'IN'          => 'IN',
334
-        'in'          => 'IN',
335
-        'NOT_IN'      => 'NOT IN',
336
-        'not_in'      => 'NOT IN',
337
-        'NOT IN'      => 'NOT IN',
338
-        'not in'      => 'NOT IN',
339
-        'between'     => 'BETWEEN',
340
-        'BETWEEN'     => 'BETWEEN',
341
-        'IS_NOT_NULL' => 'IS NOT NULL',
342
-        'is_not_null' => 'IS NOT NULL',
343
-        'IS NOT NULL' => 'IS NOT NULL',
344
-        'is not null' => 'IS NOT NULL',
345
-        'IS_NULL'     => 'IS NULL',
346
-        'is_null'     => 'IS NULL',
347
-        'IS NULL'     => 'IS NULL',
348
-        'is null'     => 'IS NULL',
349
-        'REGEXP'      => 'REGEXP',
350
-        'regexp'      => 'REGEXP',
351
-        'NOT_REGEXP'  => 'NOT REGEXP',
352
-        'not_regexp'  => 'NOT REGEXP',
353
-        'NOT REGEXP'  => 'NOT REGEXP',
354
-        'not regexp'  => 'NOT REGEXP',
355
-    ];
356
-
357
-    /**
358
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
-     *
360
-     * @var array
361
-     */
362
-    protected $_in_style_operators = ['IN', 'NOT IN'];
363
-
364
-    /**
365
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
-     * '12-31-2012'"
367
-     *
368
-     * @var array
369
-     */
370
-    protected $_between_style_operators = ['BETWEEN'];
371
-
372
-    /**
373
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
-
379
-    /**
380
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
-     * on a join table.
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
-
387
-    /**
388
-     * Allowed values for $query_params['order'] for ordering in queries
389
-     *
390
-     * @var array
391
-     */
392
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
-
394
-    /**
395
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
397
-     *
398
-     * @var array
399
-     */
400
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
-
402
-    /**
403
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
405
-     *
406
-     * @var array
407
-     */
408
-    private $_allowed_query_params = [
409
-        0,
410
-        'limit',
411
-        'order_by',
412
-        'group_by',
413
-        'having',
414
-        'force_join',
415
-        'order',
416
-        'on_join_limit',
417
-        'default_where_conditions',
418
-        'caps',
419
-        'extra_selects',
420
-        'exclude_protected',
421
-    ];
422
-
423
-    /**
424
-     * All the data types that can be used in $wpdb->prepare statements.
425
-     *
426
-     * @var array
427
-     */
428
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
-
430
-    /**
431
-     * @var EE_Registry $EE
432
-     */
433
-    protected $EE = null;
434
-
435
-
436
-    /**
437
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
-     *
439
-     * @var int
440
-     */
441
-    protected $_show_next_x_db_queries = 0;
442
-
443
-    /**
444
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
-     * WHERE, GROUP_BY, etc.
447
-     *
448
-     * @var CustomSelects
449
-     */
450
-    protected $_custom_selections = [];
451
-
452
-    /**
453
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
-     * caches every model object we've fetched from the DB on this request
455
-     *
456
-     * @var array
457
-     */
458
-    protected $_entity_map;
459
-
460
-    /**
461
-     * @var LoaderInterface
462
-     */
463
-    protected static $loader;
464
-
465
-    /**
466
-     * @var Mirror
467
-     */
468
-    private static $mirror;
469
-
470
-
471
-    /**
472
-     * constant used to show EEM_Base has not yet verified the db on this http request
473
-     */
474
-    const db_verified_none = 0;
475
-
476
-    /**
477
-     * constant used to show EEM_Base has verified the EE core db on this http request,
478
-     * but not the addons' dbs
479
-     */
480
-    const db_verified_core = 1;
481
-
482
-    /**
483
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
-     * the EE core db too)
485
-     */
486
-    const db_verified_addons = 2;
487
-
488
-    /**
489
-     * indicates whether an EEM_Base child has already re-verified the DB
490
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
491
-     * looking like EEM_Base::db_verified_*
492
-     *
493
-     * @var int - 0 = none, 1 = core, 2 = addons
494
-     */
495
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
496
-
497
-    /**
498
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
-     *        registrations for non-trashed tickets for non-trashed datetimes)
501
-     */
502
-    const default_where_conditions_all = 'all';
503
-
504
-    /**
505
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
-     *        models which share tables with other models, this can return data for the wrong model.
510
-     */
511
-    const default_where_conditions_this_only = 'this_model_only';
512
-
513
-    /**
514
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
-     */
518
-    const default_where_conditions_others_only = 'other_models_only';
519
-
520
-    /**
521
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
524
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
-     *        (regardless of whether those events and venues are trashed)
526
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
-     *        events.
528
-     */
529
-    const default_where_conditions_minimum_all = 'minimum';
530
-
531
-    /**
532
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
-     *        not)
536
-     */
537
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
-
539
-    /**
540
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
-     *        it's possible it will return table entries for other models. You should use
543
-     *        EEM_Base::default_where_conditions_minimum_all instead.
544
-     */
545
-    const default_where_conditions_none = 'none';
546
-
547
-
548
-    /**
549
-     * About all child constructors:
550
-     * they should define the _tables, _fields and _model_relations arrays.
551
-     * Should ALWAYS be called after child constructor.
552
-     * In order to make the child constructors to be as simple as possible, this parent constructor
553
-     * finalizes constructing all the object's attributes.
554
-     * Generally, rather than requiring a child to code
555
-     * $this->_tables = array(
556
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
-     *        ...);
558
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
-     * each EE_Table has a function to set the table's alias after the constructor, using
560
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
-     * do something similar.
562
-     *
563
-     * @param string|null $timezone
564
-     * @throws EE_Error
565
-     * @throws Exception
566
-     */
567
-    protected function __construct($timezone = '')
568
-    {
569
-        // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
-            throw new EE_Error(
572
-                sprintf(
573
-                    esc_html__(
574
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
-                        'event_espresso'
576
-                    ),
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        /**
582
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
-         */
584
-        if (empty(EEM_Base::$_model_query_blog_id)) {
585
-            EEM_Base::set_model_query_blog_id();
586
-        }
587
-        /**
588
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
-         * just use EE_Register_Model_Extension
590
-         *
591
-         * @var EE_Table_Base[] $_tables
592
-         */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
-        foreach ($this->_tables as $table_alias => $table_obj) {
595
-            /** @var $table_obj EE_Table_Base */
596
-            $table_obj->_construct_finalize_with_alias($table_alias);
597
-            if ($table_obj instanceof EE_Secondary_Table) {
598
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
-            }
600
-        }
601
-        /**
602
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
-         * EE_Register_Model_Extension
604
-         *
605
-         * @param EE_Model_Field_Base[] $_fields
606
-         */
607
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
-        $this->_invalidate_field_caches();
609
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
610
-            if (! array_key_exists($table_alias, $this->_tables)) {
611
-                throw new EE_Error(
612
-                    sprintf(
613
-                        esc_html__(
614
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
-                            'event_espresso'
616
-                        ),
617
-                        $table_alias,
618
-                        implode(",", $this->_fields)
619
-                    )
620
-                );
621
-            }
622
-            foreach ($fields_for_table as $field_name => $field_obj) {
623
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
-                // primary key field base has a slightly different _construct_finalize
625
-                /** @var $field_obj EE_Model_Field_Base */
626
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
-            }
628
-        }
629
-        // everything is related to Extra_Meta
630
-        if (get_class($this) !== 'EEM_Extra_Meta') {
631
-            // make extra meta related to everything, but don't block deleting things just
632
-            // because they have related extra meta info. For now just orphan those extra meta
633
-            // in the future we should automatically delete them
634
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
-        }
636
-        // and change logs
637
-        if (get_class($this) !== 'EEM_Change_Log') {
638
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
-        }
640
-        /**
641
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
-         * EE_Register_Model_Extension
643
-         *
644
-         * @param EE_Model_Relation_Base[] $_model_relations
645
-         */
646
-        $this->_model_relations = (array) apply_filters(
647
-            'FHEE__' . get_class($this) . '__construct__model_relations',
648
-            $this->_model_relations
649
-        );
650
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
651
-            /** @var $relation_obj EE_Model_Relation_Base */
652
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
-        }
654
-        foreach ($this->_indexes as $index_name => $index_obj) {
655
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
-        }
657
-        $this->set_timezone($timezone);
658
-        // finalize default where condition strategy, or set default
659
-        if (! $this->_default_where_conditions_strategy) {
660
-            // nothing was set during child constructor, so set default
661
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
-        }
663
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
664
-        if (! $this->_minimum_where_conditions_strategy) {
665
-            // nothing was set during child constructor, so set default
666
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
-        }
668
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
670
-        // to indicate to NOT set it, set it to the logical default
671
-        if ($this->_caps_slug === null) {
672
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
-        }
674
-        // initialize the standard cap restriction generators if none were specified by the child constructor
675
-        if (is_array($this->_cap_restriction_generators)) {
676
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
-                        new EE_Restriction_Generator_Protected(),
681
-                        $cap_context,
682
-                        $this
683
-                    );
684
-                }
685
-            }
686
-        }
687
-        // if there are cap restriction generators, use them to make the default cap restrictions
688
-        if (is_array($this->_cap_restriction_generators)) {
689
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
-                if (! $generator_object) {
691
-                    continue;
692
-                }
693
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
-                    throw new EE_Error(
695
-                        sprintf(
696
-                            esc_html__(
697
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
698
-                                'event_espresso'
699
-                            ),
700
-                            $context,
701
-                            $this->get_this_model_name()
702
-                        )
703
-                    );
704
-                }
705
-                $action = $this->cap_action_for_context($context);
706
-                if (! $generator_object->construction_finalized()) {
707
-                    $generator_object->_construct_finalize($this, $action);
708
-                }
709
-            }
710
-        }
711
-        do_action('AHEE__' . get_class($this) . '__construct__end');
712
-    }
713
-
714
-
715
-    /**
716
-     * @return LoaderInterface
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    protected static function getLoader(): LoaderInterface
722
-    {
723
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
724
-            EEM_Base::$loader = LoaderFactory::getLoader();
725
-        }
726
-        return EEM_Base::$loader;
727
-    }
728
-
729
-
730
-    /**
731
-     * @return Mirror
732
-     * @since   5.0.0.p
733
-     */
734
-    private static function getMirror(): Mirror
735
-    {
736
-        if (! EEM_Base::$mirror instanceof Mirror) {
737
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
-        }
739
-        return EEM_Base::$mirror;
740
-    }
741
-
742
-
743
-    /**
744
-     * @param string $model_class_Name
745
-     * @param string $timezone
746
-     * @return array
747
-     * @throws ReflectionException
748
-     * @since   5.0.0.p
749
-     */
750
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
751
-    {
752
-        $arguments = [$timezone];
753
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
-        if (count($params) > 1) {
755
-            if ($params[1]->getName() === 'model_field_factory') {
756
-                $arguments = [
757
-                    $timezone,
758
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
-                ];
760
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
761
-                $arguments = [
762
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
-                    $timezone,
764
-                ];
765
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
766
-                $arguments = [
767
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
-                    $timezone,
770
-                ];
771
-            }
772
-        }
773
-        return $arguments;
774
-    }
775
-
776
-
777
-    /**
778
-     * This function is a singleton method used to instantiate the Espresso_model object
779
-     *
780
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
-     *                                (and any incoming timezone data that gets saved).
782
-     *                                Note this just sends the timezone info to the date time model field objects.
783
-     *                                Default is NULL
784
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
-     * @return static (as in the concrete child class)
786
-     * @throws EE_Error
787
-     * @throws ReflectionException
788
-     */
789
-    public static function instance($timezone = '')
790
-    {
791
-        // check if instance of Espresso_model already exists
792
-        if (! static::$_instance instanceof static) {
793
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
-            $model     = new static(...$arguments);
795
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
-            static::$_instance = $model;
797
-        }
798
-        // we might have a timezone set, let set_timezone decide what to do with it
799
-        if ($timezone) {
800
-            static::$_instance->set_timezone($timezone);
801
-        }
802
-        // Espresso_model object
803
-        return static::$_instance;
804
-    }
805
-
806
-
807
-    /**
808
-     * resets the model and returns it
809
-     *
810
-     * @param string|null $timezone
811
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
-     * all its properties reset; if it wasn't instantiated, returns null)
813
-     * @throws EE_Error
814
-     * @throws ReflectionException
815
-     * @throws InvalidArgumentException
816
-     * @throws InvalidDataTypeException
817
-     * @throws InvalidInterfaceException
818
-     */
819
-    public static function reset($timezone = '')
820
-    {
821
-        if (! static::$_instance instanceof EEM_Base) {
822
-            return null;
823
-        }
824
-        // Let's NOT swap out the current instance for a new one
825
-        // because if someone has a reference to it, we can't remove their reference.
826
-        // It's best to keep using the same reference but change the original object instead,
827
-        // so reset all its properties to their original values as defined in the class.
828
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
-            // don't set instance to null like it was originally,
831
-            // but it's static anyways, and we're ignoring static properties (for now at least)
832
-            if (! isset($static_properties[ $property ])) {
833
-                static::$_instance->{$property} = $value;
834
-            }
835
-        }
836
-        // and then directly call its constructor again, like we would if we were creating a new one
837
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
-        static::$_instance->__construct(...$arguments);
839
-        return self::instance();
840
-    }
841
-
842
-
843
-    /**
844
-     * Used to set the $_model_query_blog_id static property.
845
-     *
846
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
-     *                      value for get_current_blog_id() will be used.
848
-     */
849
-    public static function set_model_query_blog_id($blog_id = 0)
850
-    {
851
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
852
-            ? (int) $blog_id
853
-            : get_current_blog_id();
854
-    }
855
-
856
-
857
-    /**
858
-     * Returns whatever is set as the internal $model_query_blog_id.
859
-     *
860
-     * @return int
861
-     */
862
-    public static function get_model_query_blog_id()
863
-    {
864
-        return EEM_Base::$_model_query_blog_id;
865
-    }
866
-
867
-
868
-    /**
869
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
-     *
871
-     * @param boolean $translated return localized strings or JUST the array.
872
-     * @return array
873
-     * @throws EE_Error
874
-     * @throws InvalidArgumentException
875
-     * @throws InvalidDataTypeException
876
-     * @throws InvalidInterfaceException
877
-     * @throws ReflectionException
878
-     */
879
-    public function status_array($translated = false)
880
-    {
881
-        if (! array_key_exists('Status', $this->_model_relations)) {
882
-            return [];
883
-        }
884
-        $model_name   = $this->get_this_model_name();
885
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
-        $status_array = [];
888
-        foreach ($stati as $status) {
889
-            $status_array[ $status->ID() ] = $status->get('STS_code');
890
-        }
891
-        return $translated
892
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
-            : $status_array;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
-     *
900
-     * @param array $query_params             @see
901
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
-     *                                        or if you have the development copy of EE you can view this at the path:
903
-     *                                        /docs/G--Model-System/model-query-params.md
904
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
-     *                                        EEM_Transaction::instance()->get_all( array( array(
909
-     *                                        'OR'=>array(
910
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
-     *                                        )
913
-     *                                        ),
914
-     *                                        'limit'=>10,
915
-     *                                        'group_by'=>'TXN_ID'
916
-     *                                        ));
917
-     *                                        get all the answers to the question titled "shirt size" for event with id
918
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
-     *                                        'Question.QST_display_text'=>'shirt size',
920
-     *                                        'Registration.Event.EVT_ID'=>12
921
-     *                                        ),
922
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
923
-     *                                        ));
924
-     * @throws EE_Error
925
-     * @throws ReflectionException
926
-     */
927
-    public function get_all($query_params = [])
928
-    {
929
-        if (
930
-            isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
-    }
937
-
938
-
939
-    /**
940
-     * Modifies the query parameters so we only get back model objects
941
-     * that "belong" to the current user
942
-     *
943
-     * @param array $query_params @see
944
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
-     * @return array @see
946
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
-     * @throws ReflectionException
948
-     * @throws ReflectionException
949
-     */
950
-    public function alter_query_params_to_only_include_mine($query_params = [])
951
-    {
952
-        $wp_user_field_name = $this->wp_user_field_name();
953
-        if ($wp_user_field_name) {
954
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
-        }
956
-        return $query_params;
957
-    }
958
-
959
-
960
-    /**
961
-     * Returns the name of the field's name that points to the WP_User table
962
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
-     * foreign key to the WP_User table)
964
-     *
965
-     * @return string|boolean string on success, boolean false when there is no
966
-     * foreign key to the WP_User table
967
-     * @throws ReflectionException
968
-     * @throws ReflectionException
969
-     */
970
-    public function wp_user_field_name()
971
-    {
972
-        try {
973
-            if (! empty($this->_model_chain_to_wp_user)) {
974
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
-                $last_model_name              = end($models_to_follow_to_wp_users);
976
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
-            } else {
979
-                $model_with_fk_to_wp_users = $this;
980
-                $model_chain_to_wp_user    = '';
981
-            }
982
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
984
-        } catch (EE_Error $e) {
985
-            return false;
986
-        }
987
-    }
988
-
989
-
990
-    /**
991
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
992
-     * (or transiently-related model) has a foreign key to the wp_users table;
993
-     * useful for finding if model objects of this type are 'owned' by the current user.
994
-     * This is an empty string when the foreign key is on this model and when it isn't,
995
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
996
-     * (or transiently-related model)
997
-     *
998
-     * @return string
999
-     */
1000
-    public function model_chain_to_wp_user()
1001
-    {
1002
-        return $this->_model_chain_to_wp_user;
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
-     * like how registrations don't have a foreign key to wp_users, but the
1009
-     * events they are for are), or is unrelated to wp users.
1010
-     * generally available
1011
-     *
1012
-     * @return boolean
1013
-     */
1014
-    public function is_owned()
1015
-    {
1016
-        if ($this->model_chain_to_wp_user()) {
1017
-            return true;
1018
-        }
1019
-        try {
1020
-            $this->get_foreign_key_to('WP_User');
1021
-            return true;
1022
-        } catch (EE_Error $e) {
1023
-            return false;
1024
-        }
1025
-    }
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      @see
1034
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     * @throws InvalidArgumentException
1047
-     * @throws ReflectionException
1048
-     */
1049
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
-    {
1051
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions       = $columns_to_select === null
1054
-            ? $this->_construct_default_select_sql($model_query_info)
1055
-            : '';
1056
-        if ($this->_custom_selections instanceof CustomSelects) {
1057
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
-            $select_expressions .= $select_expressions
1059
-                ? ', ' . $custom_expressions
1060
-                : $custom_expressions;
1061
-        }
1062
-
1063
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
-     * method of including extra select information.
1072
-     *
1073
-     * @param array             $query_params
1074
-     * @param null|array|string $columns_to_select
1075
-     * @return null|CustomSelects
1076
-     * @throws InvalidArgumentException
1077
-     */
1078
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
-    {
1080
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
-            return null;
1082
-        }
1083
-        $selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
-        $selects = is_string($selects)
1085
-            ? explode(',', $selects)
1086
-            : $selects;
1087
-        return new CustomSelects($selects);
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1093
-     * but you can use the model query params to more easily
1094
-     * take care of joins, field preparation etc.
1095
-     *
1096
-     * @param array  $query_params      @see
1097
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1101
-     *                                  override this and set the select to "*", or a specific column name, like
1102
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
-     *                                  the aliases used to refer to this selection, and values are to be
1105
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
-     * @throws EE_Error
1109
-     * @throws ReflectionException
1110
-     */
1111
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
-    {
1113
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * For creating a custom select statement
1119
-     *
1120
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
-     *                                 SQL, and 1=>is the datatype
1123
-     * @return string
1124
-     * @throws EE_Error
1125
-     */
1126
-    private function _construct_select_from_input($columns_to_select)
1127
-    {
1128
-        if (is_array($columns_to_select)) {
1129
-            $select_sql_array = [];
1130
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype,
1139
-                            $alias
1140
-                        )
1141
-                    );
1142
-                }
1143
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
-                    throw new EE_Error(
1145
-                        sprintf(
1146
-                            esc_html__(
1147
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
-                                'event_espresso'
1149
-                            ),
1150
-                            $selection_and_datatype[1],
1151
-                            $selection_and_datatype[0],
1152
-                            $alias,
1153
-                            implode(', ', $this->_valid_wpdb_data_types)
1154
-                        )
1155
-                    );
1156
-                }
1157
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
-            }
1159
-            $columns_to_select_string = implode(', ', $select_sql_array);
1160
-        } else {
1161
-            $columns_to_select_string = $columns_to_select;
1162
-        }
1163
-        return $columns_to_select_string;
1164
-    }
1165
-
1166
-
1167
-    /**
1168
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
-     *
1170
-     * @return string
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function primary_key_name()
1174
-    {
1175
-        return $this->get_primary_key_field()->get_name();
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
-     * If there is no primary key on this model, $id is treated as primary key string
1182
-     *
1183
-     * @param mixed $id int or string, depending on the type of the model's primary key
1184
-     * @return EE_Base_Class|mixed|null
1185
-     * @throws EE_Error
1186
-     * @throws ReflectionException
1187
-     */
1188
-    public function get_one_by_ID($id)
1189
-    {
1190
-        // since entities with no ID can still have properties, we need to check the cache for them
1191
-        $cached_value = $this->get_from_entity_map($id);
1192
-        if ($cached_value) {
1193
-            return $cached_value;
1194
-        }
1195
-        // but if no cached property AND no id is passed, just return null
1196
-        if (empty($id)) {
1197
-            return null;
1198
-        }
1199
-        $model_object = $this->get_one(
1200
-            $this->alter_query_params_to_restrict_by_ID(
1201
-                $id,
1202
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
-            )
1204
-        );
1205
-        $className    = $this->_get_class_name();
1206
-        if ($model_object instanceof $className) {
1207
-            // make sure valid objects get added to the entity map
1208
-            // so that the next call to this method doesn't trigger another trip to the db
1209
-            $this->add_to_entity_map($model_object);
1210
-        }
1211
-        return $model_object;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Alters query parameters to only get items with this ID are returned.
1217
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
-     * or could just be a simple primary key ID
1219
-     *
1220
-     * @param int   $id
1221
-     * @param array $query_params
1222
-     * @return array of normal query params, @see
1223
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
-     * @throws EE_Error
1225
-     */
1226
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
-    {
1228
-        if (! isset($query_params[0])) {
1229
-            $query_params[0] = [];
1230
-        }
1231
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1232
-        if ($conditions_from_id === null) {
1233
-            $query_params[0][ $this->primary_key_name() ] = $id;
1234
-        } else {
1235
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1236
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
-        }
1238
-        return $query_params;
1239
-    }
1240
-
1241
-
1242
-    /**
1243
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
-     * array. If no item is found, null is returned.
1245
-     *
1246
-     * @param array $query_params like EEM_Base's $query_params variable.
1247
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
-     * @throws EE_Error
1249
-     * @throws ReflectionException
1250
-     */
1251
-    public function get_one($query_params = [])
1252
-    {
1253
-        if (! is_array($query_params)) {
1254
-            EE_Error::doing_it_wrong(
1255
-                'EEM_Base::get_one',
1256
-                sprintf(
1257
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
-                    gettype($query_params)
1259
-                ),
1260
-                '4.6.0'
1261
-            );
1262
-            $query_params = [];
1263
-        }
1264
-        $query_params['limit'] = 1;
1265
-        $items                 = $this->get_all($query_params);
1266
-        if (empty($items)) {
1267
-            return null;
1268
-        }
1269
-        return array_shift($items);
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Returns the next x number of items in sequence from the given value as
1275
-     * found in the database matching the given query conditions.
1276
-     *
1277
-     * @param mixed $current_field_value    Value used for the reference point.
1278
-     * @param null  $field_to_order_by      What field is used for the
1279
-     *                                      reference point.
1280
-     * @param int   $limit                  How many to return.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an array of
1283
-     *                                      EE_Base_Class objects is returned,
1284
-     *                                      otherwise you can indicate just the
1285
-     *                                      columns you want returned.
1286
-     * @return EE_Base_Class[]|array
1287
-     * @throws EE_Error
1288
-     * @throws ReflectionException
1289
-     */
1290
-    public function next_x(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $limit = 1,
1294
-        $query_params = [],
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        return $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            $limit,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * Returns the previous x number of items in sequence from the given value
1310
-     * as found in the database matching the given query conditions.
1311
-     *
1312
-     * @param mixed $current_field_value    Value used for the reference point.
1313
-     * @param null  $field_to_order_by      What field is used for the
1314
-     *                                      reference point.
1315
-     * @param int   $limit                  How many to return.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an array of
1318
-     *                                      EE_Base_Class objects is returned,
1319
-     *                                      otherwise you can indicate just the
1320
-     *                                      columns you want returned.
1321
-     * @return EE_Base_Class[]|array
1322
-     * @throws EE_Error
1323
-     * @throws ReflectionException
1324
-     */
1325
-    public function previous_x(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $limit = 1,
1329
-        $query_params = [],
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        return $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            $limit,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-    }
1341
-
1342
-
1343
-    /**
1344
-     * Returns the next item in sequence from the given value as found in the
1345
-     * database matching the given query conditions.
1346
-     *
1347
-     * @param mixed $current_field_value    Value used for the reference point.
1348
-     * @param null  $field_to_order_by      What field is used for the
1349
-     *                                      reference point.
1350
-     * @param array $query_params           Extra conditions on the query.
1351
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
-     *                                      object is returned, otherwise you
1353
-     *                                      can indicate just the columns you
1354
-     *                                      want and a single array indexed by
1355
-     *                                      the columns will be returned.
1356
-     * @return EE_Base_Class|null|array()
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function next(
1361
-        $current_field_value,
1362
-        $field_to_order_by = null,
1363
-        $query_params = [],
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        $results = $this->_get_consecutive(
1367
-            $current_field_value,
1368
-            '>',
1369
-            $field_to_order_by,
1370
-            1,
1371
-            $query_params,
1372
-            $columns_to_select
1373
-        );
1374
-        return empty($results)
1375
-            ? null
1376
-            : reset($results);
1377
-    }
1378
-
1379
-
1380
-    /**
1381
-     * Returns the previous item in sequence from the given value as found in
1382
-     * the database matching the given query conditions.
1383
-     *
1384
-     * @param mixed $current_field_value    Value used for the reference point.
1385
-     * @param null  $field_to_order_by      What field is used for the
1386
-     *                                      reference point.
1387
-     * @param array $query_params           Extra conditions on the query.
1388
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
-     *                                      object is returned, otherwise you
1390
-     *                                      can indicate just the columns you
1391
-     *                                      want and a single array indexed by
1392
-     *                                      the columns will be returned.
1393
-     * @return EE_Base_Class|null|array()
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function previous(
1398
-        $current_field_value,
1399
-        $field_to_order_by = null,
1400
-        $query_params = [],
1401
-        $columns_to_select = null
1402
-    ) {
1403
-        $results = $this->_get_consecutive(
1404
-            $current_field_value,
1405
-            '<',
1406
-            $field_to_order_by,
1407
-            1,
1408
-            $query_params,
1409
-            $columns_to_select
1410
-        );
1411
-        return empty($results)
1412
-            ? null
1413
-            : reset($results);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Returns the a consecutive number of items in sequence from the given
1419
-     * value as found in the database matching the given query conditions.
1420
-     *
1421
-     * @param mixed  $current_field_value   Value used for the reference point.
1422
-     * @param string $operand               What operand is used for the sequence.
1423
-     * @param string $field_to_order_by     What field is used for the reference point.
1424
-     * @param int    $limit                 How many to return.
1425
-     * @param array  $query_params          Extra conditions on the query.
1426
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
-     *                                      otherwise you can indicate just the columns you want returned.
1428
-     * @return EE_Base_Class[]|array
1429
-     * @throws EE_Error
1430
-     * @throws ReflectionException
1431
-     */
1432
-    protected function _get_consecutive(
1433
-        $current_field_value,
1434
-        $operand = '>',
1435
-        $field_to_order_by = null,
1436
-        $limit = 1,
1437
-        $query_params = [],
1438
-        $columns_to_select = null
1439
-    ) {
1440
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
-        if (empty($field_to_order_by)) {
1442
-            if ($this->has_primary_key_field()) {
1443
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1444
-            } else {
1445
-                if (defined('WP_DEBUG') && WP_DEBUG) {
1446
-                    throw new EE_Error(
1447
-                        esc_html__(
1448
-                            '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).',
1449
-                            'event_espresso'
1450
-                        )
1451
-                    );
1452
-                }
1453
-                EE_Error::add_error(
1454
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1455
-                    __FILE__,
1456
-                    __FUNCTION__,
1457
-                    __LINE__
1458
-                );
1459
-                return [];
1460
-            }
1461
-        }
1462
-        if (! is_array($query_params)) {
1463
-            EE_Error::doing_it_wrong(
1464
-                'EEM_Base::_get_consecutive',
1465
-                sprintf(
1466
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
-                    gettype($query_params)
1468
-                ),
1469
-                '4.6.0'
1470
-            );
1471
-            $query_params = [];
1472
-        }
1473
-        // let's add the where query param for consecutive look up.
1474
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
-        $query_params['limit']                 = $limit;
1476
-        // set direction
1477
-        $incoming_orderby         = isset($query_params['order_by'])
1478
-            ? (array) $query_params['order_by']
1479
-            : [];
1480
-        $query_params['order_by'] = $operand === '>'
1481
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
-        if (empty($columns_to_select)) {
1485
-            return $this->get_all($query_params);
1486
-        }
1487
-        // getting just the fields
1488
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
-    }
1490
-
1491
-
1492
-    /**
1493
-     * This sets the _timezone property after model object has been instantiated.
1494
-     *
1495
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
-     * @throws Exception
1497
-     */
1498
-    public function set_timezone(?string $timezone = '')
1499
-    {
1500
-        if (! $timezone) {
1501
-            return;
1502
-        }
1503
-        $this->_timezone = $timezone;
1504
-        // note we need to loop through relations and set the timezone on those objects as well.
1505
-        foreach ($this->_model_relations as $relation) {
1506
-            $relation->set_timezone($timezone);
1507
-        }
1508
-        // and finally we do the same for any datetime fields
1509
-        foreach ($this->_fields as $field) {
1510
-            if ($field instanceof EE_Datetime_Field) {
1511
-                $field->set_timezone($timezone);
1512
-            }
1513
-        }
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * This just returns whatever is set for the current timezone.
1519
-     *
1520
-     * @access public
1521
-     * @return string
1522
-     * @throws Exception
1523
-     */
1524
-    public function get_timezone()
1525
-    {
1526
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
-        if (empty($this->_timezone)) {
1528
-            foreach ($this->_fields as $field) {
1529
-                if ($field instanceof EE_Datetime_Field) {
1530
-                    $this->set_timezone($field->get_timezone());
1531
-                    break;
1532
-                }
1533
-            }
1534
-        }
1535
-        // if timezone STILL empty then return the default timezone for the site.
1536
-        if (empty($this->_timezone)) {
1537
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
-        }
1539
-        return $this->_timezone;
1540
-    }
1541
-
1542
-
1543
-    /**
1544
-     * This returns the date formats set for the given field name and also ensures that
1545
-     * $this->_timezone property is set correctly.
1546
-     *
1547
-     * @param string $field_name The name of the field the formats are being retrieved for.
1548
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
-     * @return array formats in an array with the date format first, and the time format last.
1550
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
-     * @since 4.6.x
1552
-     */
1553
-    public function get_formats_for($field_name, $pretty = false)
1554
-    {
1555
-        $field_settings = $this->field_settings_for($field_name);
1556
-        // if not a valid EE_Datetime_Field then throw error
1557
-        if (! $field_settings instanceof EE_Datetime_Field) {
1558
-            throw new EE_Error(
1559
-                sprintf(
1560
-                    esc_html__(
1561
-                        '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.',
1562
-                        'event_espresso'
1563
-                    ),
1564
-                    $field_name
1565
-                )
1566
-            );
1567
-        }
1568
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
-        // the field.
1570
-        $this->_timezone = $field_settings->get_timezone();
1571
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
-    }
1573
-
1574
-
1575
-    /**
1576
-     * This returns the current time in a format setup for a query on this model.
1577
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
-     * it will return:
1579
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
-     *  NOW
1581
-     *  - or a unix timestamp (equivalent to time())
1582
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
-     *
1586
-     * @param string $field_name       The field the current time is needed for.
1587
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
-     *                                 formatted string matching the set format for the field in the set timezone will
1589
-     *                                 be returned.
1590
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
-     *                                 exception is triggered.
1593
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
-     * @throws Exception
1595
-     * @since 4.6.x
1596
-     */
1597
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
-    {
1599
-        $formats  = $this->get_formats_for($field_name);
1600
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
-        if ($timestamp) {
1602
-            return $DateTime->format('U');
1603
-        }
1604
-        // not returning timestamp, so return formatted string in timezone.
1605
-        switch ($what) {
1606
-            case 'time':
1607
-                return $DateTime->format($formats[1]);
1608
-            case 'date':
1609
-                return $DateTime->format($formats[0]);
1610
-            default:
1611
-                return $DateTime->format(implode(' ', $formats));
1612
-        }
1613
-    }
1614
-
1615
-
1616
-    /**
1617
-     * This receives a time string for a given field and ensures
1618
-     * that it is set up to match what the internal settings for the model are.
1619
-     * Returns a DateTime object.
1620
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
-     * (functionally the equivalent of UTC+0).
1622
-     * So when you send it in, whatever timezone string you include is ignored.
1623
-     *
1624
-     * @param string      $field_name      The field being setup.
1625
-     * @param string      $timestring      The date time string being used.
1626
-     * @param string      $incoming_format The format for the time string.
1627
-     * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
-     *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
-     *                                     incoming format is
1630
-     *                                     'U', this is ignored.
1631
-     * @return DbSafeDateTime
1632
-     * @throws EE_Error
1633
-     * @throws Exception
1634
-     */
1635
-    public function convert_datetime_for_query(
1636
-        string $field_name,
1637
-        string $timestring,
1638
-        string $incoming_format,
1639
-        ?string $timezone_string = ''
1640
-    ): DbSafeDateTime {
1641
-        // just using this to ensure the timezone is set correctly internally
1642
-        $this->get_formats_for($field_name);
1643
-        // load EEH_DTT_Helper
1644
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
-        return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
-    }
1649
-
1650
-
1651
-    /**
1652
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
-     *
1654
-     * @return EE_Table_Base[]
1655
-     */
1656
-    public function get_tables()
1657
-    {
1658
-        return $this->_tables;
1659
-    }
1660
-
1661
-
1662
-    /**
1663
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
-     * model object with EVT_ID = 1
1669
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
-     * are not specified)
1674
-     *
1675
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1680
-     *                                         ID=34, we'd use this method as follows:
1681
-     *                                         EEM_Transaction::instance()->update(
1682
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
-     *                                         array(array('TXN_ID'=>34)));
1684
-     * @param array   $query_params            @see
1685
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
-     *                                         TRUE, it is assumed that you've already called
1692
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
-     *                                         malicious javascript. However, if
1694
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
-     *                                         and every other field, before insertion. We provide this parameter
1697
-     *                                         because model objects perform their prepare_for_set function on all
1698
-     *                                         their values, and so don't need to be called again (and in many cases,
1699
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
-     *                                         prepare_for_set method...)
1701
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
-     *                                         in this model's entity map according to $fields_n_values that match
1703
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1704
-     *                                         by setting this to FALSE, but be aware that model objects being used
1705
-     *                                         could get out-of-sync with the database
1706
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
-     *                                         bad)
1709
-     * @throws EE_Error
1710
-     * @throws ReflectionException
1711
-     */
1712
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
-    {
1714
-        if (! is_array($query_params)) {
1715
-            EE_Error::doing_it_wrong(
1716
-                'EEM_Base::update',
1717
-                sprintf(
1718
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
-                    gettype($query_params)
1720
-                ),
1721
-                '4.6.0'
1722
-            );
1723
-            $query_params = [];
1724
-        }
1725
-        /**
1726
-         * Action called before a model update call has been made.
1727
-         *
1728
-         * @param EEM_Base $model
1729
-         * @param array    $fields_n_values the updated fields and their new values
1730
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
-         */
1732
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
-        /**
1734
-         * Filters the fields about to be updated given the query parameters. You can provide the
1735
-         * $query_params to $this->get_all() to find exactly which records will be updated
1736
-         *
1737
-         * @param array    $fields_n_values fields and their new values
1738
-         * @param EEM_Base $model           the model being queried
1739
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
-         */
1741
-        $fields_n_values = (array) apply_filters(
1742
-            'FHEE__EEM_Base__update__fields_n_values',
1743
-            $fields_n_values,
1744
-            $this,
1745
-            $query_params
1746
-        );
1747
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
-        // to do that, for each table, verify that it's PK isn't null.
1749
-        $tables = $this->get_tables();
1750
-        // 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
1751
-        // NOTE: we should make this code more efficient by NOT querying twice
1752
-        // before the real update, but that needs to first go through ALPHA testing
1753
-        // as it's dangerous. says Mike August 8 2014
1754
-        // we want to make sure the default_where strategy is ignored
1755
-        $this->_ignore_where_strategy = true;
1756
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
-        foreach ($wpdb_select_results as $wpdb_result) {
1758
-            // type cast stdClass as array
1759
-            $wpdb_result = (array) $wpdb_result;
1760
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
-            if ($this->has_primary_key_field()) {
1762
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
-            } else {
1764
-                // 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)
1765
-                $main_table_pk_value = null;
1766
-            }
1767
-            // 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
1768
-            // 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
1769
-            if (count($tables) > 1) {
1770
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
-                // in that table, and so we'll want to insert one
1772
-                foreach ($tables as $table_obj) {
1773
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
-                    // if there is no private key for this table on the results, it means there's no entry
1775
-                    // in this table, right? so insert a row in the current table, using any fields available
1776
-                    if (
1777
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
-                           && $wpdb_result[ $this_table_pk_column ])
1779
-                    ) {
1780
-                        $success = $this->_insert_into_specific_table(
1781
-                            $table_obj,
1782
-                            $fields_n_values,
1783
-                            $main_table_pk_value
1784
-                        );
1785
-                        // if we died here, report the error
1786
-                        if (! $success) {
1787
-                            return false;
1788
-                        }
1789
-                    }
1790
-                }
1791
-            }
1792
-            //              //and now check that if we have cached any models by that ID on the model, that
1793
-            //              //they also get updated properly
1794
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
-            //              if( $model_object ){
1796
-            //                  foreach( $fields_n_values as $field => $value ){
1797
-            //                      $model_object->set($field, $value);
1798
-            // let's make sure default_where strategy is followed now
1799
-            $this->_ignore_where_strategy = false;
1800
-        }
1801
-        // if we want to keep model objects in sync, AND
1802
-        // if this wasn't called from a model object (to update itself)
1803
-        // then we want to make sure we keep all the existing
1804
-        // model objects in sync with the db
1805
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
-            if ($this->has_primary_key_field()) {
1807
-                $model_objs_affected_ids = $this->get_col($query_params);
1808
-            } else {
1809
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
-                $model_objs_affected_ids     = [];
1812
-                foreach ($models_affected_key_columns as $row) {
1813
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1814
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
-                }
1816
-            }
1817
-            if (! $model_objs_affected_ids) {
1818
-                // wait wait wait- if nothing was affected let's stop here
1819
-                return 0;
1820
-            }
1821
-            foreach ($model_objs_affected_ids as $id) {
1822
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
-                if ($model_obj_in_entity_map) {
1824
-                    foreach ($fields_n_values as $field => $new_value) {
1825
-                        $model_obj_in_entity_map->set($field, $new_value);
1826
-                    }
1827
-                }
1828
-            }
1829
-            // if there is a primary key on this model, we can now do a slight optimization
1830
-            if ($this->has_primary_key_field()) {
1831
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
-                $query_params = [
1833
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
-                    'limit'                    => count($model_objs_affected_ids),
1835
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
-                ];
1837
-            }
1838
-        }
1839
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
-
1841
-        // note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
-        // because it doesn't accept LIMIT, ORDER BY, etc.
1843
-        $rows_affected = $this->_do_wpdb_query(
1844
-            'query',
1845
-            [
1846
-                "UPDATE " . $model_query_info->get_full_join_sql()
1847
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1848
-                . $model_query_info->get_where_sql(),
1849
-            ]
1850
-        );
1851
-
1852
-        /**
1853
-         * Action called after a model update call has been made.
1854
-         *
1855
-         * @param EEM_Base $model
1856
-         * @param array    $fields_n_values the updated fields and their new values
1857
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
-         * @param int      $rows_affected
1859
-         */
1860
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
-        return $rows_affected;// how many supposedly got updated
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1867
-     * are the values of the field specified (or by default the primary key field)
1868
-     * that matched the query params. Note that you should pass the name of the
1869
-     * model FIELD, not the database table's column name.
1870
-     *
1871
-     * @param array  $query_params
1872
-     * @param string $field_to_select
1873
-     * @return array just like $wpdb->get_col()
1874
-     * @throws EE_Error
1875
-     * @throws ReflectionException
1876
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1877
-     */
1878
-    public function get_col($query_params = [], $field_to_select = null)
1879
-    {
1880
-        if ($field_to_select) {
1881
-            $field = $this->field_settings_for($field_to_select);
1882
-        } elseif ($this->has_primary_key_field()) {
1883
-            $field = $this->get_primary_key_field();
1884
-        } else {
1885
-            $field_settings = $this->field_settings();
1886
-            // no primary key, just grab the first column
1887
-            $field = reset($field_settings);
1888
-            // don't need this array now
1889
-            unset($field_settings);
1890
-        }
1891
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
-        $select_expressions = $field->get_qualified_column();
1893
-        $SQL                =
1894
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1896
-    }
1897
-
1898
-
1899
-    /**
1900
-     * Returns a single column value for a single row from the database
1901
-     *
1902
-     * @param array  $query_params    @see
1903
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
-     * @param string $field_to_select @see EEM_Base::get_col()
1905
-     * @return string
1906
-     * @throws EE_Error
1907
-     * @throws ReflectionException
1908
-     */
1909
-    public function get_var($query_params = [], $field_to_select = null)
1910
-    {
1911
-        $query_params['limit'] = 1;
1912
-        $col                   = $this->get_col($query_params, $field_to_select);
1913
-        if (! empty($col)) {
1914
-            return reset($col);
1915
-        }
1916
-        return null;
1917
-    }
1918
-
1919
-
1920
-    /**
1921
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
-     * injection, but currently no further filtering is done
1924
-     *
1925
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
-     *                               be updated to in the DB
1927
-     * @return string of SQL
1928
-     * @throws EE_Error
1929
-     * @global      $wpdb
1930
-     */
1931
-    public function _construct_update_sql($fields_n_values)
1932
-    {
1933
-        /** @type WPDB $wpdb */
1934
-        global $wpdb;
1935
-        $cols_n_values = [];
1936
-        foreach ($fields_n_values as $field_name => $value) {
1937
-            $field_obj = $this->field_settings_for($field_name);
1938
-            // if the value is NULL, we want to assign the value to that.
1939
-            // wpdb->prepare doesn't really handle that properly
1940
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
-            $value_sql       = $prepared_value === null
1942
-                ? 'NULL'
1943
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
-        }
1946
-        return implode(",", $cols_n_values);
1947
-    }
1948
-
1949
-
1950
-    /**
1951
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
-     * Performs a HARD delete, meaning the database row should always be removed,
1953
-     * not just have a flag field on it switched
1954
-     * Wrapper for EEM_Base::delete_permanently()
1955
-     *
1956
-     * @param mixed $id
1957
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1958
-     *                             ie: enforce referential integrity
1959
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1960
-     * @return int the number of rows deleted
1961
-     * @throws EE_Error
1962
-     * @throws ReflectionException
1963
-     */
1964
-    public function delete_permanently_by_ID($id, $block_deletes = true): int
1965
-    {
1966
-        return $this->delete_permanently(
1967
-            [
1968
-                [$this->get_primary_key_field()->get_name() => $id],
1969
-                'limit' => 1,
1970
-            ],
1971
-            $block_deletes
1972
-        );
1973
-    }
1974
-
1975
-
1976
-    /**
1977
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1978
-     * Wrapper for EEM_Base::delete()
1979
-     *
1980
-     * @param mixed $id
1981
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1982
-     *                             ie: enforce referential integrity
1983
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1984
-     * @return int the number of rows deleted
1985
-     * @throws EE_Error
1986
-     * @throws ReflectionException
1987
-     */
1988
-    public function delete_by_ID($id, $block_deletes = true)
1989
-    {
1990
-        return $this->delete(
1991
-            [
1992
-                [$this->get_primary_key_field()->get_name() => $id],
1993
-                'limit' => 1,
1994
-            ],
1995
-            $block_deletes
1996
-        );
1997
-    }
1998
-
1999
-
2000
-    /**
2001
-     * Identical to delete_permanently, but does a "soft" delete if possible,
2002
-     * meaning if the model has a field that indicates its been "trashed" or
2003
-     * "soft deleted", we will just set that instead of actually deleting the rows.
2004
-     *
2005
-     * @param array   $query_params
2006
-     * @param boolean $block_deletes whether to allow related model objects to block (prevent) this deletion
2007
-     *                               ie: enforce referential integrity
2008
-     *                               It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2009
-     * @return int how many rows got deleted
2010
-     * @throws EE_Error
2011
-     * @throws ReflectionException
2012
-     * @see EEM_Base::delete_permanently
2013
-     */
2014
-    public function delete($query_params, $block_deletes = true)
2015
-    {
2016
-        return $this->delete_permanently($query_params, $block_deletes);
2017
-    }
2018
-
2019
-
2020
-    /**
2021
-     * Deletes the model objects that meet the query params. Note: this method is overridden
2022
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2023
-     * as archived, not actually deleted
2024
-     *
2025
-     * @param array   $query_params
2026
-     * @param boolean $block_deletes  whether to allow related model objects to block (prevent) this deletion
2027
-     *                                ie: enforce referential integrity
2028
-     *                                It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2029
-     * @return int how many rows got deleted
2030
-     * @throws EE_Error
2031
-     * @throws ReflectionException
2032
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2033
-     */
2034
-    public function delete_permanently($query_params, $block_deletes = true): int
2035
-    {
2036
-        /**
2037
-         * Action called just before performing a real deletion query. You can use the
2038
-         * model and its $query_params to find exactly which items will be deleted
2039
-         *
2040
-         * @param EEM_Base $model
2041
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2042
-         * @param bool     $block_deletes @see param description in method phpdoc block.
2043
-         */
2044
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $block_deletes);
2045
-        // some MySQL databases may be running safe mode, which may restrict
2046
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2047
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2048
-        // to delete them
2049
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2050
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $block_deletes);
2051
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2052
-            $columns_and_ids_for_deleting
2053
-        );
2054
-        /**
2055
-         * Allows client code to act on the items being deleted before the query is actually executed.
2056
-         * see php doc blocks for more details
2057
-         *
2058
-         * @param EEM_Base $this                         The model instance being acted on.
2059
-         * @param array    $query_params                 The incoming array of query parameters influencing what gets deleted.
2060
-         * @param bool     $block_deletes                @see param description in method phpdoc block.
2061
-         * @param array    $columns_and_ids_for_deleting An array indicating what entities will get removed as
2062
-         *                                               derived from the incoming query parameters.
2063
-         * @see details on the structure of this array in the phpdocs for the `_get_ids_for_delete_method`
2064
-         */
2065
-        do_action(
2066
-            'AHEE__EEM_Base__delete__before_query',
2067
-            $this,
2068
-            $query_params,
2069
-            $block_deletes,
2070
-            $columns_and_ids_for_deleting
2071
-        );
2072
-        $rows_deleted = 0;
2073
-        if ($deletion_where_query_part) {
2074
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2075
-            $table_aliases    = array_keys($this->_tables);
2076
-            $SQL              = "DELETE "
2077
-                                . implode(", ", $table_aliases)
2078
-                                . " FROM "
2079
-                                . $model_query_info->get_full_join_sql()
2080
-                                . " WHERE "
2081
-                                . $deletion_where_query_part;
2082
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2083
-        }
2084
-
2085
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2086
-        // there was no error with the delete query.
2087
-        if (
2088
-            $this->has_primary_key_field()
2089
-            && $rows_deleted !== false
2090
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2091
-        ) {
2092
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2093
-            foreach ($ids_for_removal as $id) {
2094
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2095
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2096
-                }
2097
-            }
2098
-
2099
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2100
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2101
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2102
-            // (although it is possible).
2103
-            // Note this can be skipped by using the provided filter and returning false.
2104
-            if (
2105
-                apply_filters(
2106
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2107
-                    ! $this instanceof EEM_Extra_Meta,
2108
-                    $this
2109
-                )
2110
-            ) {
2111
-                EEM_Extra_Meta::instance()->delete_permanently(
2112
-                    [
2113
-                        0 => [
2114
-                            'EXM_type' => $this->get_this_model_name(),
2115
-                            'OBJ_ID'   => [
2116
-                                'IN',
2117
-                                $ids_for_removal,
2118
-                            ],
2119
-                        ],
2120
-                    ]
2121
-                );
2122
-            }
2123
-        }
2124
-
2125
-        /**
2126
-         * Action called just after performing a real deletion query. Although at this point the
2127
-         * items should have been deleted
2128
-         *
2129
-         * @param EEM_Base $model
2130
-         * @param array $query_params
2131
-         * @param int   $rows_deleted
2132
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2133
-         */
2134
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2135
-        return (int) $rows_deleted;// how many supposedly got deleted
2136
-    }
2137
-
2138
-
2139
-    /**
2140
-     * Checks all the relations that throw error messages when there are blocking related objects
2141
-     * for related model objects. If there are any related model objects on those relations,
2142
-     * adds an EE_Error, and return true
2143
-     *
2144
-     * @param EE_Base_Class|int $this_model_obj_or_id
2145
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2146
-     *                                                 should be ignored when determining whether there are related
2147
-     *                                                 model objects which block this model object's deletion. Useful
2148
-     *                                                 if you know A is related to B and are considering deleting A,
2149
-     *                                                 but want to see if A has any other objects blocking its deletion
2150
-     *                                                 before removing the relation between A and B
2151
-     * @return boolean
2152
-     * @throws EE_Error
2153
-     * @throws ReflectionException
2154
-     */
2155
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2156
-    {
2157
-        // first, if $ignore_this_model_obj was supplied, get its model
2158
-        $ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2159
-            ? $ignore_this_model_obj->get_model()
2160
-            : null;
2161
-        // now check all the relations of $this_model_obj_or_id and see if there
2162
-        // are any related model objects blocking it?
2163
-        $is_blocked = false;
2164
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2165
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2166
-                // if $ignore_this_model_obj was supplied, then for the query
2167
-                // on that model needs to be told to ignore $ignore_this_model_obj
2168
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2169
-                    $related_model_objects = $relation_obj->get_all_related(
2170
-                        $this_model_obj_or_id,
2171
-                        [
2172
-                            [
2173
-                                $ignored_model->get_primary_key_field()->get_name() => [
2174
-                                    '!=',
2175
-                                    $ignore_this_model_obj->ID(),
2176
-                                ],
2177
-                            ],
2178
-                        ]
2179
-                    );
2180
-                } else {
2181
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2182
-                }
2183
-                if ($related_model_objects) {
2184
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2185
-                    $is_blocked = true;
2186
-                }
2187
-            }
2188
-        }
2189
-        return $is_blocked;
2190
-    }
2191
-
2192
-
2193
-    /**
2194
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2195
-     *
2196
-     * @param array $row_results_for_deleting
2197
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
2198
-     *                             ie: enforce referential integrity
2199
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2200
-     * @return array               The shape of this array depends on whether the model `has_primary_key_field` or not.
2201
-     *                             If the model DOES have a primary_key_field, then the array will be a simple single
2202
-     *                             dimension array where the key is the fully qualified primary key column and
2203
-     *                             the value is an array of ids that will be deleted.
2204
-     *                             Example:
2205
-     *                              [ 'Event.EVT_ID' => [ 1,2,3 ]]
2206
-     *                             If the model DOES NOT have a primary_key_field, then the array will be a
2207
-     *                             two-dimensional array where each element is a group of columns and values that get deleted.
2208
-     *                             Example:
2209
-     *                              [
2210
-     *                                  0 => [
2211
-     *                                      'Term_Relationship.object_id' => 1
2212
-     *                                      'Term_Relationship.term_taxonomy_id' => 5
2213
-     *                                  ],
2214
-     *                                  1 => [
2215
-     *                                      'Term_Relationship.object_id' => 1
2216
-     *                                      'Term_Relationship.term_taxonomy_id' => 6
2217
-     *                                  ]
2218
-     *                              ]
2219
-     * @throws EE_Error
2220
-     * @throws ReflectionException
2221
-     */
2222
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $block_deletes = true)
2223
-    {
2224
-        $ids_to_delete_indexed_by_column = [];
2225
-        if ($this->has_primary_key_field()) {
2226
-            $primary_table = $this->_get_main_table();
2227
-            // following lines are commented out because the variables were not being used
2228
-            // not deleting because unsure if calls were intentionally causing side effects
2229
-            // $primary_table_pk_field          =
2230
-            //     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2231
-            // $other_tables                    = $this->_get_other_tables();
2232
-            $ids_to_delete_indexed_by_column = $query = [];
2233
-            foreach ($row_results_for_deleting as $item_to_delete) {
2234
-                // before we mark this item for deletion,
2235
-                // make sure there's no related entities blocking its deletion (if we're checking)
2236
-                if (
2237
-                    $block_deletes
2238
-                    && $this->delete_is_blocked_by_related_models(
2239
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2240
-                    )
2241
-                ) {
2242
-                    continue;
2243
-                }
2244
-                // primary table deletes
2245
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2246
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2247
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2248
-                }
2249
-            }
2250
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2251
-            $fields = $this->get_combined_primary_key_fields();
2252
-            foreach ($row_results_for_deleting as $item_to_delete) {
2253
-                $ids_to_delete_indexed_by_column_for_row = [];
2254
-                foreach ($fields as $cpk_field) {
2255
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2256
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2257
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2258
-                    }
2259
-                }
2260
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2261
-            }
2262
-        } else {
2263
-            // so there's no primary key and no combined key...
2264
-            // sorry, can't help you
2265
-            throw new EE_Error(
2266
-                sprintf(
2267
-                    esc_html__(
2268
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2269
-                        "event_espresso"
2270
-                    ),
2271
-                    get_class($this)
2272
-                )
2273
-            );
2274
-        }
2275
-        return $ids_to_delete_indexed_by_column;
2276
-    }
2277
-
2278
-
2279
-    /**
2280
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2281
-     * the corresponding query_part for the query performing the deletion.
2282
-     *
2283
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2284
-     * @return string
2285
-     * @throws EE_Error
2286
-     */
2287
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2288
-    {
2289
-        $query_part = '';
2290
-        if (empty($ids_to_delete_indexed_by_column)) {
2291
-            return $query_part;
2292
-        } elseif ($this->has_primary_key_field()) {
2293
-            $query = [];
2294
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2295
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2296
-            }
2297
-            $query_part = ! empty($query)
2298
-                ? implode(' AND ', $query)
2299
-                : $query_part;
2300
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2301
-            $ways_to_identify_a_row = [];
2302
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2303
-                $values_for_each_combined_primary_key_for_a_row = [];
2304
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2305
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2306
-                }
2307
-                $ways_to_identify_a_row[] = '('
2308
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2309
-                                            . ')';
2310
-            }
2311
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2312
-        }
2313
-        return $query_part;
2314
-    }
2315
-
2316
-
2317
-    /**
2318
-     * Gets the model field by the fully qualified name
2319
-     *
2320
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2321
-     * @return EE_Model_Field_Base
2322
-     * @throws EE_Error
2323
-     * @throws EE_Error
2324
-     */
2325
-    public function get_field_by_column($qualified_column_name)
2326
-    {
2327
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2328
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2329
-                return $field_obj;
2330
-            }
2331
-        }
2332
-        throw new EE_Error(
2333
-            sprintf(
2334
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2335
-                $this->get_this_model_name(),
2336
-                $qualified_column_name
2337
-            )
2338
-        );
2339
-    }
2340
-
2341
-
2342
-    /**
2343
-     * Count all the rows that match criteria the model query params.
2344
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2345
-     * column
2346
-     *
2347
-     * @param array  $query_params   @see
2348
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2349
-     * @param string $field_to_count field on model to count by (not column name)
2350
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2351
-     *                               that by the setting $distinct to TRUE;
2352
-     * @return int
2353
-     * @throws EE_Error
2354
-     * @throws ReflectionException
2355
-     */
2356
-    public function count($query_params = [], $field_to_count = '', $distinct = false)
2357
-    {
2358
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2359
-        if ($field_to_count) {
2360
-            $field_obj       = $this->field_settings_for($field_to_count);
2361
-            $column_to_count = $field_obj->get_qualified_column();
2362
-        } elseif ($this->has_primary_key_field()) {
2363
-            $pk_field_obj    = $this->get_primary_key_field();
2364
-            $column_to_count = $pk_field_obj->get_qualified_column();
2365
-        } else {
2366
-            // there's no primary key
2367
-            // if we're counting distinct items, and there's no primary key,
2368
-            // we need to list out the columns for distinction;
2369
-            // otherwise we can just use star
2370
-            if ($distinct) {
2371
-                $columns_to_use = [];
2372
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2373
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2374
-                }
2375
-                $column_to_count = implode(',', $columns_to_use);
2376
-            } else {
2377
-                $column_to_count = '*';
2378
-            }
2379
-        }
2380
-        $column_to_count = $distinct
2381
-            ? "DISTINCT " . $column_to_count
2382
-            : $column_to_count;
2383
-        $SQL             =
2384
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2385
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2391
-     *
2392
-     * @param array  $query_params @see
2393
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2394
-     * @param string $field_to_sum name of field (array key in $_fields array)
2395
-     * @return float
2396
-     * @throws EE_Error
2397
-     * @throws ReflectionException
2398
-     */
2399
-    public function sum($query_params, $field_to_sum = null)
2400
-    {
2401
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2402
-        if ($field_to_sum) {
2403
-            $field_obj = $this->field_settings_for($field_to_sum);
2404
-        } else {
2405
-            $field_obj = $this->get_primary_key_field();
2406
-        }
2407
-        $column_to_count = $field_obj->get_qualified_column();
2408
-        $SQL             =
2409
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2410
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2411
-        $data_type       = $field_obj->get_wpdb_data_type();
2412
-        if ($data_type === '%d' || $data_type === '%s') {
2413
-            return (float) $return_value;
2414
-        }
2415
-        // must be %f
2416
-        return (float) $return_value;
2417
-    }
2418
-
2419
-
2420
-    /**
2421
-     * Just calls the specified method on $wpdb with the given arguments
2422
-     * Consolidates a little extra error handling code
2423
-     *
2424
-     * @param string $wpdb_method
2425
-     * @param array  $arguments_to_provide
2426
-     * @return mixed
2427
-     * @throws EE_Error
2428
-     * @global wpdb  $wpdb
2429
-     */
2430
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2431
-    {
2432
-        // if we're in maintenance mode level 2, DON'T run any queries
2433
-        // because level 2 indicates the database needs updating and
2434
-        // is probably out of sync with the code
2435
-        if (DbStatus::isOffline()) {
2436
-            throw new RuntimeException(
2437
-                esc_html__(
2438
-                    "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.",
2439
-                    "event_espresso"
2440
-                )
2441
-            );
2442
-        }
2443
-        /** @type WPDB $wpdb */
2444
-        global $wpdb;
2445
-        if (! method_exists($wpdb, $wpdb_method)) {
2446
-            throw new DomainException(
2447
-                sprintf(
2448
-                    esc_html__(
2449
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2450
-                        'event_espresso'
2451
-                    ),
2452
-                    $wpdb_method
2453
-                )
2454
-            );
2455
-        }
2456
-        $old_show_errors_value = $wpdb->show_errors;
2457
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2458
-            $wpdb->show_errors(false);
2459
-        }
2460
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2461
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2462
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2463
-            $wpdb->show_errors($old_show_errors_value);
2464
-            if (! empty($wpdb->last_error)) {
2465
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2466
-            }
2467
-            if ($result === false) {
2468
-                throw new EE_Error(
2469
-                    sprintf(
2470
-                        esc_html__(
2471
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2472
-                            'event_espresso'
2473
-                        ),
2474
-                        $wpdb_method,
2475
-                        var_export($arguments_to_provide, true)
2476
-                    )
2477
-                );
2478
-            }
2479
-        } elseif ($result === false) {
2480
-            EE_Error::add_error(
2481
-                sprintf(
2482
-                    esc_html__(
2483
-                        '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"',
2484
-                        'event_espresso'
2485
-                    ),
2486
-                    $wpdb_method,
2487
-                    var_export($arguments_to_provide, true),
2488
-                    $wpdb->last_error
2489
-                ),
2490
-                __FILE__,
2491
-                __FUNCTION__,
2492
-                __LINE__
2493
-            );
2494
-        }
2495
-        return $result;
2496
-    }
2497
-
2498
-
2499
-    /**
2500
-     * Attempts to run the indicated WPDB method with the provided arguments,
2501
-     * and if there's an error tries to verify the DB is correct. Uses
2502
-     * the static property EEM_Base::$_db_verification_level to determine whether
2503
-     * we should try to fix the EE core db, the addons, or just give up
2504
-     *
2505
-     * @param string $wpdb_method
2506
-     * @param array  $arguments_to_provide
2507
-     * @return mixed
2508
-     */
2509
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2510
-    {
2511
-        /** @type WPDB $wpdb */
2512
-        global $wpdb;
2513
-        $wpdb->last_error = null;
2514
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2515
-        // was there an error running the query? but we don't care on new activations
2516
-        // (we're going to setup the DB anyway on new activations)
2517
-        if (
2518
-            ($result === false || ! empty($wpdb->last_error))
2519
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2520
-        ) {
2521
-            switch (EEM_Base::$_db_verification_level) {
2522
-                case EEM_Base::db_verified_none:
2523
-                    // let's double-check core's DB
2524
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2525
-                    break;
2526
-                case EEM_Base::db_verified_core:
2527
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2528
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2529
-                    break;
2530
-                case EEM_Base::db_verified_addons:
2531
-                    // ummmm... you in trouble
2532
-                    return $result;
2533
-            }
2534
-            if (! empty($error_message)) {
2535
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2536
-                trigger_error($error_message);
2537
-            }
2538
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2539
-        }
2540
-        return $result;
2541
-    }
2542
-
2543
-
2544
-    /**
2545
-     * Verifies the EE core database is up-to-date and records that we've done it on
2546
-     * EEM_Base::$_db_verification_level
2547
-     *
2548
-     * @param string $wpdb_method
2549
-     * @param array  $arguments_to_provide
2550
-     * @return string
2551
-     * @throws EE_Error
2552
-     * @throws ReflectionException
2553
-     */
2554
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2555
-    {
2556
-        /** @type WPDB $wpdb */
2557
-        global $wpdb;
2558
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2559
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2560
-        $error_message                    = sprintf(
2561
-            esc_html__(
2562
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2563
-                'event_espresso'
2564
-            ),
2565
-            $wpdb->last_error,
2566
-            $wpdb_method,
2567
-            wp_json_encode($arguments_to_provide)
2568
-        );
2569
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2570
-        return $error_message;
2571
-    }
2572
-
2573
-
2574
-    /**
2575
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2576
-     * EEM_Base::$_db_verification_level
2577
-     *
2578
-     * @param $wpdb_method
2579
-     * @param $arguments_to_provide
2580
-     * @return string
2581
-     * @throws EE_Error
2582
-     * @throws ReflectionException
2583
-     */
2584
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2585
-    {
2586
-        /** @type WPDB $wpdb */
2587
-        global $wpdb;
2588
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2589
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2590
-        $error_message                    = sprintf(
2591
-            esc_html__(
2592
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2593
-                'event_espresso'
2594
-            ),
2595
-            $wpdb->last_error,
2596
-            $wpdb_method,
2597
-            wp_json_encode($arguments_to_provide)
2598
-        );
2599
-        EE_System::instance()->initialize_addons();
2600
-        return $error_message;
2601
-    }
2602
-
2603
-
2604
-    /**
2605
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2606
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2607
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2608
-     * ..."
2609
-     *
2610
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2611
-     * @return string
2612
-     */
2613
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2614
-    {
2615
-        return " FROM " . $model_query_info->get_full_join_sql() .
2616
-               $model_query_info->get_where_sql() .
2617
-               $model_query_info->get_group_by_sql() .
2618
-               $model_query_info->get_having_sql() .
2619
-               $model_query_info->get_order_by_sql() .
2620
-               $model_query_info->get_limit_sql();
2621
-    }
2622
-
2623
-
2624
-    /**
2625
-     * Set to easily debug the next X queries ran from this model.
2626
-     *
2627
-     * @param int $count
2628
-     */
2629
-    public function show_next_x_db_queries($count = 1)
2630
-    {
2631
-        $this->_show_next_x_db_queries = $count;
2632
-    }
2633
-
2634
-
2635
-    /**
2636
-     * @param $sql_query
2637
-     */
2638
-    public function show_db_query_if_previously_requested($sql_query)
2639
-    {
2640
-        if ($this->_show_next_x_db_queries > 0) {
2641
-            $left = is_admin() ? '12rem' : '2rem';
2642
-            echo "
42
+	/**
43
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
46
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
+	 *
48
+	 * @var boolean
49
+	 */
50
+	private $_values_already_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we assume
54
+	 * the data is just like form input that needs to have the model fields'
55
+	 * prepare_for_set and prepare_for_use_in_db called on it
56
+	 */
57
+	const not_prepared_by_model_object = 0;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we
61
+	 * assume this value is coming from a model object and doesn't need to have
62
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
63
+	 */
64
+	const prepared_by_model_object = 1;
65
+
66
+	/**
67
+	 * when $_values_already_prepared_by_model_object equals this, we assume
68
+	 * the values are already to be used in the database (ie no processing is done
69
+	 * on them by the model's fields)
70
+	 */
71
+	const prepared_for_use_in_db = 2;
72
+
73
+
74
+	protected $singular_item = 'Item';
75
+
76
+	protected $plural_item   = 'Items';
77
+
78
+	/**
79
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
+	 */
81
+	protected $_tables;
82
+
83
+	/**
84
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
+	 *
88
+	 * @var EE_Model_Field_Base[][] $_fields
89
+	 */
90
+	protected $_fields;
91
+
92
+	/**
93
+	 * array of different kinds of relations
94
+	 *
95
+	 * @var EE_Model_Relation_Base[] $_model_relations
96
+	 */
97
+	protected $_model_relations = [];
98
+
99
+	/**
100
+	 * @var EE_Index[] $_indexes
101
+	 */
102
+	protected $_indexes = [];
103
+
104
+	/**
105
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
106
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
+	 * by setting the same columns as used in these queries in the query yourself.
108
+	 *
109
+	 * @var EE_Default_Where_Conditions
110
+	 */
111
+	protected $_default_where_conditions_strategy;
112
+
113
+	/**
114
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
+	 * This is particularly useful when you want something between 'none' and 'default'
116
+	 *
117
+	 * @var EE_Default_Where_Conditions
118
+	 */
119
+	protected $_minimum_where_conditions_strategy;
120
+
121
+	/**
122
+	 * String describing how to find the "owner" of this model's objects.
123
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
+	 * But when there isn't, this indicates which related model, or transiently-related model,
125
+	 * has the foreign key to the wp_users table.
126
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
+	 * related to events, and events have a foreign key to wp_users.
128
+	 * On EEM_Transaction, this would be 'Transaction.Event'
129
+	 *
130
+	 * @var string
131
+	 */
132
+	protected $_model_chain_to_wp_user = '';
133
+
134
+	/**
135
+	 * String describing how to find the model with a password controlling access to this model. This property has the
136
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
+	 * This value is the path of models to follow to arrive at the model with the password field.
138
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
+	 * model with a password that should affect reading this on the front-end.
140
+	 * Eg this is an empty string for the Event model because it has a password.
141
+	 * This is null for the Registration model, because its event's password has no bearing on whether
142
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
+	 * should hide tickets for datetimes for events that have a password set.
145
+	 *
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = [
178
+		self::caps_read       => [],
179
+		self::caps_read_admin => [],
180
+		self::caps_edit       => [],
181
+		self::caps_delete     => [],
182
+	];
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = [];
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in the capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = [
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	];
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = [];
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 *
298
+	 * @var boolean
299
+	 */
300
+	protected $_wp_core_model = false;
301
+
302
+	/**
303
+	 * @var bool stores whether this model has a password field or not.
304
+	 * null until initialized by hasPasswordField()
305
+	 */
306
+	protected $has_password_field;
307
+
308
+	/**
309
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
+	 */
311
+	protected $password_field;
312
+
313
+	/**
314
+	 *    List of valid operators that can be used for querying.
315
+	 * The keys are all operators we'll accept, the values are the real SQL
316
+	 * operators used
317
+	 *
318
+	 * @var array
319
+	 */
320
+	protected $_valid_operators = [
321
+		'='           => '=',
322
+		'<='          => '<=',
323
+		'<'           => '<',
324
+		'>='          => '>=',
325
+		'>'           => '>',
326
+		'!='          => '!=',
327
+		'LIKE'        => 'LIKE',
328
+		'like'        => 'LIKE',
329
+		'NOT_LIKE'    => 'NOT LIKE',
330
+		'not_like'    => 'NOT LIKE',
331
+		'NOT LIKE'    => 'NOT LIKE',
332
+		'not like'    => 'NOT LIKE',
333
+		'IN'          => 'IN',
334
+		'in'          => 'IN',
335
+		'NOT_IN'      => 'NOT IN',
336
+		'not_in'      => 'NOT IN',
337
+		'NOT IN'      => 'NOT IN',
338
+		'not in'      => 'NOT IN',
339
+		'between'     => 'BETWEEN',
340
+		'BETWEEN'     => 'BETWEEN',
341
+		'IS_NOT_NULL' => 'IS NOT NULL',
342
+		'is_not_null' => 'IS NOT NULL',
343
+		'IS NOT NULL' => 'IS NOT NULL',
344
+		'is not null' => 'IS NOT NULL',
345
+		'IS_NULL'     => 'IS NULL',
346
+		'is_null'     => 'IS NULL',
347
+		'IS NULL'     => 'IS NULL',
348
+		'is null'     => 'IS NULL',
349
+		'REGEXP'      => 'REGEXP',
350
+		'regexp'      => 'REGEXP',
351
+		'NOT_REGEXP'  => 'NOT REGEXP',
352
+		'not_regexp'  => 'NOT REGEXP',
353
+		'NOT REGEXP'  => 'NOT REGEXP',
354
+		'not regexp'  => 'NOT REGEXP',
355
+	];
356
+
357
+	/**
358
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
+	 *
360
+	 * @var array
361
+	 */
362
+	protected $_in_style_operators = ['IN', 'NOT IN'];
363
+
364
+	/**
365
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
+	 * '12-31-2012'"
367
+	 *
368
+	 * @var array
369
+	 */
370
+	protected $_between_style_operators = ['BETWEEN'];
371
+
372
+	/**
373
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
+
379
+	/**
380
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
+	 * on a join table.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
+
387
+	/**
388
+	 * Allowed values for $query_params['order'] for ordering in queries
389
+	 *
390
+	 * @var array
391
+	 */
392
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
+
394
+	/**
395
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
+
402
+	/**
403
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
405
+	 *
406
+	 * @var array
407
+	 */
408
+	private $_allowed_query_params = [
409
+		0,
410
+		'limit',
411
+		'order_by',
412
+		'group_by',
413
+		'having',
414
+		'force_join',
415
+		'order',
416
+		'on_join_limit',
417
+		'default_where_conditions',
418
+		'caps',
419
+		'extra_selects',
420
+		'exclude_protected',
421
+	];
422
+
423
+	/**
424
+	 * All the data types that can be used in $wpdb->prepare statements.
425
+	 *
426
+	 * @var array
427
+	 */
428
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
+
430
+	/**
431
+	 * @var EE_Registry $EE
432
+	 */
433
+	protected $EE = null;
434
+
435
+
436
+	/**
437
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
+	 *
439
+	 * @var int
440
+	 */
441
+	protected $_show_next_x_db_queries = 0;
442
+
443
+	/**
444
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
+	 * WHERE, GROUP_BY, etc.
447
+	 *
448
+	 * @var CustomSelects
449
+	 */
450
+	protected $_custom_selections = [];
451
+
452
+	/**
453
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
+	 * caches every model object we've fetched from the DB on this request
455
+	 *
456
+	 * @var array
457
+	 */
458
+	protected $_entity_map;
459
+
460
+	/**
461
+	 * @var LoaderInterface
462
+	 */
463
+	protected static $loader;
464
+
465
+	/**
466
+	 * @var Mirror
467
+	 */
468
+	private static $mirror;
469
+
470
+
471
+	/**
472
+	 * constant used to show EEM_Base has not yet verified the db on this http request
473
+	 */
474
+	const db_verified_none = 0;
475
+
476
+	/**
477
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
478
+	 * but not the addons' dbs
479
+	 */
480
+	const db_verified_core = 1;
481
+
482
+	/**
483
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
+	 * the EE core db too)
485
+	 */
486
+	const db_verified_addons = 2;
487
+
488
+	/**
489
+	 * indicates whether an EEM_Base child has already re-verified the DB
490
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
491
+	 * looking like EEM_Base::db_verified_*
492
+	 *
493
+	 * @var int - 0 = none, 1 = core, 2 = addons
494
+	 */
495
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
496
+
497
+	/**
498
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
499
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
500
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
501
+	 */
502
+	const default_where_conditions_all = 'all';
503
+
504
+	/**
505
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
506
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
507
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
508
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
509
+	 *        models which share tables with other models, this can return data for the wrong model.
510
+	 */
511
+	const default_where_conditions_this_only = 'this_model_only';
512
+
513
+	/**
514
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
515
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
516
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
517
+	 */
518
+	const default_where_conditions_others_only = 'other_models_only';
519
+
520
+	/**
521
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
522
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
523
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
524
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
525
+	 *        (regardless of whether those events and venues are trashed)
526
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
527
+	 *        events.
528
+	 */
529
+	const default_where_conditions_minimum_all = 'minimum';
530
+
531
+	/**
532
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
533
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
534
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
535
+	 *        not)
536
+	 */
537
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
538
+
539
+	/**
540
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
541
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
542
+	 *        it's possible it will return table entries for other models. You should use
543
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
544
+	 */
545
+	const default_where_conditions_none = 'none';
546
+
547
+
548
+	/**
549
+	 * About all child constructors:
550
+	 * they should define the _tables, _fields and _model_relations arrays.
551
+	 * Should ALWAYS be called after child constructor.
552
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
553
+	 * finalizes constructing all the object's attributes.
554
+	 * Generally, rather than requiring a child to code
555
+	 * $this->_tables = array(
556
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
557
+	 *        ...);
558
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
559
+	 * each EE_Table has a function to set the table's alias after the constructor, using
560
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
561
+	 * do something similar.
562
+	 *
563
+	 * @param string|null $timezone
564
+	 * @throws EE_Error
565
+	 * @throws Exception
566
+	 */
567
+	protected function __construct($timezone = '')
568
+	{
569
+		// check that the model has not been loaded too soon
570
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
571
+			throw new EE_Error(
572
+				sprintf(
573
+					esc_html__(
574
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
575
+						'event_espresso'
576
+					),
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		/**
582
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
583
+		 */
584
+		if (empty(EEM_Base::$_model_query_blog_id)) {
585
+			EEM_Base::set_model_query_blog_id();
586
+		}
587
+		/**
588
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
589
+		 * just use EE_Register_Model_Extension
590
+		 *
591
+		 * @var EE_Table_Base[] $_tables
592
+		 */
593
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
594
+		foreach ($this->_tables as $table_alias => $table_obj) {
595
+			/** @var $table_obj EE_Table_Base */
596
+			$table_obj->_construct_finalize_with_alias($table_alias);
597
+			if ($table_obj instanceof EE_Secondary_Table) {
598
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
599
+			}
600
+		}
601
+		/**
602
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
603
+		 * EE_Register_Model_Extension
604
+		 *
605
+		 * @param EE_Model_Field_Base[] $_fields
606
+		 */
607
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
608
+		$this->_invalidate_field_caches();
609
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
610
+			if (! array_key_exists($table_alias, $this->_tables)) {
611
+				throw new EE_Error(
612
+					sprintf(
613
+						esc_html__(
614
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
615
+							'event_espresso'
616
+						),
617
+						$table_alias,
618
+						implode(",", $this->_fields)
619
+					)
620
+				);
621
+			}
622
+			foreach ($fields_for_table as $field_name => $field_obj) {
623
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
624
+				// primary key field base has a slightly different _construct_finalize
625
+				/** @var $field_obj EE_Model_Field_Base */
626
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
627
+			}
628
+		}
629
+		// everything is related to Extra_Meta
630
+		if (get_class($this) !== 'EEM_Extra_Meta') {
631
+			// make extra meta related to everything, but don't block deleting things just
632
+			// because they have related extra meta info. For now just orphan those extra meta
633
+			// in the future we should automatically delete them
634
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
635
+		}
636
+		// and change logs
637
+		if (get_class($this) !== 'EEM_Change_Log') {
638
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
639
+		}
640
+		/**
641
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
642
+		 * EE_Register_Model_Extension
643
+		 *
644
+		 * @param EE_Model_Relation_Base[] $_model_relations
645
+		 */
646
+		$this->_model_relations = (array) apply_filters(
647
+			'FHEE__' . get_class($this) . '__construct__model_relations',
648
+			$this->_model_relations
649
+		);
650
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
651
+			/** @var $relation_obj EE_Model_Relation_Base */
652
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
653
+		}
654
+		foreach ($this->_indexes as $index_name => $index_obj) {
655
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
656
+		}
657
+		$this->set_timezone($timezone);
658
+		// finalize default where condition strategy, or set default
659
+		if (! $this->_default_where_conditions_strategy) {
660
+			// nothing was set during child constructor, so set default
661
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662
+		}
663
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
664
+		if (! $this->_minimum_where_conditions_strategy) {
665
+			// nothing was set during child constructor, so set default
666
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667
+		}
668
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
669
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
670
+		// to indicate to NOT set it, set it to the logical default
671
+		if ($this->_caps_slug === null) {
672
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
673
+		}
674
+		// initialize the standard cap restriction generators if none were specified by the child constructor
675
+		if (is_array($this->_cap_restriction_generators)) {
676
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
679
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680
+						new EE_Restriction_Generator_Protected(),
681
+						$cap_context,
682
+						$this
683
+					);
684
+				}
685
+			}
686
+		}
687
+		// if there are cap restriction generators, use them to make the default cap restrictions
688
+		if (is_array($this->_cap_restriction_generators)) {
689
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
+				if (! $generator_object) {
691
+					continue;
692
+				}
693
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
694
+					throw new EE_Error(
695
+						sprintf(
696
+							esc_html__(
697
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
698
+								'event_espresso'
699
+							),
700
+							$context,
701
+							$this->get_this_model_name()
702
+						)
703
+					);
704
+				}
705
+				$action = $this->cap_action_for_context($context);
706
+				if (! $generator_object->construction_finalized()) {
707
+					$generator_object->_construct_finalize($this, $action);
708
+				}
709
+			}
710
+		}
711
+		do_action('AHEE__' . get_class($this) . '__construct__end');
712
+	}
713
+
714
+
715
+	/**
716
+	 * @return LoaderInterface
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	protected static function getLoader(): LoaderInterface
722
+	{
723
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
724
+			EEM_Base::$loader = LoaderFactory::getLoader();
725
+		}
726
+		return EEM_Base::$loader;
727
+	}
728
+
729
+
730
+	/**
731
+	 * @return Mirror
732
+	 * @since   5.0.0.p
733
+	 */
734
+	private static function getMirror(): Mirror
735
+	{
736
+		if (! EEM_Base::$mirror instanceof Mirror) {
737
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738
+		}
739
+		return EEM_Base::$mirror;
740
+	}
741
+
742
+
743
+	/**
744
+	 * @param string $model_class_Name
745
+	 * @param string $timezone
746
+	 * @return array
747
+	 * @throws ReflectionException
748
+	 * @since   5.0.0.p
749
+	 */
750
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
751
+	{
752
+		$arguments = [$timezone];
753
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
754
+		if (count($params) > 1) {
755
+			if ($params[1]->getName() === 'model_field_factory') {
756
+				$arguments = [
757
+					$timezone,
758
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
759
+				];
760
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
761
+				$arguments = [
762
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
763
+					$timezone,
764
+				];
765
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
766
+				$arguments = [
767
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
768
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
769
+					$timezone,
770
+				];
771
+			}
772
+		}
773
+		return $arguments;
774
+	}
775
+
776
+
777
+	/**
778
+	 * This function is a singleton method used to instantiate the Espresso_model object
779
+	 *
780
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
781
+	 *                                (and any incoming timezone data that gets saved).
782
+	 *                                Note this just sends the timezone info to the date time model field objects.
783
+	 *                                Default is NULL
784
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
785
+	 * @return static (as in the concrete child class)
786
+	 * @throws EE_Error
787
+	 * @throws ReflectionException
788
+	 */
789
+	public static function instance($timezone = '')
790
+	{
791
+		// check if instance of Espresso_model already exists
792
+		if (! static::$_instance instanceof static) {
793
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794
+			$model     = new static(...$arguments);
795
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
796
+			static::$_instance = $model;
797
+		}
798
+		// we might have a timezone set, let set_timezone decide what to do with it
799
+		if ($timezone) {
800
+			static::$_instance->set_timezone($timezone);
801
+		}
802
+		// Espresso_model object
803
+		return static::$_instance;
804
+	}
805
+
806
+
807
+	/**
808
+	 * resets the model and returns it
809
+	 *
810
+	 * @param string|null $timezone
811
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
812
+	 * all its properties reset; if it wasn't instantiated, returns null)
813
+	 * @throws EE_Error
814
+	 * @throws ReflectionException
815
+	 * @throws InvalidArgumentException
816
+	 * @throws InvalidDataTypeException
817
+	 * @throws InvalidInterfaceException
818
+	 */
819
+	public static function reset($timezone = '')
820
+	{
821
+		if (! static::$_instance instanceof EEM_Base) {
822
+			return null;
823
+		}
824
+		// Let's NOT swap out the current instance for a new one
825
+		// because if someone has a reference to it, we can't remove their reference.
826
+		// It's best to keep using the same reference but change the original object instead,
827
+		// so reset all its properties to their original values as defined in the class.
828
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
829
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830
+			// don't set instance to null like it was originally,
831
+			// but it's static anyways, and we're ignoring static properties (for now at least)
832
+			if (! isset($static_properties[ $property ])) {
833
+				static::$_instance->{$property} = $value;
834
+			}
835
+		}
836
+		// and then directly call its constructor again, like we would if we were creating a new one
837
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
838
+		static::$_instance->__construct(...$arguments);
839
+		return self::instance();
840
+	}
841
+
842
+
843
+	/**
844
+	 * Used to set the $_model_query_blog_id static property.
845
+	 *
846
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
847
+	 *                      value for get_current_blog_id() will be used.
848
+	 */
849
+	public static function set_model_query_blog_id($blog_id = 0)
850
+	{
851
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
852
+			? (int) $blog_id
853
+			: get_current_blog_id();
854
+	}
855
+
856
+
857
+	/**
858
+	 * Returns whatever is set as the internal $model_query_blog_id.
859
+	 *
860
+	 * @return int
861
+	 */
862
+	public static function get_model_query_blog_id()
863
+	{
864
+		return EEM_Base::$_model_query_blog_id;
865
+	}
866
+
867
+
868
+	/**
869
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
870
+	 *
871
+	 * @param boolean $translated return localized strings or JUST the array.
872
+	 * @return array
873
+	 * @throws EE_Error
874
+	 * @throws InvalidArgumentException
875
+	 * @throws InvalidDataTypeException
876
+	 * @throws InvalidInterfaceException
877
+	 * @throws ReflectionException
878
+	 */
879
+	public function status_array($translated = false)
880
+	{
881
+		if (! array_key_exists('Status', $this->_model_relations)) {
882
+			return [];
883
+		}
884
+		$model_name   = $this->get_this_model_name();
885
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
886
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887
+		$status_array = [];
888
+		foreach ($stati as $status) {
889
+			$status_array[ $status->ID() ] = $status->get('STS_code');
890
+		}
891
+		return $translated
892
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
893
+			: $status_array;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
899
+	 *
900
+	 * @param array $query_params             @see
901
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
902
+	 *                                        or if you have the development copy of EE you can view this at the path:
903
+	 *                                        /docs/G--Model-System/model-query-params.md
904
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
905
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
906
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
907
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
908
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
909
+	 *                                        'OR'=>array(
910
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
911
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
912
+	 *                                        )
913
+	 *                                        ),
914
+	 *                                        'limit'=>10,
915
+	 *                                        'group_by'=>'TXN_ID'
916
+	 *                                        ));
917
+	 *                                        get all the answers to the question titled "shirt size" for event with id
918
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
919
+	 *                                        'Question.QST_display_text'=>'shirt size',
920
+	 *                                        'Registration.Event.EVT_ID'=>12
921
+	 *                                        ),
922
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
923
+	 *                                        ));
924
+	 * @throws EE_Error
925
+	 * @throws ReflectionException
926
+	 */
927
+	public function get_all($query_params = [])
928
+	{
929
+		if (
930
+			isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
936
+	}
937
+
938
+
939
+	/**
940
+	 * Modifies the query parameters so we only get back model objects
941
+	 * that "belong" to the current user
942
+	 *
943
+	 * @param array $query_params @see
944
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
945
+	 * @return array @see
946
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
947
+	 * @throws ReflectionException
948
+	 * @throws ReflectionException
949
+	 */
950
+	public function alter_query_params_to_only_include_mine($query_params = [])
951
+	{
952
+		$wp_user_field_name = $this->wp_user_field_name();
953
+		if ($wp_user_field_name) {
954
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
955
+		}
956
+		return $query_params;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Returns the name of the field's name that points to the WP_User table
962
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
963
+	 * foreign key to the WP_User table)
964
+	 *
965
+	 * @return string|boolean string on success, boolean false when there is no
966
+	 * foreign key to the WP_User table
967
+	 * @throws ReflectionException
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function wp_user_field_name()
971
+	{
972
+		try {
973
+			if (! empty($this->_model_chain_to_wp_user)) {
974
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975
+				$last_model_name              = end($models_to_follow_to_wp_users);
976
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
978
+			} else {
979
+				$model_with_fk_to_wp_users = $this;
980
+				$model_chain_to_wp_user    = '';
981
+			}
982
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
984
+		} catch (EE_Error $e) {
985
+			return false;
986
+		}
987
+	}
988
+
989
+
990
+	/**
991
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
992
+	 * (or transiently-related model) has a foreign key to the wp_users table;
993
+	 * useful for finding if model objects of this type are 'owned' by the current user.
994
+	 * This is an empty string when the foreign key is on this model and when it isn't,
995
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
996
+	 * (or transiently-related model)
997
+	 *
998
+	 * @return string
999
+	 */
1000
+	public function model_chain_to_wp_user()
1001
+	{
1002
+		return $this->_model_chain_to_wp_user;
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1008
+	 * like how registrations don't have a foreign key to wp_users, but the
1009
+	 * events they are for are), or is unrelated to wp users.
1010
+	 * generally available
1011
+	 *
1012
+	 * @return boolean
1013
+	 */
1014
+	public function is_owned()
1015
+	{
1016
+		if ($this->model_chain_to_wp_user()) {
1017
+			return true;
1018
+		}
1019
+		try {
1020
+			$this->get_foreign_key_to('WP_User');
1021
+			return true;
1022
+		} catch (EE_Error $e) {
1023
+			return false;
1024
+		}
1025
+	}
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      @see
1034
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws ReflectionException
1048
+	 */
1049
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1050
+	{
1051
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1052
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions       = $columns_to_select === null
1054
+			? $this->_construct_default_select_sql($model_query_info)
1055
+			: '';
1056
+		if ($this->_custom_selections instanceof CustomSelects) {
1057
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058
+			$select_expressions .= $select_expressions
1059
+				? ', ' . $custom_expressions
1060
+				: $custom_expressions;
1061
+		}
1062
+
1063
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1064
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1070
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1071
+	 * method of including extra select information.
1072
+	 *
1073
+	 * @param array             $query_params
1074
+	 * @param null|array|string $columns_to_select
1075
+	 * @return null|CustomSelects
1076
+	 * @throws InvalidArgumentException
1077
+	 */
1078
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079
+	{
1080
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081
+			return null;
1082
+		}
1083
+		$selects = $query_params['extra_selects'] ?? $columns_to_select;
1084
+		$selects = is_string($selects)
1085
+			? explode(',', $selects)
1086
+			: $selects;
1087
+		return new CustomSelects($selects);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1093
+	 * but you can use the model query params to more easily
1094
+	 * take care of joins, field preparation etc.
1095
+	 *
1096
+	 * @param array  $query_params      @see
1097
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1098
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1099
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1100
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1101
+	 *                                  override this and set the select to "*", or a specific column name, like
1102
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1103
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1104
+	 *                                  the aliases used to refer to this selection, and values are to be
1105
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1106
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1107
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1108
+	 * @throws EE_Error
1109
+	 * @throws ReflectionException
1110
+	 */
1111
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1112
+	{
1113
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * For creating a custom select statement
1119
+	 *
1120
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1121
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1122
+	 *                                 SQL, and 1=>is the datatype
1123
+	 * @return string
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	private function _construct_select_from_input($columns_to_select)
1127
+	{
1128
+		if (is_array($columns_to_select)) {
1129
+			$select_sql_array = [];
1130
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype,
1139
+							$alias
1140
+						)
1141
+					);
1142
+				}
1143
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144
+					throw new EE_Error(
1145
+						sprintf(
1146
+							esc_html__(
1147
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1148
+								'event_espresso'
1149
+							),
1150
+							$selection_and_datatype[1],
1151
+							$selection_and_datatype[0],
1152
+							$alias,
1153
+							implode(', ', $this->_valid_wpdb_data_types)
1154
+						)
1155
+					);
1156
+				}
1157
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1158
+			}
1159
+			$columns_to_select_string = implode(', ', $select_sql_array);
1160
+		} else {
1161
+			$columns_to_select_string = $columns_to_select;
1162
+		}
1163
+		return $columns_to_select_string;
1164
+	}
1165
+
1166
+
1167
+	/**
1168
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1169
+	 *
1170
+	 * @return string
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function primary_key_name()
1174
+	{
1175
+		return $this->get_primary_key_field()->get_name();
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1181
+	 * If there is no primary key on this model, $id is treated as primary key string
1182
+	 *
1183
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1184
+	 * @return EE_Base_Class|mixed|null
1185
+	 * @throws EE_Error
1186
+	 * @throws ReflectionException
1187
+	 */
1188
+	public function get_one_by_ID($id)
1189
+	{
1190
+		// since entities with no ID can still have properties, we need to check the cache for them
1191
+		$cached_value = $this->get_from_entity_map($id);
1192
+		if ($cached_value) {
1193
+			return $cached_value;
1194
+		}
1195
+		// but if no cached property AND no id is passed, just return null
1196
+		if (empty($id)) {
1197
+			return null;
1198
+		}
1199
+		$model_object = $this->get_one(
1200
+			$this->alter_query_params_to_restrict_by_ID(
1201
+				$id,
1202
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203
+			)
1204
+		);
1205
+		$className    = $this->_get_class_name();
1206
+		if ($model_object instanceof $className) {
1207
+			// make sure valid objects get added to the entity map
1208
+			// so that the next call to this method doesn't trigger another trip to the db
1209
+			$this->add_to_entity_map($model_object);
1210
+		}
1211
+		return $model_object;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Alters query parameters to only get items with this ID are returned.
1217
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1218
+	 * or could just be a simple primary key ID
1219
+	 *
1220
+	 * @param int   $id
1221
+	 * @param array $query_params
1222
+	 * @return array of normal query params, @see
1223
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1224
+	 * @throws EE_Error
1225
+	 */
1226
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227
+	{
1228
+		if (! isset($query_params[0])) {
1229
+			$query_params[0] = [];
1230
+		}
1231
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1232
+		if ($conditions_from_id === null) {
1233
+			$query_params[0][ $this->primary_key_name() ] = $id;
1234
+		} else {
1235
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1236
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1237
+		}
1238
+		return $query_params;
1239
+	}
1240
+
1241
+
1242
+	/**
1243
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1244
+	 * array. If no item is found, null is returned.
1245
+	 *
1246
+	 * @param array $query_params like EEM_Base's $query_params variable.
1247
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1248
+	 * @throws EE_Error
1249
+	 * @throws ReflectionException
1250
+	 */
1251
+	public function get_one($query_params = [])
1252
+	{
1253
+		if (! is_array($query_params)) {
1254
+			EE_Error::doing_it_wrong(
1255
+				'EEM_Base::get_one',
1256
+				sprintf(
1257
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1258
+					gettype($query_params)
1259
+				),
1260
+				'4.6.0'
1261
+			);
1262
+			$query_params = [];
1263
+		}
1264
+		$query_params['limit'] = 1;
1265
+		$items                 = $this->get_all($query_params);
1266
+		if (empty($items)) {
1267
+			return null;
1268
+		}
1269
+		return array_shift($items);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Returns the next x number of items in sequence from the given value as
1275
+	 * found in the database matching the given query conditions.
1276
+	 *
1277
+	 * @param mixed $current_field_value    Value used for the reference point.
1278
+	 * @param null  $field_to_order_by      What field is used for the
1279
+	 *                                      reference point.
1280
+	 * @param int   $limit                  How many to return.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an array of
1283
+	 *                                      EE_Base_Class objects is returned,
1284
+	 *                                      otherwise you can indicate just the
1285
+	 *                                      columns you want returned.
1286
+	 * @return EE_Base_Class[]|array
1287
+	 * @throws EE_Error
1288
+	 * @throws ReflectionException
1289
+	 */
1290
+	public function next_x(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$limit = 1,
1294
+		$query_params = [],
1295
+		$columns_to_select = null
1296
+	) {
1297
+		return $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			$limit,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * Returns the previous x number of items in sequence from the given value
1310
+	 * as found in the database matching the given query conditions.
1311
+	 *
1312
+	 * @param mixed $current_field_value    Value used for the reference point.
1313
+	 * @param null  $field_to_order_by      What field is used for the
1314
+	 *                                      reference point.
1315
+	 * @param int   $limit                  How many to return.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an array of
1318
+	 *                                      EE_Base_Class objects is returned,
1319
+	 *                                      otherwise you can indicate just the
1320
+	 *                                      columns you want returned.
1321
+	 * @return EE_Base_Class[]|array
1322
+	 * @throws EE_Error
1323
+	 * @throws ReflectionException
1324
+	 */
1325
+	public function previous_x(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$limit = 1,
1329
+		$query_params = [],
1330
+		$columns_to_select = null
1331
+	) {
1332
+		return $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			$limit,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+	}
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the next item in sequence from the given value as found in the
1345
+	 * database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed $current_field_value    Value used for the reference point.
1348
+	 * @param null  $field_to_order_by      What field is used for the
1349
+	 *                                      reference point.
1350
+	 * @param array $query_params           Extra conditions on the query.
1351
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1352
+	 *                                      object is returned, otherwise you
1353
+	 *                                      can indicate just the columns you
1354
+	 *                                      want and a single array indexed by
1355
+	 *                                      the columns will be returned.
1356
+	 * @return EE_Base_Class|null|array()
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function next(
1361
+		$current_field_value,
1362
+		$field_to_order_by = null,
1363
+		$query_params = [],
1364
+		$columns_to_select = null
1365
+	) {
1366
+		$results = $this->_get_consecutive(
1367
+			$current_field_value,
1368
+			'>',
1369
+			$field_to_order_by,
1370
+			1,
1371
+			$query_params,
1372
+			$columns_to_select
1373
+		);
1374
+		return empty($results)
1375
+			? null
1376
+			: reset($results);
1377
+	}
1378
+
1379
+
1380
+	/**
1381
+	 * Returns the previous item in sequence from the given value as found in
1382
+	 * the database matching the given query conditions.
1383
+	 *
1384
+	 * @param mixed $current_field_value    Value used for the reference point.
1385
+	 * @param null  $field_to_order_by      What field is used for the
1386
+	 *                                      reference point.
1387
+	 * @param array $query_params           Extra conditions on the query.
1388
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1389
+	 *                                      object is returned, otherwise you
1390
+	 *                                      can indicate just the columns you
1391
+	 *                                      want and a single array indexed by
1392
+	 *                                      the columns will be returned.
1393
+	 * @return EE_Base_Class|null|array()
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function previous(
1398
+		$current_field_value,
1399
+		$field_to_order_by = null,
1400
+		$query_params = [],
1401
+		$columns_to_select = null
1402
+	) {
1403
+		$results = $this->_get_consecutive(
1404
+			$current_field_value,
1405
+			'<',
1406
+			$field_to_order_by,
1407
+			1,
1408
+			$query_params,
1409
+			$columns_to_select
1410
+		);
1411
+		return empty($results)
1412
+			? null
1413
+			: reset($results);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Returns the a consecutive number of items in sequence from the given
1419
+	 * value as found in the database matching the given query conditions.
1420
+	 *
1421
+	 * @param mixed  $current_field_value   Value used for the reference point.
1422
+	 * @param string $operand               What operand is used for the sequence.
1423
+	 * @param string $field_to_order_by     What field is used for the reference point.
1424
+	 * @param int    $limit                 How many to return.
1425
+	 * @param array  $query_params          Extra conditions on the query.
1426
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1427
+	 *                                      otherwise you can indicate just the columns you want returned.
1428
+	 * @return EE_Base_Class[]|array
1429
+	 * @throws EE_Error
1430
+	 * @throws ReflectionException
1431
+	 */
1432
+	protected function _get_consecutive(
1433
+		$current_field_value,
1434
+		$operand = '>',
1435
+		$field_to_order_by = null,
1436
+		$limit = 1,
1437
+		$query_params = [],
1438
+		$columns_to_select = null
1439
+	) {
1440
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1441
+		if (empty($field_to_order_by)) {
1442
+			if ($this->has_primary_key_field()) {
1443
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1444
+			} else {
1445
+				if (defined('WP_DEBUG') && WP_DEBUG) {
1446
+					throw new EE_Error(
1447
+						esc_html__(
1448
+							'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).',
1449
+							'event_espresso'
1450
+						)
1451
+					);
1452
+				}
1453
+				EE_Error::add_error(
1454
+					esc_html__('There was an error with the query.', 'event_espresso'),
1455
+					__FILE__,
1456
+					__FUNCTION__,
1457
+					__LINE__
1458
+				);
1459
+				return [];
1460
+			}
1461
+		}
1462
+		if (! is_array($query_params)) {
1463
+			EE_Error::doing_it_wrong(
1464
+				'EEM_Base::_get_consecutive',
1465
+				sprintf(
1466
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1467
+					gettype($query_params)
1468
+				),
1469
+				'4.6.0'
1470
+			);
1471
+			$query_params = [];
1472
+		}
1473
+		// let's add the where query param for consecutive look up.
1474
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1475
+		$query_params['limit']                 = $limit;
1476
+		// set direction
1477
+		$incoming_orderby         = isset($query_params['order_by'])
1478
+			? (array) $query_params['order_by']
1479
+			: [];
1480
+		$query_params['order_by'] = $operand === '>'
1481
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1482
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1483
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1484
+		if (empty($columns_to_select)) {
1485
+			return $this->get_all($query_params);
1486
+		}
1487
+		// getting just the fields
1488
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1489
+	}
1490
+
1491
+
1492
+	/**
1493
+	 * This sets the _timezone property after model object has been instantiated.
1494
+	 *
1495
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1496
+	 * @throws Exception
1497
+	 */
1498
+	public function set_timezone(?string $timezone = '')
1499
+	{
1500
+		if (! $timezone) {
1501
+			return;
1502
+		}
1503
+		$this->_timezone = $timezone;
1504
+		// note we need to loop through relations and set the timezone on those objects as well.
1505
+		foreach ($this->_model_relations as $relation) {
1506
+			$relation->set_timezone($timezone);
1507
+		}
1508
+		// and finally we do the same for any datetime fields
1509
+		foreach ($this->_fields as $field) {
1510
+			if ($field instanceof EE_Datetime_Field) {
1511
+				$field->set_timezone($timezone);
1512
+			}
1513
+		}
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * This just returns whatever is set for the current timezone.
1519
+	 *
1520
+	 * @access public
1521
+	 * @return string
1522
+	 * @throws Exception
1523
+	 */
1524
+	public function get_timezone()
1525
+	{
1526
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1527
+		if (empty($this->_timezone)) {
1528
+			foreach ($this->_fields as $field) {
1529
+				if ($field instanceof EE_Datetime_Field) {
1530
+					$this->set_timezone($field->get_timezone());
1531
+					break;
1532
+				}
1533
+			}
1534
+		}
1535
+		// if timezone STILL empty then return the default timezone for the site.
1536
+		if (empty($this->_timezone)) {
1537
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1538
+		}
1539
+		return $this->_timezone;
1540
+	}
1541
+
1542
+
1543
+	/**
1544
+	 * This returns the date formats set for the given field name and also ensures that
1545
+	 * $this->_timezone property is set correctly.
1546
+	 *
1547
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1548
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1549
+	 * @return array formats in an array with the date format first, and the time format last.
1550
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1551
+	 * @since 4.6.x
1552
+	 */
1553
+	public function get_formats_for($field_name, $pretty = false)
1554
+	{
1555
+		$field_settings = $this->field_settings_for($field_name);
1556
+		// if not a valid EE_Datetime_Field then throw error
1557
+		if (! $field_settings instanceof EE_Datetime_Field) {
1558
+			throw new EE_Error(
1559
+				sprintf(
1560
+					esc_html__(
1561
+						'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.',
1562
+						'event_espresso'
1563
+					),
1564
+					$field_name
1565
+				)
1566
+			);
1567
+		}
1568
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1569
+		// the field.
1570
+		$this->_timezone = $field_settings->get_timezone();
1571
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1572
+	}
1573
+
1574
+
1575
+	/**
1576
+	 * This returns the current time in a format setup for a query on this model.
1577
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1578
+	 * it will return:
1579
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1580
+	 *  NOW
1581
+	 *  - or a unix timestamp (equivalent to time())
1582
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1583
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1584
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1585
+	 *
1586
+	 * @param string $field_name       The field the current time is needed for.
1587
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1588
+	 *                                 formatted string matching the set format for the field in the set timezone will
1589
+	 *                                 be returned.
1590
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1591
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1592
+	 *                                 exception is triggered.
1593
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1594
+	 * @throws Exception
1595
+	 * @since 4.6.x
1596
+	 */
1597
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1598
+	{
1599
+		$formats  = $this->get_formats_for($field_name);
1600
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1601
+		if ($timestamp) {
1602
+			return $DateTime->format('U');
1603
+		}
1604
+		// not returning timestamp, so return formatted string in timezone.
1605
+		switch ($what) {
1606
+			case 'time':
1607
+				return $DateTime->format($formats[1]);
1608
+			case 'date':
1609
+				return $DateTime->format($formats[0]);
1610
+			default:
1611
+				return $DateTime->format(implode(' ', $formats));
1612
+		}
1613
+	}
1614
+
1615
+
1616
+	/**
1617
+	 * This receives a time string for a given field and ensures
1618
+	 * that it is set up to match what the internal settings for the model are.
1619
+	 * Returns a DateTime object.
1620
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1621
+	 * (functionally the equivalent of UTC+0).
1622
+	 * So when you send it in, whatever timezone string you include is ignored.
1623
+	 *
1624
+	 * @param string      $field_name      The field being setup.
1625
+	 * @param string      $timestring      The date time string being used.
1626
+	 * @param string      $incoming_format The format for the time string.
1627
+	 * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1628
+	 *                                     the blog.  If this is not the case, then it can be specified here.  If
1629
+	 *                                     incoming format is
1630
+	 *                                     'U', this is ignored.
1631
+	 * @return DbSafeDateTime
1632
+	 * @throws EE_Error
1633
+	 * @throws Exception
1634
+	 */
1635
+	public function convert_datetime_for_query(
1636
+		string $field_name,
1637
+		string $timestring,
1638
+		string $incoming_format,
1639
+		?string $timezone_string = ''
1640
+	): DbSafeDateTime {
1641
+		// just using this to ensure the timezone is set correctly internally
1642
+		$this->get_formats_for($field_name);
1643
+		// load EEH_DTT_Helper
1644
+		$timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647
+		return DbSafeDateTime::createFromDateTime($incomingDateTime);
1648
+	}
1649
+
1650
+
1651
+	/**
1652
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1653
+	 *
1654
+	 * @return EE_Table_Base[]
1655
+	 */
1656
+	public function get_tables()
1657
+	{
1658
+		return $this->_tables;
1659
+	}
1660
+
1661
+
1662
+	/**
1663
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1664
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1665
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1666
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1667
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1668
+	 * model object with EVT_ID = 1
1669
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1670
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1671
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1672
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1673
+	 * are not specified)
1674
+	 *
1675
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1676
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1677
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1678
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1679
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1680
+	 *                                         ID=34, we'd use this method as follows:
1681
+	 *                                         EEM_Transaction::instance()->update(
1682
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1683
+	 *                                         array(array('TXN_ID'=>34)));
1684
+	 * @param array   $query_params            @see
1685
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1686
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1687
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1688
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1689
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1690
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1691
+	 *                                         TRUE, it is assumed that you've already called
1692
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1693
+	 *                                         malicious javascript. However, if
1694
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1695
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1696
+	 *                                         and every other field, before insertion. We provide this parameter
1697
+	 *                                         because model objects perform their prepare_for_set function on all
1698
+	 *                                         their values, and so don't need to be called again (and in many cases,
1699
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1700
+	 *                                         prepare_for_set method...)
1701
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1702
+	 *                                         in this model's entity map according to $fields_n_values that match
1703
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1704
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1705
+	 *                                         could get out-of-sync with the database
1706
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1707
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1708
+	 *                                         bad)
1709
+	 * @throws EE_Error
1710
+	 * @throws ReflectionException
1711
+	 */
1712
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713
+	{
1714
+		if (! is_array($query_params)) {
1715
+			EE_Error::doing_it_wrong(
1716
+				'EEM_Base::update',
1717
+				sprintf(
1718
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1719
+					gettype($query_params)
1720
+				),
1721
+				'4.6.0'
1722
+			);
1723
+			$query_params = [];
1724
+		}
1725
+		/**
1726
+		 * Action called before a model update call has been made.
1727
+		 *
1728
+		 * @param EEM_Base $model
1729
+		 * @param array    $fields_n_values the updated fields and their new values
1730
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1731
+		 */
1732
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1733
+		/**
1734
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1735
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1736
+		 *
1737
+		 * @param array    $fields_n_values fields and their new values
1738
+		 * @param EEM_Base $model           the model being queried
1739
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1740
+		 */
1741
+		$fields_n_values = (array) apply_filters(
1742
+			'FHEE__EEM_Base__update__fields_n_values',
1743
+			$fields_n_values,
1744
+			$this,
1745
+			$query_params
1746
+		);
1747
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1748
+		// to do that, for each table, verify that it's PK isn't null.
1749
+		$tables = $this->get_tables();
1750
+		// 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
1751
+		// NOTE: we should make this code more efficient by NOT querying twice
1752
+		// before the real update, but that needs to first go through ALPHA testing
1753
+		// as it's dangerous. says Mike August 8 2014
1754
+		// we want to make sure the default_where strategy is ignored
1755
+		$this->_ignore_where_strategy = true;
1756
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1757
+		foreach ($wpdb_select_results as $wpdb_result) {
1758
+			// type cast stdClass as array
1759
+			$wpdb_result = (array) $wpdb_result;
1760
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761
+			if ($this->has_primary_key_field()) {
1762
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1763
+			} else {
1764
+				// 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)
1765
+				$main_table_pk_value = null;
1766
+			}
1767
+			// 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
1768
+			// 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
1769
+			if (count($tables) > 1) {
1770
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1771
+				// in that table, and so we'll want to insert one
1772
+				foreach ($tables as $table_obj) {
1773
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1774
+					// if there is no private key for this table on the results, it means there's no entry
1775
+					// in this table, right? so insert a row in the current table, using any fields available
1776
+					if (
1777
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
+						   && $wpdb_result[ $this_table_pk_column ])
1779
+					) {
1780
+						$success = $this->_insert_into_specific_table(
1781
+							$table_obj,
1782
+							$fields_n_values,
1783
+							$main_table_pk_value
1784
+						);
1785
+						// if we died here, report the error
1786
+						if (! $success) {
1787
+							return false;
1788
+						}
1789
+					}
1790
+				}
1791
+			}
1792
+			//              //and now check that if we have cached any models by that ID on the model, that
1793
+			//              //they also get updated properly
1794
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1795
+			//              if( $model_object ){
1796
+			//                  foreach( $fields_n_values as $field => $value ){
1797
+			//                      $model_object->set($field, $value);
1798
+			// let's make sure default_where strategy is followed now
1799
+			$this->_ignore_where_strategy = false;
1800
+		}
1801
+		// if we want to keep model objects in sync, AND
1802
+		// if this wasn't called from a model object (to update itself)
1803
+		// then we want to make sure we keep all the existing
1804
+		// model objects in sync with the db
1805
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1806
+			if ($this->has_primary_key_field()) {
1807
+				$model_objs_affected_ids = $this->get_col($query_params);
1808
+			} else {
1809
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1810
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1811
+				$model_objs_affected_ids     = [];
1812
+				foreach ($models_affected_key_columns as $row) {
1813
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1814
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1815
+				}
1816
+			}
1817
+			if (! $model_objs_affected_ids) {
1818
+				// wait wait wait- if nothing was affected let's stop here
1819
+				return 0;
1820
+			}
1821
+			foreach ($model_objs_affected_ids as $id) {
1822
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1823
+				if ($model_obj_in_entity_map) {
1824
+					foreach ($fields_n_values as $field => $new_value) {
1825
+						$model_obj_in_entity_map->set($field, $new_value);
1826
+					}
1827
+				}
1828
+			}
1829
+			// if there is a primary key on this model, we can now do a slight optimization
1830
+			if ($this->has_primary_key_field()) {
1831
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1832
+				$query_params = [
1833
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1834
+					'limit'                    => count($model_objs_affected_ids),
1835
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1836
+				];
1837
+			}
1838
+		}
1839
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1840
+
1841
+		// note: the following query doesn't use _construct_2nd_half_of_select_query()
1842
+		// because it doesn't accept LIMIT, ORDER BY, etc.
1843
+		$rows_affected = $this->_do_wpdb_query(
1844
+			'query',
1845
+			[
1846
+				"UPDATE " . $model_query_info->get_full_join_sql()
1847
+				. " SET " . $this->_construct_update_sql($fields_n_values)
1848
+				. $model_query_info->get_where_sql(),
1849
+			]
1850
+		);
1851
+
1852
+		/**
1853
+		 * Action called after a model update call has been made.
1854
+		 *
1855
+		 * @param EEM_Base $model
1856
+		 * @param array    $fields_n_values the updated fields and their new values
1857
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1858
+		 * @param int      $rows_affected
1859
+		 */
1860
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
+		return $rows_affected;// how many supposedly got updated
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1867
+	 * are the values of the field specified (or by default the primary key field)
1868
+	 * that matched the query params. Note that you should pass the name of the
1869
+	 * model FIELD, not the database table's column name.
1870
+	 *
1871
+	 * @param array  $query_params
1872
+	 * @param string $field_to_select
1873
+	 * @return array just like $wpdb->get_col()
1874
+	 * @throws EE_Error
1875
+	 * @throws ReflectionException
1876
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1877
+	 */
1878
+	public function get_col($query_params = [], $field_to_select = null)
1879
+	{
1880
+		if ($field_to_select) {
1881
+			$field = $this->field_settings_for($field_to_select);
1882
+		} elseif ($this->has_primary_key_field()) {
1883
+			$field = $this->get_primary_key_field();
1884
+		} else {
1885
+			$field_settings = $this->field_settings();
1886
+			// no primary key, just grab the first column
1887
+			$field = reset($field_settings);
1888
+			// don't need this array now
1889
+			unset($field_settings);
1890
+		}
1891
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892
+		$select_expressions = $field->get_qualified_column();
1893
+		$SQL                =
1894
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1895
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1896
+	}
1897
+
1898
+
1899
+	/**
1900
+	 * Returns a single column value for a single row from the database
1901
+	 *
1902
+	 * @param array  $query_params    @see
1903
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1904
+	 * @param string $field_to_select @see EEM_Base::get_col()
1905
+	 * @return string
1906
+	 * @throws EE_Error
1907
+	 * @throws ReflectionException
1908
+	 */
1909
+	public function get_var($query_params = [], $field_to_select = null)
1910
+	{
1911
+		$query_params['limit'] = 1;
1912
+		$col                   = $this->get_col($query_params, $field_to_select);
1913
+		if (! empty($col)) {
1914
+			return reset($col);
1915
+		}
1916
+		return null;
1917
+	}
1918
+
1919
+
1920
+	/**
1921
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1922
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1923
+	 * injection, but currently no further filtering is done
1924
+	 *
1925
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1926
+	 *                               be updated to in the DB
1927
+	 * @return string of SQL
1928
+	 * @throws EE_Error
1929
+	 * @global      $wpdb
1930
+	 */
1931
+	public function _construct_update_sql($fields_n_values)
1932
+	{
1933
+		/** @type WPDB $wpdb */
1934
+		global $wpdb;
1935
+		$cols_n_values = [];
1936
+		foreach ($fields_n_values as $field_name => $value) {
1937
+			$field_obj = $this->field_settings_for($field_name);
1938
+			// if the value is NULL, we want to assign the value to that.
1939
+			// wpdb->prepare doesn't really handle that properly
1940
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1941
+			$value_sql       = $prepared_value === null
1942
+				? 'NULL'
1943
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1945
+		}
1946
+		return implode(",", $cols_n_values);
1947
+	}
1948
+
1949
+
1950
+	/**
1951
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1952
+	 * Performs a HARD delete, meaning the database row should always be removed,
1953
+	 * not just have a flag field on it switched
1954
+	 * Wrapper for EEM_Base::delete_permanently()
1955
+	 *
1956
+	 * @param mixed $id
1957
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1958
+	 *                             ie: enforce referential integrity
1959
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1960
+	 * @return int the number of rows deleted
1961
+	 * @throws EE_Error
1962
+	 * @throws ReflectionException
1963
+	 */
1964
+	public function delete_permanently_by_ID($id, $block_deletes = true): int
1965
+	{
1966
+		return $this->delete_permanently(
1967
+			[
1968
+				[$this->get_primary_key_field()->get_name() => $id],
1969
+				'limit' => 1,
1970
+			],
1971
+			$block_deletes
1972
+		);
1973
+	}
1974
+
1975
+
1976
+	/**
1977
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1978
+	 * Wrapper for EEM_Base::delete()
1979
+	 *
1980
+	 * @param mixed $id
1981
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1982
+	 *                             ie: enforce referential integrity
1983
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1984
+	 * @return int the number of rows deleted
1985
+	 * @throws EE_Error
1986
+	 * @throws ReflectionException
1987
+	 */
1988
+	public function delete_by_ID($id, $block_deletes = true)
1989
+	{
1990
+		return $this->delete(
1991
+			[
1992
+				[$this->get_primary_key_field()->get_name() => $id],
1993
+				'limit' => 1,
1994
+			],
1995
+			$block_deletes
1996
+		);
1997
+	}
1998
+
1999
+
2000
+	/**
2001
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
2002
+	 * meaning if the model has a field that indicates its been "trashed" or
2003
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
2004
+	 *
2005
+	 * @param array   $query_params
2006
+	 * @param boolean $block_deletes whether to allow related model objects to block (prevent) this deletion
2007
+	 *                               ie: enforce referential integrity
2008
+	 *                               It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2009
+	 * @return int how many rows got deleted
2010
+	 * @throws EE_Error
2011
+	 * @throws ReflectionException
2012
+	 * @see EEM_Base::delete_permanently
2013
+	 */
2014
+	public function delete($query_params, $block_deletes = true)
2015
+	{
2016
+		return $this->delete_permanently($query_params, $block_deletes);
2017
+	}
2018
+
2019
+
2020
+	/**
2021
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
2022
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2023
+	 * as archived, not actually deleted
2024
+	 *
2025
+	 * @param array   $query_params
2026
+	 * @param boolean $block_deletes  whether to allow related model objects to block (prevent) this deletion
2027
+	 *                                ie: enforce referential integrity
2028
+	 *                                It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2029
+	 * @return int how many rows got deleted
2030
+	 * @throws EE_Error
2031
+	 * @throws ReflectionException
2032
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2033
+	 */
2034
+	public function delete_permanently($query_params, $block_deletes = true): int
2035
+	{
2036
+		/**
2037
+		 * Action called just before performing a real deletion query. You can use the
2038
+		 * model and its $query_params to find exactly which items will be deleted
2039
+		 *
2040
+		 * @param EEM_Base $model
2041
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2042
+		 * @param bool     $block_deletes @see param description in method phpdoc block.
2043
+		 */
2044
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $block_deletes);
2045
+		// some MySQL databases may be running safe mode, which may restrict
2046
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2047
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2048
+		// to delete them
2049
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2050
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $block_deletes);
2051
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2052
+			$columns_and_ids_for_deleting
2053
+		);
2054
+		/**
2055
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2056
+		 * see php doc blocks for more details
2057
+		 *
2058
+		 * @param EEM_Base $this                         The model instance being acted on.
2059
+		 * @param array    $query_params                 The incoming array of query parameters influencing what gets deleted.
2060
+		 * @param bool     $block_deletes                @see param description in method phpdoc block.
2061
+		 * @param array    $columns_and_ids_for_deleting An array indicating what entities will get removed as
2062
+		 *                                               derived from the incoming query parameters.
2063
+		 * @see details on the structure of this array in the phpdocs for the `_get_ids_for_delete_method`
2064
+		 */
2065
+		do_action(
2066
+			'AHEE__EEM_Base__delete__before_query',
2067
+			$this,
2068
+			$query_params,
2069
+			$block_deletes,
2070
+			$columns_and_ids_for_deleting
2071
+		);
2072
+		$rows_deleted = 0;
2073
+		if ($deletion_where_query_part) {
2074
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2075
+			$table_aliases    = array_keys($this->_tables);
2076
+			$SQL              = "DELETE "
2077
+								. implode(", ", $table_aliases)
2078
+								. " FROM "
2079
+								. $model_query_info->get_full_join_sql()
2080
+								. " WHERE "
2081
+								. $deletion_where_query_part;
2082
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2083
+		}
2084
+
2085
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2086
+		// there was no error with the delete query.
2087
+		if (
2088
+			$this->has_primary_key_field()
2089
+			&& $rows_deleted !== false
2090
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2091
+		) {
2092
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2093
+			foreach ($ids_for_removal as $id) {
2094
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2095
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2096
+				}
2097
+			}
2098
+
2099
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2100
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2101
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2102
+			// (although it is possible).
2103
+			// Note this can be skipped by using the provided filter and returning false.
2104
+			if (
2105
+				apply_filters(
2106
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2107
+					! $this instanceof EEM_Extra_Meta,
2108
+					$this
2109
+				)
2110
+			) {
2111
+				EEM_Extra_Meta::instance()->delete_permanently(
2112
+					[
2113
+						0 => [
2114
+							'EXM_type' => $this->get_this_model_name(),
2115
+							'OBJ_ID'   => [
2116
+								'IN',
2117
+								$ids_for_removal,
2118
+							],
2119
+						],
2120
+					]
2121
+				);
2122
+			}
2123
+		}
2124
+
2125
+		/**
2126
+		 * Action called just after performing a real deletion query. Although at this point the
2127
+		 * items should have been deleted
2128
+		 *
2129
+		 * @param EEM_Base $model
2130
+		 * @param array $query_params
2131
+		 * @param int   $rows_deleted
2132
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2133
+		 */
2134
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2135
+		return (int) $rows_deleted;// how many supposedly got deleted
2136
+	}
2137
+
2138
+
2139
+	/**
2140
+	 * Checks all the relations that throw error messages when there are blocking related objects
2141
+	 * for related model objects. If there are any related model objects on those relations,
2142
+	 * adds an EE_Error, and return true
2143
+	 *
2144
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2145
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2146
+	 *                                                 should be ignored when determining whether there are related
2147
+	 *                                                 model objects which block this model object's deletion. Useful
2148
+	 *                                                 if you know A is related to B and are considering deleting A,
2149
+	 *                                                 but want to see if A has any other objects blocking its deletion
2150
+	 *                                                 before removing the relation between A and B
2151
+	 * @return boolean
2152
+	 * @throws EE_Error
2153
+	 * @throws ReflectionException
2154
+	 */
2155
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2156
+	{
2157
+		// first, if $ignore_this_model_obj was supplied, get its model
2158
+		$ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2159
+			? $ignore_this_model_obj->get_model()
2160
+			: null;
2161
+		// now check all the relations of $this_model_obj_or_id and see if there
2162
+		// are any related model objects blocking it?
2163
+		$is_blocked = false;
2164
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2165
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2166
+				// if $ignore_this_model_obj was supplied, then for the query
2167
+				// on that model needs to be told to ignore $ignore_this_model_obj
2168
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2169
+					$related_model_objects = $relation_obj->get_all_related(
2170
+						$this_model_obj_or_id,
2171
+						[
2172
+							[
2173
+								$ignored_model->get_primary_key_field()->get_name() => [
2174
+									'!=',
2175
+									$ignore_this_model_obj->ID(),
2176
+								],
2177
+							],
2178
+						]
2179
+					);
2180
+				} else {
2181
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2182
+				}
2183
+				if ($related_model_objects) {
2184
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2185
+					$is_blocked = true;
2186
+				}
2187
+			}
2188
+		}
2189
+		return $is_blocked;
2190
+	}
2191
+
2192
+
2193
+	/**
2194
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2195
+	 *
2196
+	 * @param array $row_results_for_deleting
2197
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
2198
+	 *                             ie: enforce referential integrity
2199
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2200
+	 * @return array               The shape of this array depends on whether the model `has_primary_key_field` or not.
2201
+	 *                             If the model DOES have a primary_key_field, then the array will be a simple single
2202
+	 *                             dimension array where the key is the fully qualified primary key column and
2203
+	 *                             the value is an array of ids that will be deleted.
2204
+	 *                             Example:
2205
+	 *                              [ 'Event.EVT_ID' => [ 1,2,3 ]]
2206
+	 *                             If the model DOES NOT have a primary_key_field, then the array will be a
2207
+	 *                             two-dimensional array where each element is a group of columns and values that get deleted.
2208
+	 *                             Example:
2209
+	 *                              [
2210
+	 *                                  0 => [
2211
+	 *                                      'Term_Relationship.object_id' => 1
2212
+	 *                                      'Term_Relationship.term_taxonomy_id' => 5
2213
+	 *                                  ],
2214
+	 *                                  1 => [
2215
+	 *                                      'Term_Relationship.object_id' => 1
2216
+	 *                                      'Term_Relationship.term_taxonomy_id' => 6
2217
+	 *                                  ]
2218
+	 *                              ]
2219
+	 * @throws EE_Error
2220
+	 * @throws ReflectionException
2221
+	 */
2222
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $block_deletes = true)
2223
+	{
2224
+		$ids_to_delete_indexed_by_column = [];
2225
+		if ($this->has_primary_key_field()) {
2226
+			$primary_table = $this->_get_main_table();
2227
+			// following lines are commented out because the variables were not being used
2228
+			// not deleting because unsure if calls were intentionally causing side effects
2229
+			// $primary_table_pk_field          =
2230
+			//     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2231
+			// $other_tables                    = $this->_get_other_tables();
2232
+			$ids_to_delete_indexed_by_column = $query = [];
2233
+			foreach ($row_results_for_deleting as $item_to_delete) {
2234
+				// before we mark this item for deletion,
2235
+				// make sure there's no related entities blocking its deletion (if we're checking)
2236
+				if (
2237
+					$block_deletes
2238
+					&& $this->delete_is_blocked_by_related_models(
2239
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2240
+					)
2241
+				) {
2242
+					continue;
2243
+				}
2244
+				// primary table deletes
2245
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2246
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2247
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2248
+				}
2249
+			}
2250
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2251
+			$fields = $this->get_combined_primary_key_fields();
2252
+			foreach ($row_results_for_deleting as $item_to_delete) {
2253
+				$ids_to_delete_indexed_by_column_for_row = [];
2254
+				foreach ($fields as $cpk_field) {
2255
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2256
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2257
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2258
+					}
2259
+				}
2260
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2261
+			}
2262
+		} else {
2263
+			// so there's no primary key and no combined key...
2264
+			// sorry, can't help you
2265
+			throw new EE_Error(
2266
+				sprintf(
2267
+					esc_html__(
2268
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2269
+						"event_espresso"
2270
+					),
2271
+					get_class($this)
2272
+				)
2273
+			);
2274
+		}
2275
+		return $ids_to_delete_indexed_by_column;
2276
+	}
2277
+
2278
+
2279
+	/**
2280
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2281
+	 * the corresponding query_part for the query performing the deletion.
2282
+	 *
2283
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2284
+	 * @return string
2285
+	 * @throws EE_Error
2286
+	 */
2287
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2288
+	{
2289
+		$query_part = '';
2290
+		if (empty($ids_to_delete_indexed_by_column)) {
2291
+			return $query_part;
2292
+		} elseif ($this->has_primary_key_field()) {
2293
+			$query = [];
2294
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2295
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2296
+			}
2297
+			$query_part = ! empty($query)
2298
+				? implode(' AND ', $query)
2299
+				: $query_part;
2300
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2301
+			$ways_to_identify_a_row = [];
2302
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2303
+				$values_for_each_combined_primary_key_for_a_row = [];
2304
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2305
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2306
+				}
2307
+				$ways_to_identify_a_row[] = '('
2308
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2309
+											. ')';
2310
+			}
2311
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2312
+		}
2313
+		return $query_part;
2314
+	}
2315
+
2316
+
2317
+	/**
2318
+	 * Gets the model field by the fully qualified name
2319
+	 *
2320
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2321
+	 * @return EE_Model_Field_Base
2322
+	 * @throws EE_Error
2323
+	 * @throws EE_Error
2324
+	 */
2325
+	public function get_field_by_column($qualified_column_name)
2326
+	{
2327
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2328
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2329
+				return $field_obj;
2330
+			}
2331
+		}
2332
+		throw new EE_Error(
2333
+			sprintf(
2334
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2335
+				$this->get_this_model_name(),
2336
+				$qualified_column_name
2337
+			)
2338
+		);
2339
+	}
2340
+
2341
+
2342
+	/**
2343
+	 * Count all the rows that match criteria the model query params.
2344
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2345
+	 * column
2346
+	 *
2347
+	 * @param array  $query_params   @see
2348
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2349
+	 * @param string $field_to_count field on model to count by (not column name)
2350
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2351
+	 *                               that by the setting $distinct to TRUE;
2352
+	 * @return int
2353
+	 * @throws EE_Error
2354
+	 * @throws ReflectionException
2355
+	 */
2356
+	public function count($query_params = [], $field_to_count = '', $distinct = false)
2357
+	{
2358
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2359
+		if ($field_to_count) {
2360
+			$field_obj       = $this->field_settings_for($field_to_count);
2361
+			$column_to_count = $field_obj->get_qualified_column();
2362
+		} elseif ($this->has_primary_key_field()) {
2363
+			$pk_field_obj    = $this->get_primary_key_field();
2364
+			$column_to_count = $pk_field_obj->get_qualified_column();
2365
+		} else {
2366
+			// there's no primary key
2367
+			// if we're counting distinct items, and there's no primary key,
2368
+			// we need to list out the columns for distinction;
2369
+			// otherwise we can just use star
2370
+			if ($distinct) {
2371
+				$columns_to_use = [];
2372
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2373
+					$columns_to_use[] = $field_obj->get_qualified_column();
2374
+				}
2375
+				$column_to_count = implode(',', $columns_to_use);
2376
+			} else {
2377
+				$column_to_count = '*';
2378
+			}
2379
+		}
2380
+		$column_to_count = $distinct
2381
+			? "DISTINCT " . $column_to_count
2382
+			: $column_to_count;
2383
+		$SQL             =
2384
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2385
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2391
+	 *
2392
+	 * @param array  $query_params @see
2393
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2394
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2395
+	 * @return float
2396
+	 * @throws EE_Error
2397
+	 * @throws ReflectionException
2398
+	 */
2399
+	public function sum($query_params, $field_to_sum = null)
2400
+	{
2401
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2402
+		if ($field_to_sum) {
2403
+			$field_obj = $this->field_settings_for($field_to_sum);
2404
+		} else {
2405
+			$field_obj = $this->get_primary_key_field();
2406
+		}
2407
+		$column_to_count = $field_obj->get_qualified_column();
2408
+		$SQL             =
2409
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2410
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2411
+		$data_type       = $field_obj->get_wpdb_data_type();
2412
+		if ($data_type === '%d' || $data_type === '%s') {
2413
+			return (float) $return_value;
2414
+		}
2415
+		// must be %f
2416
+		return (float) $return_value;
2417
+	}
2418
+
2419
+
2420
+	/**
2421
+	 * Just calls the specified method on $wpdb with the given arguments
2422
+	 * Consolidates a little extra error handling code
2423
+	 *
2424
+	 * @param string $wpdb_method
2425
+	 * @param array  $arguments_to_provide
2426
+	 * @return mixed
2427
+	 * @throws EE_Error
2428
+	 * @global wpdb  $wpdb
2429
+	 */
2430
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2431
+	{
2432
+		// if we're in maintenance mode level 2, DON'T run any queries
2433
+		// because level 2 indicates the database needs updating and
2434
+		// is probably out of sync with the code
2435
+		if (DbStatus::isOffline()) {
2436
+			throw new RuntimeException(
2437
+				esc_html__(
2438
+					"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.",
2439
+					"event_espresso"
2440
+				)
2441
+			);
2442
+		}
2443
+		/** @type WPDB $wpdb */
2444
+		global $wpdb;
2445
+		if (! method_exists($wpdb, $wpdb_method)) {
2446
+			throw new DomainException(
2447
+				sprintf(
2448
+					esc_html__(
2449
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2450
+						'event_espresso'
2451
+					),
2452
+					$wpdb_method
2453
+				)
2454
+			);
2455
+		}
2456
+		$old_show_errors_value = $wpdb->show_errors;
2457
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2458
+			$wpdb->show_errors(false);
2459
+		}
2460
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2461
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2462
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2463
+			$wpdb->show_errors($old_show_errors_value);
2464
+			if (! empty($wpdb->last_error)) {
2465
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2466
+			}
2467
+			if ($result === false) {
2468
+				throw new EE_Error(
2469
+					sprintf(
2470
+						esc_html__(
2471
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2472
+							'event_espresso'
2473
+						),
2474
+						$wpdb_method,
2475
+						var_export($arguments_to_provide, true)
2476
+					)
2477
+				);
2478
+			}
2479
+		} elseif ($result === false) {
2480
+			EE_Error::add_error(
2481
+				sprintf(
2482
+					esc_html__(
2483
+						'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"',
2484
+						'event_espresso'
2485
+					),
2486
+					$wpdb_method,
2487
+					var_export($arguments_to_provide, true),
2488
+					$wpdb->last_error
2489
+				),
2490
+				__FILE__,
2491
+				__FUNCTION__,
2492
+				__LINE__
2493
+			);
2494
+		}
2495
+		return $result;
2496
+	}
2497
+
2498
+
2499
+	/**
2500
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2501
+	 * and if there's an error tries to verify the DB is correct. Uses
2502
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2503
+	 * we should try to fix the EE core db, the addons, or just give up
2504
+	 *
2505
+	 * @param string $wpdb_method
2506
+	 * @param array  $arguments_to_provide
2507
+	 * @return mixed
2508
+	 */
2509
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2510
+	{
2511
+		/** @type WPDB $wpdb */
2512
+		global $wpdb;
2513
+		$wpdb->last_error = null;
2514
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2515
+		// was there an error running the query? but we don't care on new activations
2516
+		// (we're going to setup the DB anyway on new activations)
2517
+		if (
2518
+			($result === false || ! empty($wpdb->last_error))
2519
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2520
+		) {
2521
+			switch (EEM_Base::$_db_verification_level) {
2522
+				case EEM_Base::db_verified_none:
2523
+					// let's double-check core's DB
2524
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2525
+					break;
2526
+				case EEM_Base::db_verified_core:
2527
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2528
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2529
+					break;
2530
+				case EEM_Base::db_verified_addons:
2531
+					// ummmm... you in trouble
2532
+					return $result;
2533
+			}
2534
+			if (! empty($error_message)) {
2535
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2536
+				trigger_error($error_message);
2537
+			}
2538
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2539
+		}
2540
+		return $result;
2541
+	}
2542
+
2543
+
2544
+	/**
2545
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2546
+	 * EEM_Base::$_db_verification_level
2547
+	 *
2548
+	 * @param string $wpdb_method
2549
+	 * @param array  $arguments_to_provide
2550
+	 * @return string
2551
+	 * @throws EE_Error
2552
+	 * @throws ReflectionException
2553
+	 */
2554
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2555
+	{
2556
+		/** @type WPDB $wpdb */
2557
+		global $wpdb;
2558
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2559
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2560
+		$error_message                    = sprintf(
2561
+			esc_html__(
2562
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2563
+				'event_espresso'
2564
+			),
2565
+			$wpdb->last_error,
2566
+			$wpdb_method,
2567
+			wp_json_encode($arguments_to_provide)
2568
+		);
2569
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2570
+		return $error_message;
2571
+	}
2572
+
2573
+
2574
+	/**
2575
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2576
+	 * EEM_Base::$_db_verification_level
2577
+	 *
2578
+	 * @param $wpdb_method
2579
+	 * @param $arguments_to_provide
2580
+	 * @return string
2581
+	 * @throws EE_Error
2582
+	 * @throws ReflectionException
2583
+	 */
2584
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2585
+	{
2586
+		/** @type WPDB $wpdb */
2587
+		global $wpdb;
2588
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2589
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2590
+		$error_message                    = sprintf(
2591
+			esc_html__(
2592
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2593
+				'event_espresso'
2594
+			),
2595
+			$wpdb->last_error,
2596
+			$wpdb_method,
2597
+			wp_json_encode($arguments_to_provide)
2598
+		);
2599
+		EE_System::instance()->initialize_addons();
2600
+		return $error_message;
2601
+	}
2602
+
2603
+
2604
+	/**
2605
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2606
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2607
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2608
+	 * ..."
2609
+	 *
2610
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2611
+	 * @return string
2612
+	 */
2613
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2614
+	{
2615
+		return " FROM " . $model_query_info->get_full_join_sql() .
2616
+			   $model_query_info->get_where_sql() .
2617
+			   $model_query_info->get_group_by_sql() .
2618
+			   $model_query_info->get_having_sql() .
2619
+			   $model_query_info->get_order_by_sql() .
2620
+			   $model_query_info->get_limit_sql();
2621
+	}
2622
+
2623
+
2624
+	/**
2625
+	 * Set to easily debug the next X queries ran from this model.
2626
+	 *
2627
+	 * @param int $count
2628
+	 */
2629
+	public function show_next_x_db_queries($count = 1)
2630
+	{
2631
+		$this->_show_next_x_db_queries = $count;
2632
+	}
2633
+
2634
+
2635
+	/**
2636
+	 * @param $sql_query
2637
+	 */
2638
+	public function show_db_query_if_previously_requested($sql_query)
2639
+	{
2640
+		if ($this->_show_next_x_db_queries > 0) {
2641
+			$left = is_admin() ? '12rem' : '2rem';
2642
+			echo "
2643 2643
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2644 2644
                 " . esc_html($sql_query) . "
2645 2645
             </div>";
2646
-            $this->_show_next_x_db_queries--;
2647
-        }
2648
-    }
2649
-
2650
-
2651
-    /**
2652
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2653
-     * There are the 3 cases:
2654
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2655
-     * $otherModelObject has no ID, it is first saved.
2656
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2657
-     * has no ID, it is first saved.
2658
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2659
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2660
-     * join table
2661
-     *
2662
-     * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2663
-     * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2664
-     * @param string            $relationName                     , key in EEM_Base::_relations
2665
-     *                                                            an attendee to a group, you also want to specify
2666
-     *                                                            which role they will have in that group. So you would
2667
-     *                                                            use this parameter to specify
2668
-     *                                                            array('role-column-name'=>'role-id')
2669
-     * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2670
-     *                                                            relation to for relation to methods that allow you to
2671
-     *                                                            further specify extra columns to join by (such as
2672
-     *                                                            HABTM).  Keep in mind that the only acceptable
2673
-     *                                                            query_params is strict "col" => "value" pairs because
2674
-     *                                                            these will be inserted in any new rows created as
2675
-     *                                                            well.
2676
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2677
-     * @throws EE_Error
2678
-     */
2679
-    public function add_relationship_to(
2680
-        $id_or_obj,
2681
-        $other_model_id_or_obj,
2682
-        $relationName,
2683
-        $extra_join_model_fields_n_values = []
2684
-    ) {
2685
-        $relation_obj = $this->related_settings_for($relationName);
2686
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2687
-    }
2688
-
2689
-
2690
-    /**
2691
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2692
-     * There are the 3 cases:
2693
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2694
-     * error
2695
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2696
-     * an error
2697
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2698
-     *
2699
-     * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2700
-     * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2701
-     * @param string            $relationName          key in EEM_Base::_relations
2702
-     * @param array|null        $where_query           This allows you to enter further query params for the relation
2703
-     *                                                 to for relation to methods that allow you to further specify
2704
-     *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2705
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2706
-     *                                                 because these will be inserted in any new rows created as well.
2707
-     * @return EE_Base_Class
2708
-     * @throws EE_Error
2709
-     */
2710
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2711
-    {
2712
-        $relation_obj = $this->related_settings_for($relationName);
2713
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2714
-    }
2715
-
2716
-
2717
-    /**
2718
-     * @param mixed       $id_or_obj
2719
-     * @param string      $relationName
2720
-     * @param array|null  $where_query_params
2721
-     * @return EE_Base_Class[]
2722
-     * @throws EE_Error
2723
-     * @throws ReflectionException
2724
-     */
2725
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2726
-    {
2727
-        $relation_obj = $this->related_settings_for($relationName);
2728
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * Gets all the related items of the specified $model_name, using $query_params.
2734
-     * Note: by default, we remove the "default query params"
2735
-     * because we want to get even deleted items etc.
2736
-     *
2737
-     * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2738
-     * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2739
-     * @param array|null  $query_params @see
2740
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2741
-     * @return EE_Base_Class[]
2742
-     * @throws EE_Error
2743
-     * @throws ReflectionException
2744
-     */
2745
-    public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2746
-    {
2747
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2748
-        $relation_settings = $this->related_settings_for($model_name);
2749
-        return $relation_settings->get_all_related($model_obj, $query_params);
2750
-    }
2751
-
2752
-
2753
-    /**
2754
-     * Deletes all the model objects across the relation indicated by $model_name
2755
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2756
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2757
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2758
-     *
2759
-     * @param EE_Base_Class|int|string $id_or_obj
2760
-     * @param string                   $model_name
2761
-     * @param array|null               $query_params
2762
-     * @return int how many deleted
2763
-     * @throws EE_Error
2764
-     * @throws ReflectionException
2765
-     */
2766
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2767
-    {
2768
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2769
-        $relation_settings = $this->related_settings_for($model_name);
2770
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2771
-    }
2772
-
2773
-
2774
-    /**
2775
-     * Hard deletes all the model objects across the relation indicated by $model_name
2776
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2777
-     * the model objects can't be hard deleted because of blocking related model objects,
2778
-     * just does a soft-delete on them instead.
2779
-     *
2780
-     * @param EE_Base_Class|int|string $id_or_obj
2781
-     * @param string                   $model_name
2782
-     * @param array|null               $query_params
2783
-     * @return int how many deleted
2784
-     * @throws EE_Error
2785
-     * @throws ReflectionException
2786
-     */
2787
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2788
-    {
2789
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2790
-        $relation_settings = $this->related_settings_for($model_name);
2791
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2792
-    }
2793
-
2794
-
2795
-    /**
2796
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2797
-     * unless otherwise specified in the $query_params
2798
-     *
2799
-     * @param EE_Base_Class|int|string $id_or_obj
2800
-     * @param string                   $model_name     like 'Event', or 'Registration'
2801
-     * @param array|null               $query_params   @see
2802
-     *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2803
-     * @param string                   $field_to_count name of field to count by. By default, uses primary key
2804
-     * @param bool                     $distinct       if we want to only count the distinct values for the column then
2805
-     *                                                 you can trigger that by the setting $distinct to TRUE;
2806
-     * @return int
2807
-     * @throws EE_Error
2808
-     * @throws ReflectionException
2809
-     */
2810
-    public function count_related(
2811
-        $id_or_obj,
2812
-        $model_name,
2813
-        $query_params = [],
2814
-        $field_to_count = null,
2815
-        $distinct = false
2816
-    ) {
2817
-        $related_model = $this->get_related_model_obj($model_name);
2818
-        // we're just going to use the query params on the related model's normal get_all query,
2819
-        // except add a condition to say to match the current mod
2820
-        if (! isset($query_params['default_where_conditions'])) {
2821
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2822
-        }
2823
-        $this_model_name                                                 = $this->get_this_model_name();
2824
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2825
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2826
-        return $related_model->count($query_params, $field_to_count, $distinct);
2827
-    }
2828
-
2829
-
2830
-    /**
2831
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2832
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2833
-     *
2834
-     * @param EE_Base_Class|int|string $id_or_obj
2835
-     * @param string                   $model_name   like 'Event', or 'Registration'
2836
-     * @param array|null               $query_params @see
2837
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2838
-     * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2839
-     * @return float
2840
-     * @throws EE_Error
2841
-     * @throws ReflectionException
2842
-     */
2843
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2844
-    {
2845
-        $related_model = $this->get_related_model_obj($model_name);
2846
-        if (! is_array($query_params)) {
2847
-            EE_Error::doing_it_wrong(
2848
-                'EEM_Base::sum_related',
2849
-                sprintf(
2850
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2851
-                    gettype($query_params)
2852
-                ),
2853
-                '4.6.0'
2854
-            );
2855
-            $query_params = [];
2856
-        }
2857
-        // we're just going to use the query params on the related model's normal get_all query,
2858
-        // except add a condition to say to match the current mod
2859
-        if (! isset($query_params['default_where_conditions'])) {
2860
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2861
-        }
2862
-        $this_model_name                                                 = $this->get_this_model_name();
2863
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2864
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2865
-        return $related_model->sum($query_params, $field_to_sum);
2866
-    }
2867
-
2868
-
2869
-    /**
2870
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2871
-     * $modelObject
2872
-     *
2873
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2874
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2875
-     * @param array|null          $query_params     @see
2876
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2877
-     * @return EE_Base_Class
2878
-     * @throws EE_Error
2879
-     * @throws ReflectionException
2880
-     */
2881
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2882
-    {
2883
-        $query_params['limit'] = 1;
2884
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2885
-        if ($results) {
2886
-            return array_shift($results);
2887
-        }
2888
-        return null;
2889
-    }
2890
-
2891
-
2892
-    /**
2893
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2894
-     *
2895
-     * @return string
2896
-     */
2897
-    public function get_this_model_name()
2898
-    {
2899
-        return str_replace("EEM_", "", get_class($this));
2900
-    }
2901
-
2902
-
2903
-    /**
2904
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2905
-     *
2906
-     * @return EE_Any_Foreign_Model_Name_Field
2907
-     * @throws EE_Error
2908
-     */
2909
-    public function get_field_containing_related_model_name()
2910
-    {
2911
-        foreach ($this->field_settings(true) as $field) {
2912
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2913
-                $field_with_model_name = $field;
2914
-            }
2915
-        }
2916
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2917
-            throw new EE_Error(
2918
-                sprintf(
2919
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2920
-                    $this->get_this_model_name()
2921
-                )
2922
-            );
2923
-        }
2924
-        return $field_with_model_name;
2925
-    }
2926
-
2927
-
2928
-    /**
2929
-     * Inserts a new entry into the database, for each table.
2930
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2931
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2932
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2933
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2934
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2935
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2936
-     *
2937
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2938
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2939
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2940
-     *                              of EEM_Base)
2941
-     * @return int|string new primary key on main table that got inserted
2942
-     * @throws EE_Error
2943
-     * @throws ReflectionException
2944
-     */
2945
-    public function insert($field_n_values)
2946
-    {
2947
-        /**
2948
-         * Filters the fields and their values before inserting an item using the models
2949
-         *
2950
-         * @param array    $fields_n_values keys are the fields and values are their new values
2951
-         * @param EEM_Base $model           the model used
2952
-         */
2953
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2954
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2955
-            $main_table = $this->_get_main_table();
2956
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2957
-            if ($new_id !== false) {
2958
-                foreach ($this->_get_other_tables() as $other_table) {
2959
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2960
-                }
2961
-            }
2962
-            /**
2963
-             * Done just after attempting to insert a new model object
2964
-             *
2965
-             * @param EEM_Base $model           used
2966
-             * @param array    $fields_n_values fields and their values
2967
-             * @param int|string the              ID of the newly-inserted model object
2968
-             */
2969
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2970
-            return $new_id;
2971
-        }
2972
-        return false;
2973
-    }
2974
-
2975
-
2976
-    /**
2977
-     * Checks that the result would satisfy the unique indexes on this model
2978
-     *
2979
-     * @param array  $field_n_values
2980
-     * @param string $action
2981
-     * @return boolean
2982
-     * @throws EE_Error
2983
-     * @throws ReflectionException
2984
-     */
2985
-    protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2986
-    {
2987
-        foreach ($this->unique_indexes() as $index_name => $index) {
2988
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2989
-            if ($this->exists([$uniqueness_where_params])) {
2990
-                EE_Error::add_error(
2991
-                    sprintf(
2992
-                        esc_html__(
2993
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2994
-                            "event_espresso"
2995
-                        ),
2996
-                        $action,
2997
-                        $this->_get_class_name(),
2998
-                        $index_name,
2999
-                        implode(",", $index->field_names()),
3000
-                        http_build_query($uniqueness_where_params)
3001
-                    ),
3002
-                    __FILE__,
3003
-                    __FUNCTION__,
3004
-                    __LINE__
3005
-                );
3006
-                return false;
3007
-            }
3008
-        }
3009
-        return true;
3010
-    }
3011
-
3012
-
3013
-    /**
3014
-     * Checks the database for an item that conflicts (ie, if this item were
3015
-     * saved to the DB would break some uniqueness requirement, like a primary key
3016
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
3017
-     * can be either an EE_Base_Class or an array of fields n values
3018
-     *
3019
-     * @param EE_Base_Class|array $obj_or_fields_array
3020
-     * @param boolean             $include_primary_key whether to use the model object's primary key
3021
-     *                                                 when looking for conflicts
3022
-     *                                                 (ie, if false, we ignore the model object's primary key
3023
-     *                                                 when finding "conflicts". If true, it's also considered).
3024
-     *                                                 Only works for INT primary key,
3025
-     *                                                 STRING primary keys cannot be ignored
3026
-     * @return EE_Base_Class|array
3027
-     * @throws EE_Error
3028
-     * @throws ReflectionException
3029
-     */
3030
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3031
-    {
3032
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
3033
-            $fields_n_values = $obj_or_fields_array->model_field_array();
3034
-        } elseif (is_array($obj_or_fields_array)) {
3035
-            $fields_n_values = $obj_or_fields_array;
3036
-        } else {
3037
-            throw new EE_Error(
3038
-                sprintf(
3039
-                    esc_html__(
3040
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3041
-                        "event_espresso"
3042
-                    ),
3043
-                    get_class($this),
3044
-                    $obj_or_fields_array
3045
-                )
3046
-            );
3047
-        }
3048
-        $query_params = [];
3049
-        if (
3050
-            $this->has_primary_key_field()
3051
-            && ($include_primary_key
3052
-                || $this->get_primary_key_field()
3053
-                   instanceof
3054
-                   EE_Primary_Key_String_Field)
3055
-            && isset($fields_n_values[ $this->primary_key_name() ])
3056
-        ) {
3057
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3058
-        }
3059
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3060
-            $uniqueness_where_params                              =
3061
-                array_intersect_key($fields_n_values, $unique_index->fields());
3062
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3063
-        }
3064
-        // if there is nothing to base this search on, then we shouldn't find anything
3065
-        if (empty($query_params)) {
3066
-            return [];
3067
-        }
3068
-        return $this->get_one($query_params);
3069
-    }
3070
-
3071
-
3072
-    /**
3073
-     * Like count, but is optimized and returns a boolean instead of an int
3074
-     *
3075
-     * @param array $query_params
3076
-     * @return boolean
3077
-     * @throws EE_Error
3078
-     * @throws ReflectionException
3079
-     */
3080
-    public function exists($query_params)
3081
-    {
3082
-        $query_params['limit'] = 1;
3083
-        return $this->count($query_params) > 0;
3084
-    }
3085
-
3086
-
3087
-    /**
3088
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3089
-     *
3090
-     * @param int|string $id
3091
-     * @return boolean
3092
-     * @throws EE_Error
3093
-     * @throws ReflectionException
3094
-     */
3095
-    public function exists_by_ID($id)
3096
-    {
3097
-        return $this->exists(
3098
-            [
3099
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3100
-                [
3101
-                    $this->primary_key_name() => $id,
3102
-                ],
3103
-            ]
3104
-        );
3105
-    }
3106
-
3107
-
3108
-    /**
3109
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3110
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3111
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3112
-     * on the main table)
3113
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3114
-     * cases where we want to call it directly rather than via insert().
3115
-     *
3116
-     * @access   protected
3117
-     * @param EE_Table_Base $table
3118
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3119
-     *                                       float
3120
-     * @param int           $new_id          for now we assume only int keys
3121
-     * @return int ID of new row inserted, or FALSE on failure
3122
-     * @throws EE_Error
3123
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3124
-     */
3125
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3126
-    {
3127
-        global $wpdb;
3128
-        $insertion_col_n_values = [];
3129
-        $format_for_insertion   = [];
3130
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3131
-        foreach ($fields_on_table as $field_obj) {
3132
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3133
-            if ($field_obj->is_auto_increment()) {
3134
-                continue;
3135
-            }
3136
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3137
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3138
-            if ($prepared_value !== null) {
3139
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3140
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3141
-            }
3142
-        }
3143
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3144
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3145
-            // so add the fk to the main table as a column
3146
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3147
-            $format_for_insertion[]                              =
3148
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3149
-        }
3150
-
3151
-        // insert the new entry
3152
-        $result = $this->_do_wpdb_query(
3153
-            'insert',
3154
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3155
-        );
3156
-        if ($result === false) {
3157
-            return false;
3158
-        }
3159
-        // ok, now what do we return for the ID of the newly-inserted thing?
3160
-        if ($this->has_primary_key_field()) {
3161
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3162
-                return $wpdb->insert_id;
3163
-            }
3164
-            // it's not an auto-increment primary key, so
3165
-            // it must have been supplied
3166
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3167
-        }
3168
-        // we can't return a  primary key because there is none. instead return
3169
-        // a unique string indicating this model
3170
-        return $this->get_index_primary_key_string($fields_n_values);
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3176
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3177
-     * and there is no default, we pass it along. WPDB will take care of it)
3178
-     *
3179
-     * @param EE_Model_Field_Base $field_obj
3180
-     * @param array               $fields_n_values
3181
-     * @return mixed string|int|float depending on what the table column will be expecting
3182
-     * @throws EE_Error
3183
-     */
3184
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3185
-    {
3186
-        $field_name = $field_obj->get_name();
3187
-        // if this field doesn't allow nullable, don't allow it
3188
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3189
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3190
-        }
3191
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3192
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3193
-    }
3194
-
3195
-
3196
-    /**
3197
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3198
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3199
-     * the field's prepare_for_set() method.
3200
-     *
3201
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3202
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3203
-     *                                   top of file)
3204
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3205
-     *                                   $value is a custom selection
3206
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3207
-     */
3208
-    private function _prepare_value_for_use_in_db($value, $field)
3209
-    {
3210
-        if ($field instanceof EE_Model_Field_Base) {
3211
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3212
-            switch ($this->_values_already_prepared_by_model_object) {
3213
-                /** @noinspection PhpMissingBreakStatementInspection */
3214
-                case self::not_prepared_by_model_object:
3215
-                    $value = $field->prepare_for_set($value);
3216
-                // purposefully left out "return"
3217
-                // no break
3218
-                case self::prepared_by_model_object:
3219
-                    /** @noinspection SuspiciousAssignmentsInspection */
3220
-                    $value = $field->prepare_for_use_in_db($value);
3221
-                // no break
3222
-                case self::prepared_for_use_in_db:
3223
-                    // leave the value alone
3224
-            }
3225
-            // phpcs:enable
3226
-        }
3227
-        return $value;
3228
-    }
3229
-
3230
-
3231
-    /**
3232
-     * Returns the main table on this model
3233
-     *
3234
-     * @return EE_Primary_Table
3235
-     * @throws EE_Error
3236
-     */
3237
-    protected function _get_main_table()
3238
-    {
3239
-        foreach ($this->_tables as $table) {
3240
-            if ($table instanceof EE_Primary_Table) {
3241
-                return $table;
3242
-            }
3243
-        }
3244
-        throw new EE_Error(
3245
-            sprintf(
3246
-                esc_html__(
3247
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3248
-                    'event_espresso'
3249
-                ),
3250
-                get_class($this)
3251
-            )
3252
-        );
3253
-    }
3254
-
3255
-
3256
-    /**
3257
-     * table
3258
-     * returns EE_Primary_Table table name
3259
-     *
3260
-     * @return string
3261
-     * @throws EE_Error
3262
-     */
3263
-    public function table()
3264
-    {
3265
-        return $this->_get_main_table()->get_table_name();
3266
-    }
3267
-
3268
-
3269
-    /**
3270
-     * table
3271
-     * returns first EE_Secondary_Table table name
3272
-     *
3273
-     * @return string
3274
-     */
3275
-    public function second_table()
3276
-    {
3277
-        // grab second table from tables array
3278
-        $second_table = end($this->_tables);
3279
-        return $second_table instanceof EE_Secondary_Table
3280
-            ? $second_table->get_table_name()
3281
-            : null;
3282
-    }
3283
-
3284
-
3285
-    /**
3286
-     * get_table_obj_by_alias
3287
-     * returns table name given it's alias
3288
-     *
3289
-     * @param string $table_alias
3290
-     * @return EE_Primary_Table | EE_Secondary_Table
3291
-     */
3292
-    public function get_table_obj_by_alias($table_alias = '')
3293
-    {
3294
-        return $this->_tables[ $table_alias ] ?? null;
3295
-    }
3296
-
3297
-
3298
-    /**
3299
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3300
-     *
3301
-     * @return EE_Secondary_Table[]
3302
-     */
3303
-    protected function _get_other_tables()
3304
-    {
3305
-        $other_tables = [];
3306
-        foreach ($this->_tables as $table_alias => $table) {
3307
-            if ($table instanceof EE_Secondary_Table) {
3308
-                $other_tables[ $table_alias ] = $table;
3309
-            }
3310
-        }
3311
-        return $other_tables;
3312
-    }
3313
-
3314
-
3315
-    /**
3316
-     * Finds all the fields that correspond to the given table
3317
-     *
3318
-     * @param string $table_alias , array key in EEM_Base::_tables
3319
-     * @return EE_Model_Field_Base[]
3320
-     */
3321
-    public function _get_fields_for_table($table_alias)
3322
-    {
3323
-        return $this->_fields[ $table_alias ];
3324
-    }
3325
-
3326
-
3327
-    /**
3328
-     * Recurses through all the where parameters, and finds all the related models we'll need
3329
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3330
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3331
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3332
-     * related Registration, Transaction, and Payment models.
3333
-     *
3334
-     * @param array $query_params @see
3335
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3336
-     * @return EE_Model_Query_Info_Carrier
3337
-     * @throws EE_Error
3338
-     */
3339
-    public function _extract_related_models_from_query($query_params)
3340
-    {
3341
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3342
-        if (array_key_exists(0, $query_params)) {
3343
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3344
-        }
3345
-        if (array_key_exists('group_by', $query_params)) {
3346
-            if (is_array($query_params['group_by'])) {
3347
-                $this->_extract_related_models_from_sub_params_array_values(
3348
-                    $query_params['group_by'],
3349
-                    $query_info_carrier,
3350
-                    'group_by'
3351
-                );
3352
-            } elseif (! empty($query_params['group_by'])) {
3353
-                $this->_extract_related_model_info_from_query_param(
3354
-                    $query_params['group_by'],
3355
-                    $query_info_carrier,
3356
-                    'group_by'
3357
-                );
3358
-            }
3359
-        }
3360
-        if (array_key_exists('having', $query_params)) {
3361
-            $this->_extract_related_models_from_sub_params_array_keys(
3362
-                $query_params[0],
3363
-                $query_info_carrier,
3364
-                'having'
3365
-            );
3366
-        }
3367
-        if (array_key_exists('order_by', $query_params)) {
3368
-            if (is_array($query_params['order_by'])) {
3369
-                $this->_extract_related_models_from_sub_params_array_keys(
3370
-                    $query_params['order_by'],
3371
-                    $query_info_carrier,
3372
-                    'order_by'
3373
-                );
3374
-            } elseif (! empty($query_params['order_by'])) {
3375
-                $this->_extract_related_model_info_from_query_param(
3376
-                    $query_params['order_by'],
3377
-                    $query_info_carrier,
3378
-                    'order_by'
3379
-                );
3380
-            }
3381
-        }
3382
-        if (array_key_exists('force_join', $query_params)) {
3383
-            $this->_extract_related_models_from_sub_params_array_values(
3384
-                $query_params['force_join'],
3385
-                $query_info_carrier,
3386
-                'force_join'
3387
-            );
3388
-        }
3389
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3390
-        return $query_info_carrier;
3391
-    }
3392
-
3393
-
3394
-    /**
3395
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3396
-     *
3397
-     * @param array                       $sub_query_params
3398
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3400
-     * @return EE_Model_Query_Info_Carrier
3401
-     * @throws EE_Error
3402
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3403
-     */
3404
-    private function _extract_related_models_from_sub_params_array_keys(
3405
-        $sub_query_params,
3406
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3407
-        $query_param_type
3408
-    ) {
3409
-        if (! empty($sub_query_params)) {
3410
-            $sub_query_params = (array) $sub_query_params;
3411
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3412
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3413
-                $this->_extract_related_model_info_from_query_param(
3414
-                    $param,
3415
-                    $model_query_info_carrier,
3416
-                    $query_param_type
3417
-                );
3418
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3419
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3420
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3421
-                // of array('Registration.TXN_ID'=>23)
3422
-                $query_param_sans_stars =
3423
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3424
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3425
-                    if (! is_array($possibly_array_of_params)) {
3426
-                        throw new EE_Error(
3427
-                            sprintf(
3428
-                                esc_html__(
3429
-                                    "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3430
-                                    "event_espresso"
3431
-                                ),
3432
-                                $param,
3433
-                                $possibly_array_of_params
3434
-                            )
3435
-                        );
3436
-                    }
3437
-                    $this->_extract_related_models_from_sub_params_array_keys(
3438
-                        $possibly_array_of_params,
3439
-                        $model_query_info_carrier,
3440
-                        $query_param_type
3441
-                    );
3442
-                } elseif (
3443
-                    $query_param_type === 0 // ie WHERE
3444
-                    && is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3445
-                    && isset($possibly_array_of_params[2])
3446
-                    && $possibly_array_of_params[2]
3447
-                ) {
3448
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3449
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3450
-                    // from which we should extract query parameters!
3451
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3452
-                        throw new EE_Error(
3453
-                            sprintf(
3454
-                                esc_html__(
3455
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3456
-                                    "event_espresso"
3457
-                                ),
3458
-                                $query_param_type,
3459
-                                implode(",", $possibly_array_of_params)
3460
-                            )
3461
-                        );
3462
-                    }
3463
-                    $this->_extract_related_model_info_from_query_param(
3464
-                        $possibly_array_of_params[1],
3465
-                        $model_query_info_carrier,
3466
-                        $query_param_type
3467
-                    );
3468
-                }
3469
-            }
3470
-        }
3471
-        return $model_query_info_carrier;
3472
-    }
3473
-
3474
-
3475
-    /**
3476
-     * For extracting related models from forced_joins, where the array values contain the info about what
3477
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3478
-     *
3479
-     * @param array                       $sub_query_params @see
3480
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3481
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3482
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3483
-     * @return EE_Model_Query_Info_Carrier
3484
-     * @throws EE_Error
3485
-     */
3486
-    private function _extract_related_models_from_sub_params_array_values(
3487
-        $sub_query_params,
3488
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3489
-        $query_param_type
3490
-    ) {
3491
-        if (! empty($sub_query_params)) {
3492
-            if (! is_array($sub_query_params)) {
3493
-                throw new EE_Error(
3494
-                    sprintf(
3495
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3496
-                        $sub_query_params
3497
-                    )
3498
-                );
3499
-            }
3500
-            foreach ($sub_query_params as $param) {
3501
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3502
-                $this->_extract_related_model_info_from_query_param(
3503
-                    $param,
3504
-                    $model_query_info_carrier,
3505
-                    $query_param_type
3506
-                );
3507
-            }
3508
-        }
3509
-        return $model_query_info_carrier;
3510
-    }
3511
-
3512
-
3513
-    /**
3514
-     * Extract all the query parts from  model query params
3515
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3516
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3517
-     * but use them in a different order. Eg, we need to know what models we are querying
3518
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3519
-     * other models before we can finalize the where clause SQL.
3520
-     *
3521
-     * @param array $query_params
3522
-     * @return EE_Model_Query_Info_Carrier
3523
-     * @throws EE_Error
3524
-     * @throws ModelConfigurationException
3525
-     * @throws ReflectionException
3526
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3527
-     */
3528
-    public function _create_model_query_info_carrier($query_params)
3529
-    {
3530
-        if (! is_array($query_params)) {
3531
-            EE_Error::doing_it_wrong(
3532
-                'EEM_Base::_create_model_query_info_carrier',
3533
-                sprintf(
3534
-                    esc_html__(
3535
-                        '$query_params should be an array, you passed a variable of type %s',
3536
-                        'event_espresso'
3537
-                    ),
3538
-                    gettype($query_params)
3539
-                ),
3540
-                '4.6.0'
3541
-            );
3542
-            $query_params = [];
3543
-        }
3544
-        $query_params[0] = $query_params[0] ?? [];
3545
-        // first check if we should alter the query to account for caps or not
3546
-        // because the caps might require us to do extra joins
3547
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3548
-            $query_params[0] = array_replace_recursive(
3549
-                $query_params[0],
3550
-                $this->caps_where_conditions($query_params['caps'])
3551
-            );
3552
-        }
3553
-
3554
-        // check if we should alter the query to remove data related to protected
3555
-        // custom post types
3556
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3557
-            $where_param_key_for_password = $this->modelChainAndPassword();
3558
-            // only include if related to a cpt where no password has been set
3559
-            $query_params[0]['OR*nopassword'] = [
3560
-                $where_param_key_for_password       => '',
3561
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3562
-            ];
3563
-        }
3564
-        $query_object = $this->_extract_related_models_from_query($query_params);
3565
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3566
-        foreach ($query_params[0] as $key => $value) {
3567
-            if (is_int($key)) {
3568
-                throw new EE_Error(
3569
-                    sprintf(
3570
-                        esc_html__(
3571
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3572
-                            "event_espresso"
3573
-                        ),
3574
-                        $key,
3575
-                        var_export($value, true),
3576
-                        var_export($query_params, true),
3577
-                        get_class($this)
3578
-                    )
3579
-                );
3580
-            }
3581
-        }
3582
-        if (
3583
-            array_key_exists('default_where_conditions', $query_params)
3584
-            && ! empty($query_params['default_where_conditions'])
3585
-        ) {
3586
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3587
-        } else {
3588
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3589
-        }
3590
-        $query_params[0] = array_merge(
3591
-            $this->_get_default_where_conditions_for_models_in_query(
3592
-                $query_object,
3593
-                $use_default_where_conditions,
3594
-                $query_params[0]
3595
-            ),
3596
-            $query_params[0]
3597
-        );
3598
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3599
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3600
-        // So we need to setup a subquery and use that for the main join.
3601
-        // Note for now this only works on the primary table for the model.
3602
-        // So for instance, you could set the limit array like this:
3603
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3604
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3605
-            $query_object->set_main_model_join_sql(
3606
-                $this->_construct_limit_join_select(
3607
-                    $query_params['on_join_limit'][0],
3608
-                    $query_params['on_join_limit'][1]
3609
-                )
3610
-            );
3611
-        }
3612
-        // set limit
3613
-        if (array_key_exists('limit', $query_params)) {
3614
-            if (is_array($query_params['limit'])) {
3615
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3616
-                    $e = sprintf(
3617
-                        esc_html__(
3618
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3619
-                            "event_espresso"
3620
-                        ),
3621
-                        http_build_query($query_params['limit'])
3622
-                    );
3623
-                    throw new EE_Error($e . "|" . $e);
3624
-                }
3625
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3626
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3627
-            } elseif (! empty($query_params['limit'])) {
3628
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3629
-            }
3630
-        }
3631
-        // set order by
3632
-        if (array_key_exists('order_by', $query_params)) {
3633
-            if (is_array($query_params['order_by'])) {
3634
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3635
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3636
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3637
-                if (array_key_exists('order', $query_params)) {
3638
-                    throw new EE_Error(
3639
-                        sprintf(
3640
-                            esc_html__(
3641
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3642
-                                "event_espresso"
3643
-                            ),
3644
-                            get_class($this),
3645
-                            implode(", ", array_keys($query_params['order_by'])),
3646
-                            implode(", ", $query_params['order_by']),
3647
-                            $query_params['order']
3648
-                        )
3649
-                    );
3650
-                }
3651
-                $this->_extract_related_models_from_sub_params_array_keys(
3652
-                    $query_params['order_by'],
3653
-                    $query_object,
3654
-                    'order_by'
3655
-                );
3656
-                // assume it's an array of fields to order by
3657
-                $order_array = [];
3658
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3659
-                    $order         = $this->_extract_order($order);
3660
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3661
-                }
3662
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3663
-            } elseif (! empty($query_params['order_by'])) {
3664
-                $this->_extract_related_model_info_from_query_param(
3665
-                    $query_params['order_by'],
3666
-                    $query_object,
3667
-                    'order',
3668
-                    $query_params['order_by']
3669
-                );
3670
-                $order = isset($query_params['order'])
3671
-                    ? $this->_extract_order($query_params['order'])
3672
-                    : 'DESC';
3673
-                $query_object->set_order_by_sql(
3674
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3675
-                );
3676
-            }
3677
-        }
3678
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3679
-        if (
3680
-            ! array_key_exists('order_by', $query_params)
3681
-            && array_key_exists('order', $query_params)
3682
-            && ! empty($query_params['order'])
3683
-        ) {
3684
-            $pk_field = $this->get_primary_key_field();
3685
-            $order    = $this->_extract_order($query_params['order']);
3686
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3687
-        }
3688
-        // set group by
3689
-        if (array_key_exists('group_by', $query_params)) {
3690
-            if (is_array($query_params['group_by'])) {
3691
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3692
-                $group_by_array = [];
3693
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3694
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3695
-                }
3696
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3697
-            } elseif (! empty($query_params['group_by'])) {
3698
-                $query_object->set_group_by_sql(
3699
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3700
-                );
3701
-            }
3702
-        }
3703
-        // set having
3704
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3705
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3706
-        }
3707
-        // now, just verify they didn't pass anything wack
3708
-        foreach ($query_params as $query_key => $query_value) {
3709
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3710
-                throw new EE_Error(
3711
-                    sprintf(
3712
-                        esc_html__(
3713
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3714
-                            'event_espresso'
3715
-                        ),
3716
-                        $query_key,
3717
-                        get_class($this),
3718
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3719
-                        implode(',', $this->_allowed_query_params)
3720
-                    )
3721
-                );
3722
-            }
3723
-        }
3724
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3725
-        if (empty($main_model_join_sql)) {
3726
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3727
-        }
3728
-        return $query_object;
3729
-    }
3730
-
3731
-
3732
-    /**
3733
-     * Gets the where conditions that should be imposed on the query based on the
3734
-     * context (eg reading frontend, backend, edit or delete).
3735
-     *
3736
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3737
-     * @return array @see
3738
-     *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3739
-     * @throws EE_Error
3740
-     */
3741
-    public function caps_where_conditions($context = self::caps_read)
3742
-    {
3743
-        EEM_Base::verify_is_valid_cap_context($context);
3744
-        $cap_where_conditions = [];
3745
-        $cap_restrictions     = $this->caps_missing($context);
3746
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3747
-            $cap_where_conditions = array_replace_recursive(
3748
-                $cap_where_conditions,
3749
-                $restriction_if_no_cap->get_default_where_conditions()
3750
-            );
3751
-        }
3752
-        return apply_filters(
3753
-            'FHEE__EEM_Base__caps_where_conditions__return',
3754
-            $cap_where_conditions,
3755
-            $this,
3756
-            $context,
3757
-            $cap_restrictions
3758
-        );
3759
-    }
3760
-
3761
-
3762
-    /**
3763
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3764
-     * otherwise throws an exception
3765
-     *
3766
-     * @param string $should_be_order_string
3767
-     * @return string either ASC, asc, DESC or desc
3768
-     * @throws EE_Error
3769
-     */
3770
-    private function _extract_order($should_be_order_string)
3771
-    {
3772
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3773
-            return $should_be_order_string;
3774
-        }
3775
-        throw new EE_Error(
3776
-            sprintf(
3777
-                esc_html__(
3778
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3779
-                    "event_espresso"
3780
-                ),
3781
-                get_class($this),
3782
-                $should_be_order_string
3783
-            )
3784
-        );
3785
-    }
3786
-
3787
-
3788
-    /**
3789
-     * Looks at all the models which are included in this query, and asks each
3790
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3791
-     * so they can be merged
3792
-     *
3793
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3794
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3795
-     *                                                                  'none' means NO default where conditions will
3796
-     *                                                                  be used AT ALL during this query.
3797
-     *                                                                  'other_models_only' means default where
3798
-     *                                                                  conditions from other models will be used, but
3799
-     *                                                                  not for this primary model. 'all', the default,
3800
-     *                                                                  means default where conditions will apply as
3801
-     *                                                                  normal
3802
-     * @param array                       $where_query_params
3803
-     * @return array
3804
-     * @throws EE_Error
3805
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3806
-     *                                                                  .md#0-where-conditions
3807
-     */
3808
-    private function _get_default_where_conditions_for_models_in_query(
3809
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3810
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3811
-        $where_query_params = []
3812
-    ) {
3813
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3814
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3815
-            throw new EE_Error(
3816
-                sprintf(
3817
-                    esc_html__(
3818
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3819
-                        "event_espresso"
3820
-                    ),
3821
-                    $use_default_where_conditions,
3822
-                    implode(", ", $allowed_used_default_where_conditions_values)
3823
-                )
3824
-            );
3825
-        }
3826
-        $universal_query_params = [];
3827
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3828
-            $universal_query_params = $this->_get_default_where_conditions();
3829
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3830
-            $universal_query_params = $this->_get_minimum_where_conditions();
3831
-        }
3832
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3833
-            $related_model = $this->get_related_model_obj($model_name);
3834
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3835
-                $related_model_universal_where_params =
3836
-                    $related_model->_get_default_where_conditions($model_relation_path);
3837
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3838
-                $related_model_universal_where_params =
3839
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3840
-            } else {
3841
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3842
-                continue;
3843
-            }
3844
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3845
-                $related_model_universal_where_params,
3846
-                $where_query_params,
3847
-                $related_model,
3848
-                $model_relation_path
3849
-            );
3850
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3851
-                $universal_query_params,
3852
-                $overrides
3853
-            );
3854
-        }
3855
-        return $universal_query_params;
3856
-    }
3857
-
3858
-
3859
-    /**
3860
-     * Determines whether or not we should use default where conditions for the model in question
3861
-     * (this model, or other related models).
3862
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3863
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3864
-     * We should use default where conditions on related models when they requested to use default where conditions
3865
-     * on all models, or specifically just on other related models
3866
-     *
3867
-     * @param      $default_where_conditions_value
3868
-     * @param bool $for_this_model false means this is for OTHER related models
3869
-     * @return bool
3870
-     */
3871
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3872
-    {
3873
-        return (
3874
-                   $for_this_model
3875
-                   && in_array(
3876
-                       $default_where_conditions_value,
3877
-                       [
3878
-                           EEM_Base::default_where_conditions_all,
3879
-                           EEM_Base::default_where_conditions_this_only,
3880
-                           EEM_Base::default_where_conditions_minimum_others,
3881
-                       ],
3882
-                       true
3883
-                   )
3884
-               )
3885
-               || (
3886
-                   ! $for_this_model
3887
-                   && in_array(
3888
-                       $default_where_conditions_value,
3889
-                       [
3890
-                           EEM_Base::default_where_conditions_all,
3891
-                           EEM_Base::default_where_conditions_others_only,
3892
-                       ],
3893
-                       true
3894
-                   )
3895
-               );
3896
-    }
3897
-
3898
-
3899
-    /**
3900
-     * Determines whether or not we should use default minimum conditions for the model in question
3901
-     * (this model, or other related models).
3902
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3903
-     * where conditions.
3904
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3905
-     * on this model or others
3906
-     *
3907
-     * @param      $default_where_conditions_value
3908
-     * @param bool $for_this_model false means this is for OTHER related models
3909
-     * @return bool
3910
-     */
3911
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3912
-    {
3913
-        return (
3914
-                   $for_this_model
3915
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3916
-               )
3917
-               || (
3918
-                   ! $for_this_model
3919
-                   && in_array(
3920
-                       $default_where_conditions_value,
3921
-                       [
3922
-                           EEM_Base::default_where_conditions_minimum_others,
3923
-                           EEM_Base::default_where_conditions_minimum_all,
3924
-                       ],
3925
-                       true
3926
-                   )
3927
-               );
3928
-    }
3929
-
3930
-
3931
-    /**
3932
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3933
-     * then we also add a special where condition which allows for that model's primary key
3934
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3935
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3936
-     *
3937
-     * @param array    $default_where_conditions
3938
-     * @param array    $provided_where_conditions
3939
-     * @param EEM_Base $model
3940
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3941
-     * @return array @see
3942
-     *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3943
-     * @throws EE_Error
3944
-     */
3945
-    private function _override_defaults_or_make_null_friendly(
3946
-        $default_where_conditions,
3947
-        $provided_where_conditions,
3948
-        $model,
3949
-        $model_relation_path
3950
-    ) {
3951
-        $null_friendly_where_conditions = [];
3952
-        $none_overridden                = true;
3953
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3954
-        foreach ($default_where_conditions as $key => $val) {
3955
-            if (isset($provided_where_conditions[ $key ])) {
3956
-                $none_overridden = false;
3957
-            } else {
3958
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3959
-            }
3960
-        }
3961
-        if ($none_overridden && $default_where_conditions) {
3962
-            if ($model->has_primary_key_field()) {
3963
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3964
-                                                                                   . "."
3965
-                                                                                   . $model->primary_key_name() ] =
3966
-                    ['IS NULL'];
3967
-            }/*else{
2646
+			$this->_show_next_x_db_queries--;
2647
+		}
2648
+	}
2649
+
2650
+
2651
+	/**
2652
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2653
+	 * There are the 3 cases:
2654
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2655
+	 * $otherModelObject has no ID, it is first saved.
2656
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2657
+	 * has no ID, it is first saved.
2658
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2659
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2660
+	 * join table
2661
+	 *
2662
+	 * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2663
+	 * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2664
+	 * @param string            $relationName                     , key in EEM_Base::_relations
2665
+	 *                                                            an attendee to a group, you also want to specify
2666
+	 *                                                            which role they will have in that group. So you would
2667
+	 *                                                            use this parameter to specify
2668
+	 *                                                            array('role-column-name'=>'role-id')
2669
+	 * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2670
+	 *                                                            relation to for relation to methods that allow you to
2671
+	 *                                                            further specify extra columns to join by (such as
2672
+	 *                                                            HABTM).  Keep in mind that the only acceptable
2673
+	 *                                                            query_params is strict "col" => "value" pairs because
2674
+	 *                                                            these will be inserted in any new rows created as
2675
+	 *                                                            well.
2676
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2677
+	 * @throws EE_Error
2678
+	 */
2679
+	public function add_relationship_to(
2680
+		$id_or_obj,
2681
+		$other_model_id_or_obj,
2682
+		$relationName,
2683
+		$extra_join_model_fields_n_values = []
2684
+	) {
2685
+		$relation_obj = $this->related_settings_for($relationName);
2686
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2687
+	}
2688
+
2689
+
2690
+	/**
2691
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2692
+	 * There are the 3 cases:
2693
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2694
+	 * error
2695
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2696
+	 * an error
2697
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2698
+	 *
2699
+	 * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2700
+	 * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2701
+	 * @param string            $relationName          key in EEM_Base::_relations
2702
+	 * @param array|null        $where_query           This allows you to enter further query params for the relation
2703
+	 *                                                 to for relation to methods that allow you to further specify
2704
+	 *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2705
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2706
+	 *                                                 because these will be inserted in any new rows created as well.
2707
+	 * @return EE_Base_Class
2708
+	 * @throws EE_Error
2709
+	 */
2710
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2711
+	{
2712
+		$relation_obj = $this->related_settings_for($relationName);
2713
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2714
+	}
2715
+
2716
+
2717
+	/**
2718
+	 * @param mixed       $id_or_obj
2719
+	 * @param string      $relationName
2720
+	 * @param array|null  $where_query_params
2721
+	 * @return EE_Base_Class[]
2722
+	 * @throws EE_Error
2723
+	 * @throws ReflectionException
2724
+	 */
2725
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2726
+	{
2727
+		$relation_obj = $this->related_settings_for($relationName);
2728
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * Gets all the related items of the specified $model_name, using $query_params.
2734
+	 * Note: by default, we remove the "default query params"
2735
+	 * because we want to get even deleted items etc.
2736
+	 *
2737
+	 * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2738
+	 * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2739
+	 * @param array|null  $query_params @see
2740
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2741
+	 * @return EE_Base_Class[]
2742
+	 * @throws EE_Error
2743
+	 * @throws ReflectionException
2744
+	 */
2745
+	public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2746
+	{
2747
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2748
+		$relation_settings = $this->related_settings_for($model_name);
2749
+		return $relation_settings->get_all_related($model_obj, $query_params);
2750
+	}
2751
+
2752
+
2753
+	/**
2754
+	 * Deletes all the model objects across the relation indicated by $model_name
2755
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2756
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2757
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2758
+	 *
2759
+	 * @param EE_Base_Class|int|string $id_or_obj
2760
+	 * @param string                   $model_name
2761
+	 * @param array|null               $query_params
2762
+	 * @return int how many deleted
2763
+	 * @throws EE_Error
2764
+	 * @throws ReflectionException
2765
+	 */
2766
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2767
+	{
2768
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2769
+		$relation_settings = $this->related_settings_for($model_name);
2770
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2771
+	}
2772
+
2773
+
2774
+	/**
2775
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2776
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2777
+	 * the model objects can't be hard deleted because of blocking related model objects,
2778
+	 * just does a soft-delete on them instead.
2779
+	 *
2780
+	 * @param EE_Base_Class|int|string $id_or_obj
2781
+	 * @param string                   $model_name
2782
+	 * @param array|null               $query_params
2783
+	 * @return int how many deleted
2784
+	 * @throws EE_Error
2785
+	 * @throws ReflectionException
2786
+	 */
2787
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2788
+	{
2789
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2790
+		$relation_settings = $this->related_settings_for($model_name);
2791
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2792
+	}
2793
+
2794
+
2795
+	/**
2796
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2797
+	 * unless otherwise specified in the $query_params
2798
+	 *
2799
+	 * @param EE_Base_Class|int|string $id_or_obj
2800
+	 * @param string                   $model_name     like 'Event', or 'Registration'
2801
+	 * @param array|null               $query_params   @see
2802
+	 *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2803
+	 * @param string                   $field_to_count name of field to count by. By default, uses primary key
2804
+	 * @param bool                     $distinct       if we want to only count the distinct values for the column then
2805
+	 *                                                 you can trigger that by the setting $distinct to TRUE;
2806
+	 * @return int
2807
+	 * @throws EE_Error
2808
+	 * @throws ReflectionException
2809
+	 */
2810
+	public function count_related(
2811
+		$id_or_obj,
2812
+		$model_name,
2813
+		$query_params = [],
2814
+		$field_to_count = null,
2815
+		$distinct = false
2816
+	) {
2817
+		$related_model = $this->get_related_model_obj($model_name);
2818
+		// we're just going to use the query params on the related model's normal get_all query,
2819
+		// except add a condition to say to match the current mod
2820
+		if (! isset($query_params['default_where_conditions'])) {
2821
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2822
+		}
2823
+		$this_model_name                                                 = $this->get_this_model_name();
2824
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2825
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2826
+		return $related_model->count($query_params, $field_to_count, $distinct);
2827
+	}
2828
+
2829
+
2830
+	/**
2831
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2832
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2833
+	 *
2834
+	 * @param EE_Base_Class|int|string $id_or_obj
2835
+	 * @param string                   $model_name   like 'Event', or 'Registration'
2836
+	 * @param array|null               $query_params @see
2837
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2838
+	 * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2839
+	 * @return float
2840
+	 * @throws EE_Error
2841
+	 * @throws ReflectionException
2842
+	 */
2843
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2844
+	{
2845
+		$related_model = $this->get_related_model_obj($model_name);
2846
+		if (! is_array($query_params)) {
2847
+			EE_Error::doing_it_wrong(
2848
+				'EEM_Base::sum_related',
2849
+				sprintf(
2850
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2851
+					gettype($query_params)
2852
+				),
2853
+				'4.6.0'
2854
+			);
2855
+			$query_params = [];
2856
+		}
2857
+		// we're just going to use the query params on the related model's normal get_all query,
2858
+		// except add a condition to say to match the current mod
2859
+		if (! isset($query_params['default_where_conditions'])) {
2860
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2861
+		}
2862
+		$this_model_name                                                 = $this->get_this_model_name();
2863
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2864
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2865
+		return $related_model->sum($query_params, $field_to_sum);
2866
+	}
2867
+
2868
+
2869
+	/**
2870
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2871
+	 * $modelObject
2872
+	 *
2873
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2874
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2875
+	 * @param array|null          $query_params     @see
2876
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2877
+	 * @return EE_Base_Class
2878
+	 * @throws EE_Error
2879
+	 * @throws ReflectionException
2880
+	 */
2881
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2882
+	{
2883
+		$query_params['limit'] = 1;
2884
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2885
+		if ($results) {
2886
+			return array_shift($results);
2887
+		}
2888
+		return null;
2889
+	}
2890
+
2891
+
2892
+	/**
2893
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2894
+	 *
2895
+	 * @return string
2896
+	 */
2897
+	public function get_this_model_name()
2898
+	{
2899
+		return str_replace("EEM_", "", get_class($this));
2900
+	}
2901
+
2902
+
2903
+	/**
2904
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2905
+	 *
2906
+	 * @return EE_Any_Foreign_Model_Name_Field
2907
+	 * @throws EE_Error
2908
+	 */
2909
+	public function get_field_containing_related_model_name()
2910
+	{
2911
+		foreach ($this->field_settings(true) as $field) {
2912
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2913
+				$field_with_model_name = $field;
2914
+			}
2915
+		}
2916
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2917
+			throw new EE_Error(
2918
+				sprintf(
2919
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2920
+					$this->get_this_model_name()
2921
+				)
2922
+			);
2923
+		}
2924
+		return $field_with_model_name;
2925
+	}
2926
+
2927
+
2928
+	/**
2929
+	 * Inserts a new entry into the database, for each table.
2930
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2931
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2932
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2933
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2934
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2935
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2936
+	 *
2937
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2938
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2939
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2940
+	 *                              of EEM_Base)
2941
+	 * @return int|string new primary key on main table that got inserted
2942
+	 * @throws EE_Error
2943
+	 * @throws ReflectionException
2944
+	 */
2945
+	public function insert($field_n_values)
2946
+	{
2947
+		/**
2948
+		 * Filters the fields and their values before inserting an item using the models
2949
+		 *
2950
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2951
+		 * @param EEM_Base $model           the model used
2952
+		 */
2953
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2954
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2955
+			$main_table = $this->_get_main_table();
2956
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2957
+			if ($new_id !== false) {
2958
+				foreach ($this->_get_other_tables() as $other_table) {
2959
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2960
+				}
2961
+			}
2962
+			/**
2963
+			 * Done just after attempting to insert a new model object
2964
+			 *
2965
+			 * @param EEM_Base $model           used
2966
+			 * @param array    $fields_n_values fields and their values
2967
+			 * @param int|string the              ID of the newly-inserted model object
2968
+			 */
2969
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2970
+			return $new_id;
2971
+		}
2972
+		return false;
2973
+	}
2974
+
2975
+
2976
+	/**
2977
+	 * Checks that the result would satisfy the unique indexes on this model
2978
+	 *
2979
+	 * @param array  $field_n_values
2980
+	 * @param string $action
2981
+	 * @return boolean
2982
+	 * @throws EE_Error
2983
+	 * @throws ReflectionException
2984
+	 */
2985
+	protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2986
+	{
2987
+		foreach ($this->unique_indexes() as $index_name => $index) {
2988
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2989
+			if ($this->exists([$uniqueness_where_params])) {
2990
+				EE_Error::add_error(
2991
+					sprintf(
2992
+						esc_html__(
2993
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2994
+							"event_espresso"
2995
+						),
2996
+						$action,
2997
+						$this->_get_class_name(),
2998
+						$index_name,
2999
+						implode(",", $index->field_names()),
3000
+						http_build_query($uniqueness_where_params)
3001
+					),
3002
+					__FILE__,
3003
+					__FUNCTION__,
3004
+					__LINE__
3005
+				);
3006
+				return false;
3007
+			}
3008
+		}
3009
+		return true;
3010
+	}
3011
+
3012
+
3013
+	/**
3014
+	 * Checks the database for an item that conflicts (ie, if this item were
3015
+	 * saved to the DB would break some uniqueness requirement, like a primary key
3016
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
3017
+	 * can be either an EE_Base_Class or an array of fields n values
3018
+	 *
3019
+	 * @param EE_Base_Class|array $obj_or_fields_array
3020
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
3021
+	 *                                                 when looking for conflicts
3022
+	 *                                                 (ie, if false, we ignore the model object's primary key
3023
+	 *                                                 when finding "conflicts". If true, it's also considered).
3024
+	 *                                                 Only works for INT primary key,
3025
+	 *                                                 STRING primary keys cannot be ignored
3026
+	 * @return EE_Base_Class|array
3027
+	 * @throws EE_Error
3028
+	 * @throws ReflectionException
3029
+	 */
3030
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3031
+	{
3032
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
3033
+			$fields_n_values = $obj_or_fields_array->model_field_array();
3034
+		} elseif (is_array($obj_or_fields_array)) {
3035
+			$fields_n_values = $obj_or_fields_array;
3036
+		} else {
3037
+			throw new EE_Error(
3038
+				sprintf(
3039
+					esc_html__(
3040
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3041
+						"event_espresso"
3042
+					),
3043
+					get_class($this),
3044
+					$obj_or_fields_array
3045
+				)
3046
+			);
3047
+		}
3048
+		$query_params = [];
3049
+		if (
3050
+			$this->has_primary_key_field()
3051
+			&& ($include_primary_key
3052
+				|| $this->get_primary_key_field()
3053
+				   instanceof
3054
+				   EE_Primary_Key_String_Field)
3055
+			&& isset($fields_n_values[ $this->primary_key_name() ])
3056
+		) {
3057
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3058
+		}
3059
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3060
+			$uniqueness_where_params                              =
3061
+				array_intersect_key($fields_n_values, $unique_index->fields());
3062
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3063
+		}
3064
+		// if there is nothing to base this search on, then we shouldn't find anything
3065
+		if (empty($query_params)) {
3066
+			return [];
3067
+		}
3068
+		return $this->get_one($query_params);
3069
+	}
3070
+
3071
+
3072
+	/**
3073
+	 * Like count, but is optimized and returns a boolean instead of an int
3074
+	 *
3075
+	 * @param array $query_params
3076
+	 * @return boolean
3077
+	 * @throws EE_Error
3078
+	 * @throws ReflectionException
3079
+	 */
3080
+	public function exists($query_params)
3081
+	{
3082
+		$query_params['limit'] = 1;
3083
+		return $this->count($query_params) > 0;
3084
+	}
3085
+
3086
+
3087
+	/**
3088
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3089
+	 *
3090
+	 * @param int|string $id
3091
+	 * @return boolean
3092
+	 * @throws EE_Error
3093
+	 * @throws ReflectionException
3094
+	 */
3095
+	public function exists_by_ID($id)
3096
+	{
3097
+		return $this->exists(
3098
+			[
3099
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3100
+				[
3101
+					$this->primary_key_name() => $id,
3102
+				],
3103
+			]
3104
+		);
3105
+	}
3106
+
3107
+
3108
+	/**
3109
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3110
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3111
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3112
+	 * on the main table)
3113
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3114
+	 * cases where we want to call it directly rather than via insert().
3115
+	 *
3116
+	 * @access   protected
3117
+	 * @param EE_Table_Base $table
3118
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3119
+	 *                                       float
3120
+	 * @param int           $new_id          for now we assume only int keys
3121
+	 * @return int ID of new row inserted, or FALSE on failure
3122
+	 * @throws EE_Error
3123
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3124
+	 */
3125
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3126
+	{
3127
+		global $wpdb;
3128
+		$insertion_col_n_values = [];
3129
+		$format_for_insertion   = [];
3130
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3131
+		foreach ($fields_on_table as $field_obj) {
3132
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3133
+			if ($field_obj->is_auto_increment()) {
3134
+				continue;
3135
+			}
3136
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3137
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3138
+			if ($prepared_value !== null) {
3139
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3140
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3141
+			}
3142
+		}
3143
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3144
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3145
+			// so add the fk to the main table as a column
3146
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3147
+			$format_for_insertion[]                              =
3148
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3149
+		}
3150
+
3151
+		// insert the new entry
3152
+		$result = $this->_do_wpdb_query(
3153
+			'insert',
3154
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3155
+		);
3156
+		if ($result === false) {
3157
+			return false;
3158
+		}
3159
+		// ok, now what do we return for the ID of the newly-inserted thing?
3160
+		if ($this->has_primary_key_field()) {
3161
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3162
+				return $wpdb->insert_id;
3163
+			}
3164
+			// it's not an auto-increment primary key, so
3165
+			// it must have been supplied
3166
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3167
+		}
3168
+		// we can't return a  primary key because there is none. instead return
3169
+		// a unique string indicating this model
3170
+		return $this->get_index_primary_key_string($fields_n_values);
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3176
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3177
+	 * and there is no default, we pass it along. WPDB will take care of it)
3178
+	 *
3179
+	 * @param EE_Model_Field_Base $field_obj
3180
+	 * @param array               $fields_n_values
3181
+	 * @return mixed string|int|float depending on what the table column will be expecting
3182
+	 * @throws EE_Error
3183
+	 */
3184
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3185
+	{
3186
+		$field_name = $field_obj->get_name();
3187
+		// if this field doesn't allow nullable, don't allow it
3188
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3189
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3190
+		}
3191
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3192
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3193
+	}
3194
+
3195
+
3196
+	/**
3197
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3198
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3199
+	 * the field's prepare_for_set() method.
3200
+	 *
3201
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3202
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3203
+	 *                                   top of file)
3204
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3205
+	 *                                   $value is a custom selection
3206
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3207
+	 */
3208
+	private function _prepare_value_for_use_in_db($value, $field)
3209
+	{
3210
+		if ($field instanceof EE_Model_Field_Base) {
3211
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3212
+			switch ($this->_values_already_prepared_by_model_object) {
3213
+				/** @noinspection PhpMissingBreakStatementInspection */
3214
+				case self::not_prepared_by_model_object:
3215
+					$value = $field->prepare_for_set($value);
3216
+				// purposefully left out "return"
3217
+				// no break
3218
+				case self::prepared_by_model_object:
3219
+					/** @noinspection SuspiciousAssignmentsInspection */
3220
+					$value = $field->prepare_for_use_in_db($value);
3221
+				// no break
3222
+				case self::prepared_for_use_in_db:
3223
+					// leave the value alone
3224
+			}
3225
+			// phpcs:enable
3226
+		}
3227
+		return $value;
3228
+	}
3229
+
3230
+
3231
+	/**
3232
+	 * Returns the main table on this model
3233
+	 *
3234
+	 * @return EE_Primary_Table
3235
+	 * @throws EE_Error
3236
+	 */
3237
+	protected function _get_main_table()
3238
+	{
3239
+		foreach ($this->_tables as $table) {
3240
+			if ($table instanceof EE_Primary_Table) {
3241
+				return $table;
3242
+			}
3243
+		}
3244
+		throw new EE_Error(
3245
+			sprintf(
3246
+				esc_html__(
3247
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3248
+					'event_espresso'
3249
+				),
3250
+				get_class($this)
3251
+			)
3252
+		);
3253
+	}
3254
+
3255
+
3256
+	/**
3257
+	 * table
3258
+	 * returns EE_Primary_Table table name
3259
+	 *
3260
+	 * @return string
3261
+	 * @throws EE_Error
3262
+	 */
3263
+	public function table()
3264
+	{
3265
+		return $this->_get_main_table()->get_table_name();
3266
+	}
3267
+
3268
+
3269
+	/**
3270
+	 * table
3271
+	 * returns first EE_Secondary_Table table name
3272
+	 *
3273
+	 * @return string
3274
+	 */
3275
+	public function second_table()
3276
+	{
3277
+		// grab second table from tables array
3278
+		$second_table = end($this->_tables);
3279
+		return $second_table instanceof EE_Secondary_Table
3280
+			? $second_table->get_table_name()
3281
+			: null;
3282
+	}
3283
+
3284
+
3285
+	/**
3286
+	 * get_table_obj_by_alias
3287
+	 * returns table name given it's alias
3288
+	 *
3289
+	 * @param string $table_alias
3290
+	 * @return EE_Primary_Table | EE_Secondary_Table
3291
+	 */
3292
+	public function get_table_obj_by_alias($table_alias = '')
3293
+	{
3294
+		return $this->_tables[ $table_alias ] ?? null;
3295
+	}
3296
+
3297
+
3298
+	/**
3299
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3300
+	 *
3301
+	 * @return EE_Secondary_Table[]
3302
+	 */
3303
+	protected function _get_other_tables()
3304
+	{
3305
+		$other_tables = [];
3306
+		foreach ($this->_tables as $table_alias => $table) {
3307
+			if ($table instanceof EE_Secondary_Table) {
3308
+				$other_tables[ $table_alias ] = $table;
3309
+			}
3310
+		}
3311
+		return $other_tables;
3312
+	}
3313
+
3314
+
3315
+	/**
3316
+	 * Finds all the fields that correspond to the given table
3317
+	 *
3318
+	 * @param string $table_alias , array key in EEM_Base::_tables
3319
+	 * @return EE_Model_Field_Base[]
3320
+	 */
3321
+	public function _get_fields_for_table($table_alias)
3322
+	{
3323
+		return $this->_fields[ $table_alias ];
3324
+	}
3325
+
3326
+
3327
+	/**
3328
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3329
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3330
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3331
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3332
+	 * related Registration, Transaction, and Payment models.
3333
+	 *
3334
+	 * @param array $query_params @see
3335
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3336
+	 * @return EE_Model_Query_Info_Carrier
3337
+	 * @throws EE_Error
3338
+	 */
3339
+	public function _extract_related_models_from_query($query_params)
3340
+	{
3341
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3342
+		if (array_key_exists(0, $query_params)) {
3343
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3344
+		}
3345
+		if (array_key_exists('group_by', $query_params)) {
3346
+			if (is_array($query_params['group_by'])) {
3347
+				$this->_extract_related_models_from_sub_params_array_values(
3348
+					$query_params['group_by'],
3349
+					$query_info_carrier,
3350
+					'group_by'
3351
+				);
3352
+			} elseif (! empty($query_params['group_by'])) {
3353
+				$this->_extract_related_model_info_from_query_param(
3354
+					$query_params['group_by'],
3355
+					$query_info_carrier,
3356
+					'group_by'
3357
+				);
3358
+			}
3359
+		}
3360
+		if (array_key_exists('having', $query_params)) {
3361
+			$this->_extract_related_models_from_sub_params_array_keys(
3362
+				$query_params[0],
3363
+				$query_info_carrier,
3364
+				'having'
3365
+			);
3366
+		}
3367
+		if (array_key_exists('order_by', $query_params)) {
3368
+			if (is_array($query_params['order_by'])) {
3369
+				$this->_extract_related_models_from_sub_params_array_keys(
3370
+					$query_params['order_by'],
3371
+					$query_info_carrier,
3372
+					'order_by'
3373
+				);
3374
+			} elseif (! empty($query_params['order_by'])) {
3375
+				$this->_extract_related_model_info_from_query_param(
3376
+					$query_params['order_by'],
3377
+					$query_info_carrier,
3378
+					'order_by'
3379
+				);
3380
+			}
3381
+		}
3382
+		if (array_key_exists('force_join', $query_params)) {
3383
+			$this->_extract_related_models_from_sub_params_array_values(
3384
+				$query_params['force_join'],
3385
+				$query_info_carrier,
3386
+				'force_join'
3387
+			);
3388
+		}
3389
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3390
+		return $query_info_carrier;
3391
+	}
3392
+
3393
+
3394
+	/**
3395
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3396
+	 *
3397
+	 * @param array                       $sub_query_params
3398
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3399
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3400
+	 * @return EE_Model_Query_Info_Carrier
3401
+	 * @throws EE_Error
3402
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3403
+	 */
3404
+	private function _extract_related_models_from_sub_params_array_keys(
3405
+		$sub_query_params,
3406
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3407
+		$query_param_type
3408
+	) {
3409
+		if (! empty($sub_query_params)) {
3410
+			$sub_query_params = (array) $sub_query_params;
3411
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3412
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3413
+				$this->_extract_related_model_info_from_query_param(
3414
+					$param,
3415
+					$model_query_info_carrier,
3416
+					$query_param_type
3417
+				);
3418
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3419
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3420
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3421
+				// of array('Registration.TXN_ID'=>23)
3422
+				$query_param_sans_stars =
3423
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3424
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3425
+					if (! is_array($possibly_array_of_params)) {
3426
+						throw new EE_Error(
3427
+							sprintf(
3428
+								esc_html__(
3429
+									"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3430
+									"event_espresso"
3431
+								),
3432
+								$param,
3433
+								$possibly_array_of_params
3434
+							)
3435
+						);
3436
+					}
3437
+					$this->_extract_related_models_from_sub_params_array_keys(
3438
+						$possibly_array_of_params,
3439
+						$model_query_info_carrier,
3440
+						$query_param_type
3441
+					);
3442
+				} elseif (
3443
+					$query_param_type === 0 // ie WHERE
3444
+					&& is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3445
+					&& isset($possibly_array_of_params[2])
3446
+					&& $possibly_array_of_params[2]
3447
+				) {
3448
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3449
+					// indicating that $possible_array_of_params[1] is actually a field name,
3450
+					// from which we should extract query parameters!
3451
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3452
+						throw new EE_Error(
3453
+							sprintf(
3454
+								esc_html__(
3455
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3456
+									"event_espresso"
3457
+								),
3458
+								$query_param_type,
3459
+								implode(",", $possibly_array_of_params)
3460
+							)
3461
+						);
3462
+					}
3463
+					$this->_extract_related_model_info_from_query_param(
3464
+						$possibly_array_of_params[1],
3465
+						$model_query_info_carrier,
3466
+						$query_param_type
3467
+					);
3468
+				}
3469
+			}
3470
+		}
3471
+		return $model_query_info_carrier;
3472
+	}
3473
+
3474
+
3475
+	/**
3476
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3477
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3478
+	 *
3479
+	 * @param array                       $sub_query_params @see
3480
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3481
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3482
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3483
+	 * @return EE_Model_Query_Info_Carrier
3484
+	 * @throws EE_Error
3485
+	 */
3486
+	private function _extract_related_models_from_sub_params_array_values(
3487
+		$sub_query_params,
3488
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3489
+		$query_param_type
3490
+	) {
3491
+		if (! empty($sub_query_params)) {
3492
+			if (! is_array($sub_query_params)) {
3493
+				throw new EE_Error(
3494
+					sprintf(
3495
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3496
+						$sub_query_params
3497
+					)
3498
+				);
3499
+			}
3500
+			foreach ($sub_query_params as $param) {
3501
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3502
+				$this->_extract_related_model_info_from_query_param(
3503
+					$param,
3504
+					$model_query_info_carrier,
3505
+					$query_param_type
3506
+				);
3507
+			}
3508
+		}
3509
+		return $model_query_info_carrier;
3510
+	}
3511
+
3512
+
3513
+	/**
3514
+	 * Extract all the query parts from  model query params
3515
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3516
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3517
+	 * but use them in a different order. Eg, we need to know what models we are querying
3518
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3519
+	 * other models before we can finalize the where clause SQL.
3520
+	 *
3521
+	 * @param array $query_params
3522
+	 * @return EE_Model_Query_Info_Carrier
3523
+	 * @throws EE_Error
3524
+	 * @throws ModelConfigurationException
3525
+	 * @throws ReflectionException
3526
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3527
+	 */
3528
+	public function _create_model_query_info_carrier($query_params)
3529
+	{
3530
+		if (! is_array($query_params)) {
3531
+			EE_Error::doing_it_wrong(
3532
+				'EEM_Base::_create_model_query_info_carrier',
3533
+				sprintf(
3534
+					esc_html__(
3535
+						'$query_params should be an array, you passed a variable of type %s',
3536
+						'event_espresso'
3537
+					),
3538
+					gettype($query_params)
3539
+				),
3540
+				'4.6.0'
3541
+			);
3542
+			$query_params = [];
3543
+		}
3544
+		$query_params[0] = $query_params[0] ?? [];
3545
+		// first check if we should alter the query to account for caps or not
3546
+		// because the caps might require us to do extra joins
3547
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3548
+			$query_params[0] = array_replace_recursive(
3549
+				$query_params[0],
3550
+				$this->caps_where_conditions($query_params['caps'])
3551
+			);
3552
+		}
3553
+
3554
+		// check if we should alter the query to remove data related to protected
3555
+		// custom post types
3556
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3557
+			$where_param_key_for_password = $this->modelChainAndPassword();
3558
+			// only include if related to a cpt where no password has been set
3559
+			$query_params[0]['OR*nopassword'] = [
3560
+				$where_param_key_for_password       => '',
3561
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3562
+			];
3563
+		}
3564
+		$query_object = $this->_extract_related_models_from_query($query_params);
3565
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3566
+		foreach ($query_params[0] as $key => $value) {
3567
+			if (is_int($key)) {
3568
+				throw new EE_Error(
3569
+					sprintf(
3570
+						esc_html__(
3571
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3572
+							"event_espresso"
3573
+						),
3574
+						$key,
3575
+						var_export($value, true),
3576
+						var_export($query_params, true),
3577
+						get_class($this)
3578
+					)
3579
+				);
3580
+			}
3581
+		}
3582
+		if (
3583
+			array_key_exists('default_where_conditions', $query_params)
3584
+			&& ! empty($query_params['default_where_conditions'])
3585
+		) {
3586
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3587
+		} else {
3588
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3589
+		}
3590
+		$query_params[0] = array_merge(
3591
+			$this->_get_default_where_conditions_for_models_in_query(
3592
+				$query_object,
3593
+				$use_default_where_conditions,
3594
+				$query_params[0]
3595
+			),
3596
+			$query_params[0]
3597
+		);
3598
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3599
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3600
+		// So we need to setup a subquery and use that for the main join.
3601
+		// Note for now this only works on the primary table for the model.
3602
+		// So for instance, you could set the limit array like this:
3603
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3604
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3605
+			$query_object->set_main_model_join_sql(
3606
+				$this->_construct_limit_join_select(
3607
+					$query_params['on_join_limit'][0],
3608
+					$query_params['on_join_limit'][1]
3609
+				)
3610
+			);
3611
+		}
3612
+		// set limit
3613
+		if (array_key_exists('limit', $query_params)) {
3614
+			if (is_array($query_params['limit'])) {
3615
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3616
+					$e = sprintf(
3617
+						esc_html__(
3618
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3619
+							"event_espresso"
3620
+						),
3621
+						http_build_query($query_params['limit'])
3622
+					);
3623
+					throw new EE_Error($e . "|" . $e);
3624
+				}
3625
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3626
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3627
+			} elseif (! empty($query_params['limit'])) {
3628
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3629
+			}
3630
+		}
3631
+		// set order by
3632
+		if (array_key_exists('order_by', $query_params)) {
3633
+			if (is_array($query_params['order_by'])) {
3634
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3635
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3636
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3637
+				if (array_key_exists('order', $query_params)) {
3638
+					throw new EE_Error(
3639
+						sprintf(
3640
+							esc_html__(
3641
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3642
+								"event_espresso"
3643
+							),
3644
+							get_class($this),
3645
+							implode(", ", array_keys($query_params['order_by'])),
3646
+							implode(", ", $query_params['order_by']),
3647
+							$query_params['order']
3648
+						)
3649
+					);
3650
+				}
3651
+				$this->_extract_related_models_from_sub_params_array_keys(
3652
+					$query_params['order_by'],
3653
+					$query_object,
3654
+					'order_by'
3655
+				);
3656
+				// assume it's an array of fields to order by
3657
+				$order_array = [];
3658
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3659
+					$order         = $this->_extract_order($order);
3660
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3661
+				}
3662
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3663
+			} elseif (! empty($query_params['order_by'])) {
3664
+				$this->_extract_related_model_info_from_query_param(
3665
+					$query_params['order_by'],
3666
+					$query_object,
3667
+					'order',
3668
+					$query_params['order_by']
3669
+				);
3670
+				$order = isset($query_params['order'])
3671
+					? $this->_extract_order($query_params['order'])
3672
+					: 'DESC';
3673
+				$query_object->set_order_by_sql(
3674
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3675
+				);
3676
+			}
3677
+		}
3678
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3679
+		if (
3680
+			! array_key_exists('order_by', $query_params)
3681
+			&& array_key_exists('order', $query_params)
3682
+			&& ! empty($query_params['order'])
3683
+		) {
3684
+			$pk_field = $this->get_primary_key_field();
3685
+			$order    = $this->_extract_order($query_params['order']);
3686
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3687
+		}
3688
+		// set group by
3689
+		if (array_key_exists('group_by', $query_params)) {
3690
+			if (is_array($query_params['group_by'])) {
3691
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3692
+				$group_by_array = [];
3693
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3694
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3695
+				}
3696
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3697
+			} elseif (! empty($query_params['group_by'])) {
3698
+				$query_object->set_group_by_sql(
3699
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3700
+				);
3701
+			}
3702
+		}
3703
+		// set having
3704
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3705
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3706
+		}
3707
+		// now, just verify they didn't pass anything wack
3708
+		foreach ($query_params as $query_key => $query_value) {
3709
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3710
+				throw new EE_Error(
3711
+					sprintf(
3712
+						esc_html__(
3713
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3714
+							'event_espresso'
3715
+						),
3716
+						$query_key,
3717
+						get_class($this),
3718
+						//                      print_r( $this->_allowed_query_params, TRUE )
3719
+						implode(',', $this->_allowed_query_params)
3720
+					)
3721
+				);
3722
+			}
3723
+		}
3724
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3725
+		if (empty($main_model_join_sql)) {
3726
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3727
+		}
3728
+		return $query_object;
3729
+	}
3730
+
3731
+
3732
+	/**
3733
+	 * Gets the where conditions that should be imposed on the query based on the
3734
+	 * context (eg reading frontend, backend, edit or delete).
3735
+	 *
3736
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3737
+	 * @return array @see
3738
+	 *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3739
+	 * @throws EE_Error
3740
+	 */
3741
+	public function caps_where_conditions($context = self::caps_read)
3742
+	{
3743
+		EEM_Base::verify_is_valid_cap_context($context);
3744
+		$cap_where_conditions = [];
3745
+		$cap_restrictions     = $this->caps_missing($context);
3746
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3747
+			$cap_where_conditions = array_replace_recursive(
3748
+				$cap_where_conditions,
3749
+				$restriction_if_no_cap->get_default_where_conditions()
3750
+			);
3751
+		}
3752
+		return apply_filters(
3753
+			'FHEE__EEM_Base__caps_where_conditions__return',
3754
+			$cap_where_conditions,
3755
+			$this,
3756
+			$context,
3757
+			$cap_restrictions
3758
+		);
3759
+	}
3760
+
3761
+
3762
+	/**
3763
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3764
+	 * otherwise throws an exception
3765
+	 *
3766
+	 * @param string $should_be_order_string
3767
+	 * @return string either ASC, asc, DESC or desc
3768
+	 * @throws EE_Error
3769
+	 */
3770
+	private function _extract_order($should_be_order_string)
3771
+	{
3772
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3773
+			return $should_be_order_string;
3774
+		}
3775
+		throw new EE_Error(
3776
+			sprintf(
3777
+				esc_html__(
3778
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3779
+					"event_espresso"
3780
+				),
3781
+				get_class($this),
3782
+				$should_be_order_string
3783
+			)
3784
+		);
3785
+	}
3786
+
3787
+
3788
+	/**
3789
+	 * Looks at all the models which are included in this query, and asks each
3790
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3791
+	 * so they can be merged
3792
+	 *
3793
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3794
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3795
+	 *                                                                  'none' means NO default where conditions will
3796
+	 *                                                                  be used AT ALL during this query.
3797
+	 *                                                                  'other_models_only' means default where
3798
+	 *                                                                  conditions from other models will be used, but
3799
+	 *                                                                  not for this primary model. 'all', the default,
3800
+	 *                                                                  means default where conditions will apply as
3801
+	 *                                                                  normal
3802
+	 * @param array                       $where_query_params
3803
+	 * @return array
3804
+	 * @throws EE_Error
3805
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3806
+	 *                                                                  .md#0-where-conditions
3807
+	 */
3808
+	private function _get_default_where_conditions_for_models_in_query(
3809
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3810
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3811
+		$where_query_params = []
3812
+	) {
3813
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3814
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3815
+			throw new EE_Error(
3816
+				sprintf(
3817
+					esc_html__(
3818
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3819
+						"event_espresso"
3820
+					),
3821
+					$use_default_where_conditions,
3822
+					implode(", ", $allowed_used_default_where_conditions_values)
3823
+				)
3824
+			);
3825
+		}
3826
+		$universal_query_params = [];
3827
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3828
+			$universal_query_params = $this->_get_default_where_conditions();
3829
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3830
+			$universal_query_params = $this->_get_minimum_where_conditions();
3831
+		}
3832
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3833
+			$related_model = $this->get_related_model_obj($model_name);
3834
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3835
+				$related_model_universal_where_params =
3836
+					$related_model->_get_default_where_conditions($model_relation_path);
3837
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3838
+				$related_model_universal_where_params =
3839
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3840
+			} else {
3841
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3842
+				continue;
3843
+			}
3844
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3845
+				$related_model_universal_where_params,
3846
+				$where_query_params,
3847
+				$related_model,
3848
+				$model_relation_path
3849
+			);
3850
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3851
+				$universal_query_params,
3852
+				$overrides
3853
+			);
3854
+		}
3855
+		return $universal_query_params;
3856
+	}
3857
+
3858
+
3859
+	/**
3860
+	 * Determines whether or not we should use default where conditions for the model in question
3861
+	 * (this model, or other related models).
3862
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3863
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3864
+	 * We should use default where conditions on related models when they requested to use default where conditions
3865
+	 * on all models, or specifically just on other related models
3866
+	 *
3867
+	 * @param      $default_where_conditions_value
3868
+	 * @param bool $for_this_model false means this is for OTHER related models
3869
+	 * @return bool
3870
+	 */
3871
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3872
+	{
3873
+		return (
3874
+				   $for_this_model
3875
+				   && in_array(
3876
+					   $default_where_conditions_value,
3877
+					   [
3878
+						   EEM_Base::default_where_conditions_all,
3879
+						   EEM_Base::default_where_conditions_this_only,
3880
+						   EEM_Base::default_where_conditions_minimum_others,
3881
+					   ],
3882
+					   true
3883
+				   )
3884
+			   )
3885
+			   || (
3886
+				   ! $for_this_model
3887
+				   && in_array(
3888
+					   $default_where_conditions_value,
3889
+					   [
3890
+						   EEM_Base::default_where_conditions_all,
3891
+						   EEM_Base::default_where_conditions_others_only,
3892
+					   ],
3893
+					   true
3894
+				   )
3895
+			   );
3896
+	}
3897
+
3898
+
3899
+	/**
3900
+	 * Determines whether or not we should use default minimum conditions for the model in question
3901
+	 * (this model, or other related models).
3902
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3903
+	 * where conditions.
3904
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3905
+	 * on this model or others
3906
+	 *
3907
+	 * @param      $default_where_conditions_value
3908
+	 * @param bool $for_this_model false means this is for OTHER related models
3909
+	 * @return bool
3910
+	 */
3911
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3912
+	{
3913
+		return (
3914
+				   $for_this_model
3915
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3916
+			   )
3917
+			   || (
3918
+				   ! $for_this_model
3919
+				   && in_array(
3920
+					   $default_where_conditions_value,
3921
+					   [
3922
+						   EEM_Base::default_where_conditions_minimum_others,
3923
+						   EEM_Base::default_where_conditions_minimum_all,
3924
+					   ],
3925
+					   true
3926
+				   )
3927
+			   );
3928
+	}
3929
+
3930
+
3931
+	/**
3932
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3933
+	 * then we also add a special where condition which allows for that model's primary key
3934
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3935
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3936
+	 *
3937
+	 * @param array    $default_where_conditions
3938
+	 * @param array    $provided_where_conditions
3939
+	 * @param EEM_Base $model
3940
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3941
+	 * @return array @see
3942
+	 *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3943
+	 * @throws EE_Error
3944
+	 */
3945
+	private function _override_defaults_or_make_null_friendly(
3946
+		$default_where_conditions,
3947
+		$provided_where_conditions,
3948
+		$model,
3949
+		$model_relation_path
3950
+	) {
3951
+		$null_friendly_where_conditions = [];
3952
+		$none_overridden                = true;
3953
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3954
+		foreach ($default_where_conditions as $key => $val) {
3955
+			if (isset($provided_where_conditions[ $key ])) {
3956
+				$none_overridden = false;
3957
+			} else {
3958
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3959
+			}
3960
+		}
3961
+		if ($none_overridden && $default_where_conditions) {
3962
+			if ($model->has_primary_key_field()) {
3963
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3964
+																				   . "."
3965
+																				   . $model->primary_key_name() ] =
3966
+					['IS NULL'];
3967
+			}/*else{
3968 3968
                 //@todo NO PK, use other defaults
3969 3969
             }*/
3970
-        }
3971
-        return $null_friendly_where_conditions;
3972
-    }
3973
-
3974
-
3975
-    /**
3976
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3977
-     * default where conditions on all get_all, update, and delete queries done by this model.
3978
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3979
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3980
-     *
3981
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3982
-     * @return array @see
3983
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3984
-     * @throws EE_Error
3985
-     * @throws EE_Error
3986
-     */
3987
-    private function _get_default_where_conditions($model_relation_path = '')
3988
-    {
3989
-        if ($this->_ignore_where_strategy) {
3990
-            return [];
3991
-        }
3992
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3993
-    }
3994
-
3995
-
3996
-    /**
3997
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3998
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3999
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
4000
-     * NOT array('Event_CPT.post_type'=>'esp_event').
4001
-     * Similar to _get_default_where_conditions
4002
-     *
4003
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
4004
-     * @return array @see
4005
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4006
-     * @throws EE_Error
4007
-     * @throws EE_Error
4008
-     */
4009
-    protected function _get_minimum_where_conditions($model_relation_path = '')
4010
-    {
4011
-        if ($this->_ignore_where_strategy) {
4012
-            return [];
4013
-        }
4014
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4015
-    }
4016
-
4017
-
4018
-    /**
4019
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4020
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4021
-     *
4022
-     * @param EE_Model_Query_Info_Carrier $model_query_info
4023
-     * @return string
4024
-     * @throws EE_Error
4025
-     */
4026
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4027
-    {
4028
-        $selects = $this->_get_columns_to_select_for_this_model();
4029
-        foreach (
4030
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4031
-        ) {
4032
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4033
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4034
-            foreach ($other_model_selects as $key => $value) {
4035
-                $selects[] = $value;
4036
-            }
4037
-        }
4038
-        return implode(", ", $selects);
4039
-    }
4040
-
4041
-
4042
-    /**
4043
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4044
-     * So that's going to be the columns for all the fields on the model
4045
-     *
4046
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
4047
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4048
-     */
4049
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4050
-    {
4051
-        $fields                                       = $this->field_settings();
4052
-        $selects                                      = [];
4053
-        $table_alias_with_model_relation_chain_prefix =
4054
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4055
-                $model_relation_chain,
4056
-                $this->get_this_model_name()
4057
-            );
4058
-        foreach ($fields as $field_obj) {
4059
-            $selects[] = $table_alias_with_model_relation_chain_prefix
4060
-                         . $field_obj->get_table_alias()
4061
-                         . "."
4062
-                         . $field_obj->get_table_column()
4063
-                         . " AS '"
4064
-                         . $table_alias_with_model_relation_chain_prefix
4065
-                         . $field_obj->get_table_alias()
4066
-                         . "."
4067
-                         . $field_obj->get_table_column()
4068
-                         . "'";
4069
-        }
4070
-        // make sure we are also getting the PKs of each table
4071
-        $tables = $this->get_tables();
4072
-        if (count($tables) > 1) {
4073
-            foreach ($tables as $table_obj) {
4074
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4075
-                                       . $table_obj->get_fully_qualified_pk_column();
4076
-                if (! in_array($qualified_pk_column, $selects)) {
4077
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4078
-                }
4079
-            }
4080
-        }
4081
-        return $selects;
4082
-    }
4083
-
4084
-
4085
-    /**
4086
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4087
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4088
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4089
-     * SQL for joining, and the data types
4090
-     *
4091
-     * @param null|string                 $original_query_param
4092
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4093
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4095
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4096
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4097
-     *                                                          or 'Registration's
4098
-     * @param string                      $original_query_param what it originally was (eg
4099
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4100
-     *                                                          matches $query_param
4101
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4102
-     * @throws EE_Error
4103
-     */
4104
-    private function _extract_related_model_info_from_query_param(
4105
-        $query_param,
4106
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4107
-        $query_param_type,
4108
-        $original_query_param = null
4109
-    ) {
4110
-        if ($original_query_param === null) {
4111
-            $original_query_param = $query_param;
4112
-        }
4113
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4114
-        // check to see if we have a field on this model
4115
-        $this_model_fields = $this->field_settings(true);
4116
-        if (array_key_exists($query_param, $this_model_fields)) {
4117
-            $field_is_allowed = in_array(
4118
-                $query_param_type,
4119
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4120
-                true
4121
-            );
4122
-            if ($field_is_allowed) {
4123
-                return;
4124
-            }
4125
-            throw new EE_Error(
4126
-                sprintf(
4127
-                    esc_html__(
4128
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4129
-                        "event_espresso"
4130
-                    ),
4131
-                    $query_param,
4132
-                    get_class($this),
4133
-                    $query_param_type,
4134
-                    $original_query_param
4135
-                )
4136
-            );
4137
-        }
4138
-        // check if this is a special logic query param
4139
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4140
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4141
-            if ($operator_is_allowed) {
4142
-                return;
4143
-            }
4144
-            throw new EE_Error(
4145
-                sprintf(
4146
-                    esc_html__(
4147
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4148
-                        'event_espresso'
4149
-                    ),
4150
-                    implode('", "', $this->_logic_query_param_keys),
4151
-                    $query_param,
4152
-                    get_class($this),
4153
-                    '<br />',
4154
-                    "\t"
4155
-                    . ' $passed_in_query_info = <pre>'
4156
-                    . print_r($passed_in_query_info, true)
4157
-                    . '</pre>'
4158
-                    . "\n\t"
4159
-                    . ' $query_param_type = '
4160
-                    . $query_param_type
4161
-                    . "\n\t"
4162
-                    . ' $original_query_param = '
4163
-                    . $original_query_param
4164
-                )
4165
-            );
4166
-        }
4167
-        // check if it's a custom selection
4168
-        if (
4169
-            $this->_custom_selections instanceof CustomSelects
4170
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4171
-        ) {
4172
-            return;
4173
-        }
4174
-        // check if has a model name at the beginning
4175
-        // and
4176
-        // check if it's a field on a related model
4177
-        if (
4178
-            $this->extractJoinModelFromQueryParams(
4179
-                $passed_in_query_info,
4180
-                $query_param,
4181
-                $original_query_param,
4182
-                $query_param_type
4183
-            )
4184
-        ) {
4185
-            return;
4186
-        }
4187
-
4188
-        // ok so $query_param didn't start with a model name
4189
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4190
-        // it's wack, that's what it is
4191
-        throw new EE_Error(
4192
-            sprintf(
4193
-                esc_html__(
4194
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4195
-                    "event_espresso"
4196
-                ),
4197
-                $query_param,
4198
-                get_class($this),
4199
-                $query_param_type,
4200
-                $original_query_param
4201
-            )
4202
-        );
4203
-    }
4204
-
4205
-
4206
-    /**
4207
-     * Extracts any possible join model information from the provided possible_join_string.
4208
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4209
-     * join
4210
-     * parts that should be added to the query.
4211
-     *
4212
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4213
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4214
-     * @param null|string                 $original_query_param
4215
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4216
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4217
-     *                                                           etc.)
4218
-     * @return bool  returns true if a join was added and false if not.
4219
-     * @throws EE_Error
4220
-     */
4221
-    private function extractJoinModelFromQueryParams(
4222
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4223
-        $possible_join_string,
4224
-        $original_query_param,
4225
-        $query_parameter_type
4226
-    ) {
4227
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4228
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4229
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4230
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4231
-                if ($possible_join_string === '') {
4232
-                    // nothing left to $query_param
4233
-                    // we should actually end in a field name, not a model like this!
4234
-                    throw new EE_Error(
4235
-                        sprintf(
4236
-                            esc_html__(
4237
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4238
-                                "event_espresso"
4239
-                            ),
4240
-                            $possible_join_string,
4241
-                            $query_parameter_type,
4242
-                            get_class($this),
4243
-                            $valid_related_model_name
4244
-                        )
4245
-                    );
4246
-                }
4247
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4248
-                $related_model_obj->_extract_related_model_info_from_query_param(
4249
-                    $possible_join_string,
4250
-                    $query_info_carrier,
4251
-                    $query_parameter_type,
4252
-                    $original_query_param
4253
-                );
4254
-                return true;
4255
-            }
4256
-            if ($possible_join_string === $valid_related_model_name) {
4257
-                $this->_add_join_to_model(
4258
-                    $valid_related_model_name,
4259
-                    $query_info_carrier,
4260
-                    $original_query_param
4261
-                );
4262
-                return true;
4263
-            }
4264
-        }
4265
-        return false;
4266
-    }
4267
-
4268
-
4269
-    /**
4270
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4271
-     *
4272
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4273
-     * @throws EE_Error
4274
-     */
4275
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4276
-    {
4277
-        if (
4278
-            $this->_custom_selections instanceof CustomSelects
4279
-            && (
4280
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4281
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4282
-            )
4283
-        ) {
4284
-            $original_selects = $this->_custom_selections->originalSelects();
4285
-            foreach ($original_selects as $alias => $select_configuration) {
4286
-                $this->extractJoinModelFromQueryParams(
4287
-                    $query_info_carrier,
4288
-                    $select_configuration[0],
4289
-                    $select_configuration[0],
4290
-                    'custom_selects'
4291
-                );
4292
-            }
4293
-        }
4294
-    }
4295
-
4296
-
4297
-    /**
4298
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4299
-     * and store it on $passed_in_query_info
4300
-     *
4301
-     * @param string                      $model_name
4302
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4303
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4304
-     *                                                          model and $model_name. Eg, if we are querying Event,
4305
-     *                                                          and are adding a join to 'Payment' with the original
4306
-     *                                                          query param key
4307
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4308
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4309
-     *                                                          Payment wants to add default query params so that it
4310
-     *                                                          will know what models to prepend onto its default query
4311
-     *                                                          params or in case it wants to rename tables (in case
4312
-     *                                                          there are multiple joins to the same table)
4313
-     * @return void
4314
-     * @throws EE_Error
4315
-     */
4316
-    private function _add_join_to_model(
4317
-        $model_name,
4318
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4319
-        $original_query_param
4320
-    ) {
4321
-        $relation_obj         = $this->related_settings_for($model_name);
4322
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4323
-        // check if the relation is HABTM, because then we're essentially doing two joins
4324
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4325
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4326
-            $join_model_obj = $relation_obj->get_join_model();
4327
-            // replace the model specified with the join model for this relation chain, whi
4328
-            $relation_chain_to_join_model =
4329
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4330
-                    $model_name,
4331
-                    $join_model_obj->get_this_model_name(),
4332
-                    $model_relation_chain
4333
-                );
4334
-            $passed_in_query_info->merge(
4335
-                new EE_Model_Query_Info_Carrier(
4336
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4337
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4338
-                )
4339
-            );
4340
-        }
4341
-        // now just join to the other table pointed to by the relation object, and add its data types
4342
-        $passed_in_query_info->merge(
4343
-            new EE_Model_Query_Info_Carrier(
4344
-                [$model_relation_chain => $model_name],
4345
-                $relation_obj->get_join_statement($model_relation_chain)
4346
-            )
4347
-        );
4348
-    }
4349
-
4350
-
4351
-    /**
4352
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4353
-     *
4354
-     * @param array $where_params @see
4355
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4356
-     * @return string of SQL
4357
-     * @throws EE_Error
4358
-     */
4359
-    private function _construct_where_clause($where_params)
4360
-    {
4361
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4362
-        if ($SQL) {
4363
-            return " WHERE " . $SQL;
4364
-        }
4365
-        return '';
4366
-    }
4367
-
4368
-
4369
-    /**
4370
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4371
-     * and should be passed HAVING parameters, not WHERE parameters
4372
-     *
4373
-     * @param array $having_params
4374
-     * @return string
4375
-     * @throws EE_Error
4376
-     */
4377
-    private function _construct_having_clause($having_params)
4378
-    {
4379
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4380
-        if ($SQL) {
4381
-            return " HAVING " . $SQL;
4382
-        }
4383
-        return '';
4384
-    }
4385
-
4386
-
4387
-    /**
4388
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4389
-     * Event_Meta.meta_value = 'foo'))"
4390
-     *
4391
-     * @param array  $where_params @see
4392
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4393
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4394
-     * @return string of SQL
4395
-     * @throws EE_Error
4396
-     */
4397
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4398
-    {
4399
-        $where_clauses = [];
4400
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4401
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4402
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4403
-                switch ($query_param) {
4404
-                    case 'not':
4405
-                    case 'NOT':
4406
-                        $where_clauses[] = "! ("
4407
-                                           . $this->_construct_condition_clause_recursive(
4408
-                                               $op_and_value_or_sub_condition,
4409
-                                               $glue
4410
-                                           )
4411
-                                           . ")";
4412
-                        break;
4413
-                    case 'and':
4414
-                    case 'AND':
4415
-                        $where_clauses[] = " ("
4416
-                                           . $this->_construct_condition_clause_recursive(
4417
-                                               $op_and_value_or_sub_condition,
4418
-                                               ' AND '
4419
-                                           )
4420
-                                           . ")";
4421
-                        break;
4422
-                    case 'or':
4423
-                    case 'OR':
4424
-                        $where_clauses[] = " ("
4425
-                                           . $this->_construct_condition_clause_recursive(
4426
-                                               $op_and_value_or_sub_condition,
4427
-                                               ' OR '
4428
-                                           )
4429
-                                           . ")";
4430
-                        break;
4431
-                }
4432
-            } else {
4433
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4434
-                // if it's not a normal field, maybe it's a custom selection?
4435
-                if (! $field_obj) {
4436
-                    if ($this->_custom_selections instanceof CustomSelects) {
4437
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4438
-                    } else {
4439
-                        throw new EE_Error(
4440
-                            sprintf(
4441
-                                esc_html__(
4442
-                                    "%s is neither a valid model field name, nor a custom selection",
4443
-                                    "event_espresso"
4444
-                                ),
4445
-                                $query_param
4446
-                            )
4447
-                        );
4448
-                    }
4449
-                }
4450
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4451
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4452
-            }
4453
-        }
4454
-        return $where_clauses
4455
-            ? implode($glue, $where_clauses)
4456
-            : '';
4457
-    }
4458
-
4459
-
4460
-    /**
4461
-     * Takes the input parameter and extract the table name (alias) and column name
4462
-     *
4463
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4464
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4465
-     * @throws EE_Error
4466
-     */
4467
-    private function _deduce_column_name_from_query_param($query_param)
4468
-    {
4469
-        $field = $this->_deduce_field_from_query_param($query_param);
4470
-        if ($field) {
4471
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4472
-                $field->get_model_name(),
4473
-                $query_param
4474
-            );
4475
-            return $table_alias_prefix . $field->get_qualified_column();
4476
-        }
4477
-        if (
4478
-            $this->_custom_selections instanceof CustomSelects
4479
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4480
-        ) {
4481
-            // maybe it's custom selection item?
4482
-            // if so, just use it as the "column name"
4483
-            return $query_param;
4484
-        }
4485
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4486
-            ? implode(',', $this->_custom_selections->columnAliases())
4487
-            : '';
4488
-        throw new EE_Error(
4489
-            sprintf(
4490
-                esc_html__(
4491
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4492
-                    "event_espresso"
4493
-                ),
4494
-                $query_param,
4495
-                $custom_select_aliases
4496
-            )
4497
-        );
4498
-    }
4499
-
4500
-
4501
-    /**
4502
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4503
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4504
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4505
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4506
-     *
4507
-     * @param string $condition_query_param_key
4508
-     * @return string
4509
-     */
4510
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4511
-    {
4512
-        $pos_of_star = strpos($condition_query_param_key, '*');
4513
-        if ($pos_of_star === false) {
4514
-            return $condition_query_param_key;
4515
-        }
4516
-        return substr($condition_query_param_key, 0, $pos_of_star);
4517
-    }
4518
-
4519
-
4520
-    /**
4521
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4522
-     *
4523
-     * @param array|string               $op_and_value
4524
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4525
-     * @return string
4526
-     * @throws EE_Error
4527
-     */
4528
-    private function _construct_op_and_value($op_and_value, $field_obj)
4529
-    {
4530
-        $operator = '=';
4531
-        $value    = $op_and_value;
4532
-        if (is_array($op_and_value)) {
4533
-            $operator = isset($op_and_value[0])
4534
-                ? $this->_prepare_operator_for_sql($op_and_value[0])
4535
-                : null;
4536
-            if (! $operator) {
4537
-                $php_array_like_string = [];
4538
-                foreach ($op_and_value as $key => $value) {
4539
-                    $value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4540
-                    $php_array_like_string[] = "$key=>$value";
4541
-                }
4542
-                throw new EE_Error(
4543
-                    sprintf(
4544
-                        esc_html__(
4545
-                            "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))",
4546
-                            "event_espresso"
4547
-                        ),
4548
-                        implode(",", $php_array_like_string)
4549
-                    )
4550
-                );
4551
-            }
4552
-            $value = $op_and_value[1] ?? null;
4553
-        }
4554
-
4555
-        // check to see if the value is actually another field
4556
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4557
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4558
-        }
4559
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4560
-            // in this case, the value should be an array, or at least a comma-separated list
4561
-            // it will need to handle a little differently
4562
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4563
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4564
-            return $operator . SP . $cleaned_value;
4565
-        }
4566
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4567
-            // the value should be an array with count of two.
4568
-            if (count($value) !== 2) {
4569
-                throw new EE_Error(
4570
-                    sprintf(
4571
-                        esc_html__(
4572
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4573
-                            'event_espresso'
4574
-                        ),
4575
-                        "BETWEEN"
4576
-                    )
4577
-                );
4578
-            }
4579
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4580
-            return $operator . SP . $cleaned_value;
4581
-        }
4582
-        if (in_array($operator, $this->valid_null_style_operators())) {
4583
-            if ($value !== null) {
4584
-                throw new EE_Error(
4585
-                    sprintf(
4586
-                        esc_html__(
4587
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4588
-                            "event_espresso"
4589
-                        ),
4590
-                        $value,
4591
-                        $operator
4592
-                    )
4593
-                );
4594
-            }
4595
-            return $operator;
4596
-        }
4597
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4598
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4599
-            // remove other junk. So just treat it as a string.
4600
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4601
-        }
4602
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4603
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4604
-        }
4605
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4606
-            throw new EE_Error(
4607
-                sprintf(
4608
-                    esc_html__(
4609
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4610
-                        'event_espresso'
4611
-                    ),
4612
-                    $operator,
4613
-                    $operator
4614
-                )
4615
-            );
4616
-        }
4617
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4618
-            throw new EE_Error(
4619
-                sprintf(
4620
-                    esc_html__(
4621
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4622
-                        'event_espresso'
4623
-                    ),
4624
-                    $operator,
4625
-                    $operator
4626
-                )
4627
-            );
4628
-        }
4629
-        throw new EE_Error(
4630
-            sprintf(
4631
-                esc_html__(
4632
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4633
-                    "event_espresso"
4634
-                ),
4635
-                http_build_query($op_and_value)
4636
-            )
4637
-        );
4638
-    }
4639
-
4640
-
4641
-    /**
4642
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4643
-     *
4644
-     * @param array                      $values
4645
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4646
-     *                                              '%s'
4647
-     * @return string
4648
-     * @throws EE_Error
4649
-     */
4650
-    public function _construct_between_value($values, $field_obj)
4651
-    {
4652
-        $cleaned_values = [];
4653
-        foreach ($values as $value) {
4654
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4655
-        }
4656
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4657
-    }
4658
-
4659
-
4660
-    /**
4661
-     * Takes an array or a comma-separated list of $values and cleans them
4662
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4663
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4664
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4665
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4666
-     *
4667
-     * @param mixed                      $values    array or comma-separated string
4668
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4669
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4670
-     * @throws EE_Error
4671
-     */
4672
-    public function _construct_in_value($values, $field_obj)
4673
-    {
4674
-        $prepped = [];
4675
-        // check if the value is a CSV list
4676
-        if (is_string($values)) {
4677
-            // in which case, turn it into an array
4678
-            $values = explode(',', $values);
4679
-        }
4680
-        // make sure we only have one of each value in the list
4681
-        $values = array_unique($values);
4682
-        foreach ($values as $value) {
4683
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4684
-        }
4685
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4686
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4687
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4688
-        if (empty($prepped)) {
4689
-            $all_fields  = $this->field_settings();
4690
-            $first_field = reset($all_fields);
4691
-            $main_table  = $this->_get_main_table();
4692
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4693
-        }
4694
-        return '(' . implode(',', $prepped) . ')';
4695
-    }
4696
-
4697
-
4698
-    /**
4699
-     * @param mixed                      $value
4700
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4701
-     * @return false|null|string
4702
-     * @throws EE_Error
4703
-     */
4704
-    private function _wpdb_prepare_using_field($value, $field_obj)
4705
-    {
4706
-        /** @type WPDB $wpdb */
4707
-        global $wpdb;
4708
-        if ($field_obj instanceof EE_Model_Field_Base) {
4709
-            return $wpdb->prepare(
4710
-                $field_obj->get_wpdb_data_type(),
4711
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4712
-            );
4713
-        } //$field_obj should really just be a data type
4714
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4715
-            throw new EE_Error(
4716
-                sprintf(
4717
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4718
-                    $field_obj,
4719
-                    implode(",", $this->_valid_wpdb_data_types)
4720
-                )
4721
-            );
4722
-        }
4723
-        return $wpdb->prepare($field_obj, $value);
4724
-    }
4725
-
4726
-
4727
-    /**
4728
-     * Takes the input parameter and finds the model field that it indicates.
4729
-     *
4730
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4731
-     * @return EE_Model_Field_Base
4732
-     * @throws EE_Error
4733
-     */
4734
-    protected function _deduce_field_from_query_param($query_param_name)
4735
-    {
4736
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4737
-        // which will help us find the database table and column
4738
-        $query_param_parts = explode(".", $query_param_name);
4739
-        if (empty($query_param_parts)) {
4740
-            throw new EE_Error(
4741
-                sprintf(
4742
-                    esc_html__(
4743
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4744
-                        'event_espresso'
4745
-                    ),
4746
-                    $query_param_name
4747
-                )
4748
-            );
4749
-        }
4750
-        $number_of_parts       = count($query_param_parts);
4751
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4752
-        if ($number_of_parts === 1) {
4753
-            $field_name = $last_query_param_part;
4754
-            $model_obj  = $this;
4755
-        } else {// $number_of_parts >= 2
4756
-            // the last part is the column name, and there are only 2parts. therefore...
4757
-            $field_name = $last_query_param_part;
4758
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4759
-        }
4760
-        try {
4761
-            return $model_obj->field_settings_for($field_name);
4762
-        } catch (EE_Error $e) {
4763
-            return null;
4764
-        }
4765
-    }
4766
-
4767
-
4768
-    /**
4769
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4770
-     * alias and column which corresponds to it
4771
-     *
4772
-     * @param string $field_name
4773
-     * @return string
4774
-     * @throws EE_Error
4775
-     */
4776
-    public function _get_qualified_column_for_field($field_name)
4777
-    {
4778
-        $all_fields = $this->field_settings();
4779
-        $field      = $all_fields[ $field_name ] ?? false;
4780
-        if ($field) {
4781
-            return $field->get_qualified_column();
4782
-        }
4783
-        throw new EE_Error(
4784
-            sprintf(
4785
-                esc_html__(
4786
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4787
-                    'event_espresso'
4788
-                ),
4789
-                $field_name,
4790
-                get_class($this)
4791
-            )
4792
-        );
4793
-    }
4794
-
4795
-
4796
-    /**
4797
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4798
-     * Example usage:
4799
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4800
-     *      array(),
4801
-     *      ARRAY_A,
4802
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4803
-     *  );
4804
-     * is equivalent to
4805
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4806
-     * and
4807
-     *  EEM_Event::instance()->get_all_wpdb_results(
4808
-     *      array(
4809
-     *          array(
4810
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4811
-     *          ),
4812
-     *          ARRAY_A,
4813
-     *          implode(
4814
-     *              ', ',
4815
-     *              array_merge(
4816
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4817
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4818
-     *              )
4819
-     *          )
4820
-     *      )
4821
-     *  );
4822
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4823
-     *
4824
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4825
-     *                                            and the one whose fields you are selecting for example: when querying
4826
-     *                                            tickets model and selecting fields from the tickets model you would
4827
-     *                                            leave this parameter empty, because no models are needed to join
4828
-     *                                            between the queried model and the selected one. Likewise when
4829
-     *                                            querying the datetime model and selecting fields from the tickets
4830
-     *                                            model, it would also be left empty, because there is a direct
4831
-     *                                            relation from datetimes to tickets, so no model is needed to join
4832
-     *                                            them together. However, when querying from the event model and
4833
-     *                                            selecting fields from the ticket model, you should provide the string
4834
-     *                                            'Datetime', indicating that the event model must first join to the
4835
-     *                                            datetime model in order to find its relation to ticket model.
4836
-     *                                            Also, when querying from the venue model and selecting fields from
4837
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4838
-     *                                            indicating you need to join the venue model to the event model,
4839
-     *                                            to the datetime model, in order to find its relation to the ticket
4840
-     *                                            model. This string is used to deduce the prefix that gets added onto
4841
-     *                                            the models' tables qualified columns
4842
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4843
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4844
-     *                                            qualified column names
4845
-     * @return array|string
4846
-     */
4847
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4848
-    {
4849
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4850
-                ? ''
4851
-                : '__');
4852
-        $qualified_columns = [];
4853
-        foreach ($this->field_settings() as $field_name => $field) {
4854
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4855
-        }
4856
-        return $return_string
4857
-            ? implode(', ', $qualified_columns)
4858
-            : $qualified_columns;
4859
-    }
4860
-
4861
-
4862
-    /**
4863
-     * constructs the select use on special limit joins
4864
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4865
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4866
-     * (as that is typically where the limits would be set).
4867
-     *
4868
-     * @param string       $table_alias The table the select is being built for
4869
-     * @param mixed|string $limit       The limit for this select
4870
-     * @return string                The final select join element for the query.
4871
-     * @throws EE_Error
4872
-     * @throws EE_Error
4873
-     */
4874
-    public function _construct_limit_join_select($table_alias, $limit)
4875
-    {
4876
-        $SQL = '';
4877
-        foreach ($this->_tables as $table_obj) {
4878
-            if ($table_obj instanceof EE_Primary_Table) {
4879
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4880
-                    ? $table_obj->get_select_join_limit($limit)
4881
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4882
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4883
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4884
-                    ? $table_obj->get_select_join_limit_join($limit)
4885
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4886
-            }
4887
-        }
4888
-        return $SQL;
4889
-    }
4890
-
4891
-
4892
-    /**
4893
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4894
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4895
-     *
4896
-     * @return string SQL
4897
-     * @throws EE_Error
4898
-     */
4899
-    public function _construct_internal_join()
4900
-    {
4901
-        $SQL = $this->_get_main_table()->get_table_sql();
4902
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4903
-        return $SQL;
4904
-    }
4905
-
4906
-
4907
-    /**
4908
-     * Constructs the SQL for joining all the tables on this model.
4909
-     * Normally $alias should be the primary table's alias, but in cases where
4910
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4911
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4912
-     * alias, this will construct SQL like:
4913
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4914
-     * With $alias being a secondary table's alias, this will construct SQL like:
4915
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4916
-     *
4917
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4918
-     * @return string
4919
-     * @throws EE_Error
4920
-     * @throws EE_Error
4921
-     */
4922
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4923
-    {
4924
-        $SQL               = '';
4925
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4926
-        foreach ($this->_tables as $table_obj) {
4927
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4928
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4929
-                    // so we're joining to this table, meaning the table is already in
4930
-                    // the FROM statement, BUT the primary table isn't. So we want
4931
-                    // to add the inverse join sql
4932
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4933
-                } else {
4934
-                    // just add a regular JOIN to this table from the primary table
4935
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4936
-                }
4937
-            }// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4938
-        }
4939
-        return $SQL;
4940
-    }
4941
-
4942
-
4943
-    /**
4944
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4945
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4946
-     * their data type (eg, '%s', '%d', etc)
4947
-     *
4948
-     * @return array
4949
-     */
4950
-    public function _get_data_types()
4951
-    {
4952
-        $data_types = [];
4953
-        foreach ($this->field_settings() as $field_obj) {
4954
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4955
-            /** @var $field_obj EE_Model_Field_Base */
4956
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4957
-        }
4958
-        return $data_types;
4959
-    }
4960
-
4961
-
4962
-    /**
4963
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4964
-     *
4965
-     * @param string $model_name
4966
-     * @return EEM_Base
4967
-     * @throws EE_Error
4968
-     */
4969
-    public function get_related_model_obj($model_name)
4970
-    {
4971
-        $model_classname = "EEM_" . $model_name;
4972
-        if (! class_exists($model_classname)) {
4973
-            throw new EE_Error(
4974
-                sprintf(
4975
-                    esc_html__(
4976
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4977
-                        'event_espresso'
4978
-                    ),
4979
-                    $model_name,
4980
-                    $model_classname
4981
-                )
4982
-            );
4983
-        }
4984
-        return call_user_func($model_classname . "::instance");
4985
-    }
4986
-
4987
-
4988
-    /**
4989
-     * Returns the array of EE_ModelRelations for this model.
4990
-     *
4991
-     * @return EE_Model_Relation_Base[]
4992
-     */
4993
-    public function relation_settings()
4994
-    {
4995
-        return $this->_model_relations;
4996
-    }
4997
-
4998
-
4999
-    /**
5000
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
5001
-     * because without THOSE models, this model probably doesn't have much purpose.
5002
-     * (Eg, without an event, datetimes have little purpose.)
5003
-     *
5004
-     * @return EE_Belongs_To_Relation[]
5005
-     */
5006
-    public function belongs_to_relations()
5007
-    {
5008
-        $belongs_to_relations = [];
5009
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
5010
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
5011
-                $belongs_to_relations[ $model_name ] = $relation_obj;
5012
-            }
5013
-        }
5014
-        return $belongs_to_relations;
5015
-    }
5016
-
5017
-
5018
-    /**
5019
-     * Returns the specified EE_Model_Relation, or throws an exception
5020
-     *
5021
-     * @param string $relation_name name of relation, key in $this->_relatedModels
5022
-     * @return EE_Model_Relation_Base
5023
-     * @throws EE_Error
5024
-     */
5025
-    public function related_settings_for($relation_name)
5026
-    {
5027
-        $relatedModels = $this->relation_settings();
5028
-        if (! array_key_exists($relation_name, $relatedModels)) {
5029
-            throw new EE_Error(
5030
-                sprintf(
5031
-                    esc_html__(
5032
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5033
-                        'event_espresso'
5034
-                    ),
5035
-                    $relation_name,
5036
-                    $this->_get_class_name(),
5037
-                    implode(', ', array_keys($relatedModels))
5038
-                )
5039
-            );
5040
-        }
5041
-        return $relatedModels[ $relation_name ];
5042
-    }
5043
-
5044
-
5045
-    /**
5046
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5047
-     * fields
5048
-     *
5049
-     * @param string  $fieldName
5050
-     * @param boolean $include_db_only_fields
5051
-     * @return EE_Model_Field_Base
5052
-     * @throws EE_Error
5053
-     */
5054
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
5055
-    {
5056
-        $fieldSettings = $this->field_settings($include_db_only_fields);
5057
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5058
-            throw new EE_Error(
5059
-                sprintf(
5060
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5061
-                    $fieldName,
5062
-                    get_class($this)
5063
-                )
5064
-            );
5065
-        }
5066
-        return $fieldSettings[ $fieldName ];
5067
-    }
5068
-
5069
-
5070
-    /**
5071
-     * Checks if this field exists on this model
5072
-     *
5073
-     * @param string $fieldName a key in the model's _field_settings array
5074
-     * @return boolean
5075
-     */
5076
-    public function has_field($fieldName)
5077
-    {
5078
-        $fieldSettings = $this->field_settings(true);
5079
-        if (isset($fieldSettings[ $fieldName ])) {
5080
-            return true;
5081
-        }
5082
-        return false;
5083
-    }
5084
-
5085
-
5086
-    /**
5087
-     * Returns whether or not this model has a relation to the specified model
5088
-     *
5089
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5090
-     * @return boolean
5091
-     */
5092
-    public function has_relation($relation_name)
5093
-    {
5094
-        $relations = $this->relation_settings();
5095
-        if (isset($relations[ $relation_name ])) {
5096
-            return true;
5097
-        }
5098
-        return false;
5099
-    }
5100
-
5101
-
5102
-    /**
5103
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5104
-     * Eg, on EE_Answer that would be ANS_ID field object
5105
-     *
5106
-     * @param $field_obj
5107
-     * @return boolean
5108
-     */
5109
-    public function is_primary_key_field($field_obj): bool
5110
-    {
5111
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5112
-    }
5113
-
5114
-
5115
-    /**
5116
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5117
-     * Eg, on EE_Answer that would be ANS_ID field object
5118
-     *
5119
-     * @return EE_Primary_Key_Field_Base
5120
-     * @throws EE_Error
5121
-     */
5122
-    public function get_primary_key_field()
5123
-    {
5124
-        if ($this->_primary_key_field === null) {
5125
-            foreach ($this->field_settings(true) as $field_obj) {
5126
-                if ($this->is_primary_key_field($field_obj)) {
5127
-                    $this->_primary_key_field = $field_obj;
5128
-                    break;
5129
-                }
5130
-            }
5131
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5132
-                throw new EE_Error(
5133
-                    sprintf(
5134
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5135
-                        get_class($this)
5136
-                    )
5137
-                );
5138
-            }
5139
-        }
5140
-        return $this->_primary_key_field;
5141
-    }
5142
-
5143
-
5144
-    /**
5145
-     * Returns whether or not not there is a primary key on this model.
5146
-     * Internally does some caching.
5147
-     *
5148
-     * @return boolean
5149
-     */
5150
-    public function has_primary_key_field()
5151
-    {
5152
-        if ($this->_has_primary_key_field === null) {
5153
-            try {
5154
-                $this->get_primary_key_field();
5155
-                $this->_has_primary_key_field = true;
5156
-            } catch (EE_Error $e) {
5157
-                $this->_has_primary_key_field = false;
5158
-            }
5159
-        }
5160
-        return $this->_has_primary_key_field;
5161
-    }
5162
-
5163
-
5164
-    /**
5165
-     * Finds the first field of type $field_class_name.
5166
-     *
5167
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5168
-     *                                 EE_Foreign_Key_Field, etc
5169
-     * @return EE_Model_Field_Base or null if none is found
5170
-     */
5171
-    public function get_a_field_of_type($field_class_name)
5172
-    {
5173
-        foreach ($this->field_settings() as $field) {
5174
-            if ($field instanceof $field_class_name) {
5175
-                return $field;
5176
-            }
5177
-        }
5178
-        return null;
5179
-    }
5180
-
5181
-
5182
-    /**
5183
-     * Gets a foreign key field pointing to model.
5184
-     *
5185
-     * @param string $model_name eg Event, Registration, not EEM_Event
5186
-     * @return EE_Foreign_Key_Field_Base
5187
-     * @throws EE_Error
5188
-     */
5189
-    public function get_foreign_key_to($model_name)
5190
-    {
5191
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
-            foreach ($this->field_settings() as $field) {
5193
-                if (
5194
-                    $field instanceof EE_Foreign_Key_Field_Base
5195
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5196
-                ) {
5197
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5198
-                    break;
5199
-                }
5200
-            }
5201
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5202
-                throw new EE_Error(
5203
-                    sprintf(
5204
-                        esc_html__(
5205
-                            "There is no foreign key field pointing to model %s on model %s",
5206
-                            'event_espresso'
5207
-                        ),
5208
-                        $model_name,
5209
-                        get_class($this)
5210
-                    )
5211
-                );
5212
-            }
5213
-        }
5214
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5215
-    }
5216
-
5217
-
5218
-    /**
5219
-     * Gets the table name (including $wpdb->prefix) for the table alias
5220
-     *
5221
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5222
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5223
-     *                            Either one works
5224
-     * @return string
5225
-     */
5226
-    public function get_table_for_alias($table_alias)
5227
-    {
5228
-        $table_alias_sans_model_relation_chain_prefix =
5229
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5230
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5231
-    }
5232
-
5233
-
5234
-    /**
5235
-     * Returns a flat array of all field son this model, instead of organizing them
5236
-     * by table_alias as they are in the constructor.
5237
-     *
5238
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5239
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5240
-     */
5241
-    public function field_settings($include_db_only_fields = false)
5242
-    {
5243
-        if ($include_db_only_fields) {
5244
-            if ($this->_cached_fields === null) {
5245
-                $this->_cached_fields = [];
5246
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5247
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5249
-                    }
5250
-                }
5251
-            }
5252
-            return $this->_cached_fields;
5253
-        }
5254
-        if ($this->_cached_fields_non_db_only === null) {
5255
-            $this->_cached_fields_non_db_only = [];
5256
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5257
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5258
-                    /** @var $field_obj EE_Model_Field_Base */
5259
-                    if (! $field_obj->is_db_only_field()) {
5260
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5261
-                    }
5262
-                }
5263
-            }
5264
-        }
5265
-        return $this->_cached_fields_non_db_only;
5266
-    }
5267
-
5268
-
5269
-    /**
5270
-     *        cycle though array of attendees and create objects out of each item
5271
-     *
5272
-     * @access        private
5273
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5274
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5275
-     *                           numerically indexed)
5276
-     * @throws EE_Error
5277
-     * @throws ReflectionException
5278
-     */
5279
-    protected function _create_objects($rows = [])
5280
-    {
5281
-        $array_of_objects = [];
5282
-        if (empty($rows)) {
5283
-            return [];
5284
-        }
5285
-        $count_if_model_has_no_primary_key = 0;
5286
-        $has_primary_key                   = $this->has_primary_key_field();
5287
-        $primary_key_field                 = $has_primary_key
5288
-            ? $this->get_primary_key_field()
5289
-            : null;
5290
-        foreach ((array) $rows as $row) {
5291
-            if (empty($row)) {
5292
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5293
-                return [];
5294
-            }
5295
-            // check if we've already set this object in the results array,
5296
-            // in which case there's no need to process it further (again)
5297
-            if ($has_primary_key) {
5298
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5299
-                    $row,
5300
-                    $primary_key_field->get_qualified_column(),
5301
-                    $primary_key_field->get_table_column()
5302
-                );
5303
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5304
-                    continue;
5305
-                }
5306
-            }
5307
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5308
-            if (! $classInstance) {
5309
-                throw new EE_Error(
5310
-                    sprintf(
5311
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5312
-                        $this->get_this_model_name(),
5313
-                        http_build_query($row)
5314
-                    )
5315
-                );
5316
-            }
5317
-            // set the timezone on the instantiated objects
5318
-            $classInstance->set_timezone($this->_timezone);
5319
-            // make sure if there is any timezone setting present that we set the timezone for the object
5320
-            $key                      = $has_primary_key
5321
-                ? $classInstance->ID()
5322
-                : $count_if_model_has_no_primary_key++;
5323
-            $array_of_objects[ $key ] = $classInstance;
5324
-            // also, for all the relations of type BelongsTo, see if we can cache
5325
-            // those related models
5326
-            // (we could do this for other relations too, but if there are conditions
5327
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5328
-            // so it requires a little more thought than just caching them immediately...)
5329
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5330
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5331
-                    // check if this model's INFO is present. If so, cache it on the model
5332
-                    $other_model           = $relation_obj->get_other_model();
5333
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5334
-                    // if we managed to make a model object from the results, cache it on the main model object
5335
-                    if ($other_model_obj_maybe) {
5336
-                        // set timezone on these other model objects if they are present
5337
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5338
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5339
-                    }
5340
-                }
5341
-            }
5342
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5343
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5344
-            // the field in the CustomSelects object
5345
-            if ($this->_custom_selections instanceof CustomSelects) {
5346
-                $classInstance->setCustomSelectsValues(
5347
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5348
-                );
5349
-            }
5350
-        }
5351
-        return $array_of_objects;
5352
-    }
5353
-
5354
-
5355
-    /**
5356
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5357
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5358
-     *
5359
-     * @param array $db_results_row
5360
-     * @return array
5361
-     */
5362
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5363
-    {
5364
-        $results = [];
5365
-        if ($this->_custom_selections instanceof CustomSelects) {
5366
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5367
-                if (isset($db_results_row[ $alias ])) {
5368
-                    $results[ $alias ] = $this->convertValueToDataType(
5369
-                        $db_results_row[ $alias ],
5370
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5371
-                    );
5372
-                }
5373
-            }
5374
-        }
5375
-        return $results;
5376
-    }
5377
-
5378
-
5379
-    /**
5380
-     * This will set the value for the given alias
5381
-     *
5382
-     * @param string $value
5383
-     * @param string $datatype (one of %d, %s, %f)
5384
-     * @return int|string|float (int for %d, string for %s, float for %f)
5385
-     */
5386
-    protected function convertValueToDataType($value, $datatype)
5387
-    {
5388
-        switch ($datatype) {
5389
-            case '%f':
5390
-                return (float) $value;
5391
-            case '%d':
5392
-                return (int) $value;
5393
-            default:
5394
-                return (string) $value;
5395
-        }
5396
-    }
5397
-
5398
-
5399
-    /**
5400
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5401
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5402
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5403
-     * object (as set in the model_field!).
5404
-     *
5405
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5406
-     * @throws EE_Error
5407
-     * @throws ReflectionException
5408
-     */
5409
-    public function create_default_object()
5410
-    {
5411
-        $this_model_fields_and_values = [];
5412
-        // setup the row using default values;
5413
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5414
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5415
-        }
5416
-        $className = $this->_get_class_name();
5417
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5418
-    }
5419
-
5420
-
5421
-    /**
5422
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5423
-     *                             or an stdClass where each property is the name of a column,
5424
-     * @return EE_Base_Class
5425
-     * @throws EE_Error
5426
-     * @throws ReflectionException
5427
-     */
5428
-    public function instantiate_class_from_array_or_object($cols_n_values)
5429
-    {
5430
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5431
-            $cols_n_values = get_object_vars($cols_n_values);
5432
-        }
5433
-        $primary_key = null;
5434
-        // make sure the array only has keys that are fields/columns on this model
5435
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5436
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5437
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5438
-        }
5439
-        $className = $this->_get_class_name();
5440
-        // check we actually found results that we can use to build our model object
5441
-        // if not, return null
5442
-        if ($this->has_primary_key_field()) {
5443
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5444
-                return null;
5445
-            }
5446
-        } elseif ($this->unique_indexes()) {
5447
-            $first_column = reset($this_model_fields_n_values);
5448
-            if (empty($first_column)) {
5449
-                return null;
5450
-            }
5451
-        }
5452
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5453
-        if ($primary_key) {
5454
-            $classInstance = $this->get_from_entity_map($primary_key);
5455
-            if (! $classInstance) {
5456
-                $classInstance = EE_Registry::instance()
5457
-                                            ->load_class(
5458
-                                                $className,
5459
-                                                [$this_model_fields_n_values, $this->_timezone],
5460
-                                                true,
5461
-                                                false
5462
-                                            );
5463
-                // add this new object to the entity map
5464
-                $classInstance = $this->add_to_entity_map($classInstance);
5465
-            }
5466
-        } else {
5467
-            $classInstance = EE_Registry::instance()->load_class(
5468
-                $className,
5469
-                [$this_model_fields_n_values, $this->_timezone],
5470
-                true,
5471
-                false
5472
-            );
5473
-        }
5474
-        return $classInstance;
5475
-    }
5476
-
5477
-
5478
-    /**
5479
-     * Gets the model object from the  entity map if it exists
5480
-     *
5481
-     * @param int|string $id the ID of the model object
5482
-     * @return EE_Base_Class
5483
-     */
5484
-    public function get_from_entity_map($id)
5485
-    {
5486
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5487
-    }
5488
-
5489
-
5490
-    /**
5491
-     * add_to_entity_map
5492
-     * Adds the object to the model's entity mappings
5493
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5494
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5495
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5496
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5497
-     *        then this method should be called immediately after the update query
5498
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5499
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5500
-     *
5501
-     * @param EE_Base_Class $object
5502
-     * @return EE_Base_Class
5503
-     * @throws EE_Error
5504
-     * @throws ReflectionException
5505
-     */
5506
-    public function add_to_entity_map(EE_Base_Class $object)
5507
-    {
5508
-        $className = $this->_get_class_name();
5509
-        if (! $object instanceof $className) {
5510
-            throw new EE_Error(
5511
-                sprintf(
5512
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5513
-                    is_object($object)
5514
-                        ? get_class($object)
5515
-                        : $object,
5516
-                    $className
5517
-                )
5518
-            );
5519
-        }
5520
-
5521
-        if (! $object->ID()) {
5522
-            throw new EE_Error(
5523
-                sprintf(
5524
-                    esc_html__(
5525
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5526
-                        "event_espresso"
5527
-                    ),
5528
-                    get_class($this)
5529
-                )
5530
-            );
5531
-        }
5532
-        // double check it's not already there
5533
-        $classInstance = $this->get_from_entity_map($object->ID());
5534
-        if ($classInstance) {
5535
-            return $classInstance;
5536
-        }
5537
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5538
-        return $object;
5539
-    }
5540
-
5541
-
5542
-    /**
5543
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5544
-     * if no identifier is provided, then the entire entity map is emptied
5545
-     *
5546
-     * @param int|string $id the ID of the model object
5547
-     * @return boolean
5548
-     */
5549
-    public function clear_entity_map($id = null)
5550
-    {
5551
-        if (empty($id)) {
5552
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5553
-            return true;
5554
-        }
5555
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5556
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5557
-            return true;
5558
-        }
5559
-        return false;
5560
-    }
5561
-
5562
-
5563
-    /**
5564
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5565
-     * Given an array where keys are column (or column alias) names and values,
5566
-     * returns an array of their corresponding field names and database values
5567
-     *
5568
-     * @param array $cols_n_values
5569
-     * @return array
5570
-     * @throws EE_Error
5571
-     * @throws ReflectionException
5572
-     */
5573
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5574
-    {
5575
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5576
-    }
5577
-
5578
-
5579
-    /**
5580
-     * _deduce_fields_n_values_from_cols_n_values
5581
-     * Given an array where keys are column (or column alias) names and values,
5582
-     * returns an array of their corresponding field names and database values
5583
-     *
5584
-     * @param array|stdClass $cols_n_values
5585
-     * @return array
5586
-     * @throws EE_Error
5587
-     * @throws ReflectionException
5588
-     */
5589
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5590
-    {
5591
-        if ($cols_n_values instanceof stdClass) {
5592
-            $cols_n_values = get_object_vars($cols_n_values);
5593
-        }
5594
-        $this_model_fields_n_values = [];
5595
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5596
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5597
-                $cols_n_values,
5598
-                $table_obj->get_fully_qualified_pk_column(),
5599
-                $table_obj->get_pk_column()
5600
-            );
5601
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5602
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5603
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
-                    if (! $field_obj->is_db_only_field()) {
5605
-                        // prepare field as if its coming from db
5606
-                        $prepared_value                            =
5607
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5608
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5609
-                    }
5610
-                }
5611
-            } else {
5612
-                // the table's rows existed. Use their values
5613
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5614
-                    if (! $field_obj->is_db_only_field()) {
5615
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5616
-                            $cols_n_values,
5617
-                            $field_obj->get_qualified_column(),
5618
-                            $field_obj->get_table_column()
5619
-                        );
5620
-                    }
5621
-                }
5622
-            }
5623
-        }
5624
-        return $this_model_fields_n_values;
5625
-    }
5626
-
5627
-
5628
-    /**
5629
-     * @param $cols_n_values
5630
-     * @param $qualified_column
5631
-     * @param $regular_column
5632
-     * @return null
5633
-     * @throws EE_Error
5634
-     * @throws ReflectionException
5635
-     */
5636
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5637
-    {
5638
-        $value = null;
5639
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5640
-        // does the field on the model relate to this column retrieved from the db?
5641
-        // or is it a db-only field? (not relating to the model)
5642
-        if (isset($cols_n_values[ $qualified_column ])) {
5643
-            $value = $cols_n_values[ $qualified_column ];
5644
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5645
-            $value = $cols_n_values[ $regular_column ];
5646
-        } elseif (! empty($this->foreign_key_aliases)) {
5647
-            // no PK?  ok check if there is a foreign key alias set for this table
5648
-            // then check if that alias exists in the incoming data
5649
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5650
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5651
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5652
-                    $value = $cols_n_values[ $FK_alias ];
5653
-                    [$pk_class] = explode('.', $PK_column);
5654
-                    $pk_model_name = "EEM_{$pk_class}";
5655
-                    /** @var EEM_Base $pk_model */
5656
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5657
-                    if ($pk_model instanceof EEM_Base) {
5658
-                        // make sure object is pulled from db and added to entity map
5659
-                        $pk_model->get_one_by_ID($value);
5660
-                    }
5661
-                    break;
5662
-                }
5663
-            }
5664
-        }
5665
-        return $value;
5666
-    }
5667
-
5668
-
5669
-    /**
5670
-     * refresh_entity_map_from_db
5671
-     * Makes sure the model object in the entity map at $id assumes the values
5672
-     * of the database (opposite of EE_base_Class::save())
5673
-     *
5674
-     * @param int|string $id
5675
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5676
-     * @throws EE_Error
5677
-     * @throws ReflectionException
5678
-     */
5679
-    public function refresh_entity_map_from_db($id)
5680
-    {
5681
-        $obj_in_map = $this->get_from_entity_map($id);
5682
-        if ($obj_in_map) {
5683
-            $wpdb_results = $this->_get_all_wpdb_results(
5684
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5685
-            );
5686
-            if ($wpdb_results && is_array($wpdb_results)) {
5687
-                $one_row = reset($wpdb_results);
5688
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5689
-                    $obj_in_map->set_from_db($field_name, $db_value);
5690
-                }
5691
-                // clear the cache of related model objects
5692
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5693
-                    $obj_in_map->clear_cache($relation_name, null, true);
5694
-                }
5695
-            }
5696
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5697
-            return $obj_in_map;
5698
-        }
5699
-        return $this->get_one_by_ID($id);
5700
-    }
5701
-
5702
-
5703
-    /**
5704
-     * refresh_entity_map_with
5705
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5706
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5707
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5708
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5709
-     *
5710
-     * @param int|string    $id
5711
-     * @param EE_Base_Class $replacing_model_obj
5712
-     * @return EE_Base_Class
5713
-     * @throws EE_Error
5714
-     * @throws ReflectionException
5715
-     */
5716
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5717
-    {
5718
-        $obj_in_map = $this->get_from_entity_map($id);
5719
-        if ($obj_in_map) {
5720
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5721
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5722
-                    $obj_in_map->set($field_name, $value);
5723
-                }
5724
-                // make the model object in the entity map's cache match the $replacing_model_obj
5725
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5726
-                    $obj_in_map->clear_cache($relation_name, null, true);
5727
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5728
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5729
-                    }
5730
-                }
5731
-            }
5732
-            return $obj_in_map;
5733
-        }
5734
-        $this->add_to_entity_map($replacing_model_obj);
5735
-        return $replacing_model_obj;
5736
-    }
5737
-
5738
-
5739
-    /**
5740
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5741
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5742
-     * require_once($this->_getClassName().".class.php");
5743
-     *
5744
-     * @return string
5745
-     */
5746
-    private function _get_class_name()
5747
-    {
5748
-        return "EE_" . $this->get_this_model_name();
5749
-    }
5750
-
5751
-
5752
-    /**
5753
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5754
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5755
-     * it would be 'Events'.
5756
-     *
5757
-     * @param int|float|null $quantity
5758
-     * @return string
5759
-     */
5760
-    public function item_name($quantity = 1): string
5761
-    {
5762
-        $quantity = floor($quantity);
5763
-        return apply_filters(
5764
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5765
-            $quantity > 1
5766
-                ? $this->plural_item
5767
-                : $this->singular_item,
5768
-            $quantity,
5769
-            $this->plural_item,
5770
-            $this->singular_item
5771
-        );
5772
-    }
5773
-
5774
-
5775
-    /**
5776
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5777
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5778
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5779
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5780
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5781
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5782
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5783
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5784
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5785
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5786
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5787
-     *        return $previousReturnValue.$returnString;
5788
-     * }
5789
-     * require('EEM_Answer.model.php');
5790
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5791
-     * // will output "you called my_callback! and passed args:monkeys,100"
5792
-     *
5793
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5794
-     * @param array  $args       array of original arguments passed to the function
5795
-     * @return mixed whatever the plugin which calls add_filter decides
5796
-     * @throws EE_Error
5797
-     */
5798
-    public function __call($methodName, $args)
5799
-    {
5800
-        $className = get_class($this);
5801
-        $tagName   = "FHEE__{$className}__{$methodName}";
5802
-        if (! has_filter($tagName)) {
5803
-            throw new EE_Error(
5804
-                sprintf(
5805
-                    esc_html__(
5806
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5807
-                        'event_espresso'
5808
-                    ),
5809
-                    $methodName,
5810
-                    $className,
5811
-                    $tagName,
5812
-                    '<br />'
5813
-                )
5814
-            );
5815
-        }
5816
-        return apply_filters($tagName, null, $this, $args);
5817
-    }
5818
-
5819
-
5820
-    /**
5821
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5822
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5823
-     *
5824
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5825
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5826
-     *                                                       the object's class name
5827
-     *                                                       or object's ID
5828
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5829
-     *                                                       exists in the database. If it does not, we add it
5830
-     * @return EE_Base_Class
5831
-     * @throws EE_Error
5832
-     * @throws ReflectionException
5833
-     */
5834
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5835
-    {
5836
-        $className = $this->_get_class_name();
5837
-        if ($base_class_obj_or_id instanceof $className) {
5838
-            $model_object = $base_class_obj_or_id;
5839
-        } else {
5840
-            $primary_key_field = $this->get_primary_key_field();
5841
-            if (
5842
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5843
-                && (
5844
-                    is_int($base_class_obj_or_id)
5845
-                    || is_string($base_class_obj_or_id)
5846
-                )
5847
-            ) {
5848
-                // assume it's an ID.
5849
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5850
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5851
-            } elseif (
5852
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5853
-                && is_string($base_class_obj_or_id)
5854
-            ) {
5855
-                // assume it's a string representation of the object
5856
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5857
-            } else {
5858
-                throw new EE_Error(
5859
-                    sprintf(
5860
-                        esc_html__(
5861
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5862
-                            'event_espresso'
5863
-                        ),
5864
-                        $base_class_obj_or_id,
5865
-                        $this->_get_class_name(),
5866
-                        print_r($base_class_obj_or_id, true)
5867
-                    )
5868
-                );
5869
-            }
5870
-        }
5871
-        if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5872
-            $model_object->save();
5873
-        }
5874
-        return $model_object;
5875
-    }
5876
-
5877
-
5878
-    /**
5879
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5880
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5881
-     * returns it ID.
5882
-     *
5883
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5884
-     * @return int|string depending on the type of this model object's ID
5885
-     * @throws EE_Error
5886
-     * @throws ReflectionException
5887
-     */
5888
-    public function ensure_is_ID($base_class_obj_or_id)
5889
-    {
5890
-        $className = $this->_get_class_name();
5891
-        if ($base_class_obj_or_id instanceof $className) {
5892
-            /** @var $base_class_obj_or_id EE_Base_Class */
5893
-            $id = $base_class_obj_or_id->ID();
5894
-        } elseif (is_int($base_class_obj_or_id)) {
5895
-            // assume it's an ID
5896
-            $id = $base_class_obj_or_id;
5897
-        } elseif (is_string($base_class_obj_or_id)) {
5898
-            // assume its a string representation of the object
5899
-            $id = $base_class_obj_or_id;
5900
-        } else {
5901
-            throw new EE_Error(
5902
-                sprintf(
5903
-                    esc_html__(
5904
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5905
-                        'event_espresso'
5906
-                    ),
5907
-                    $base_class_obj_or_id,
5908
-                    $this->_get_class_name(),
5909
-                    print_r($base_class_obj_or_id, true)
5910
-                )
5911
-            );
5912
-        }
5913
-        return $id;
5914
-    }
5915
-
5916
-
5917
-    /**
5918
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5919
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5920
-     * been sanitized and converted into the appropriate domain.
5921
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5922
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5923
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5924
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5925
-     * $EVT = EEM_Event::instance(); $old_setting =
5926
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5927
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5928
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5929
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5930
-     *
5931
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5932
-     * @return void
5933
-     */
5934
-    public function assume_values_already_prepared_by_model_object(
5935
-        $values_already_prepared = self::not_prepared_by_model_object
5936
-    ) {
5937
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5938
-    }
5939
-
5940
-
5941
-    /**
5942
-     * Read comments for assume_values_already_prepared_by_model_object()
5943
-     *
5944
-     * @return int
5945
-     */
5946
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5947
-    {
5948
-        return $this->_values_already_prepared_by_model_object;
5949
-    }
5950
-
5951
-
5952
-    /**
5953
-     * Gets all the indexes on this model
5954
-     *
5955
-     * @return EE_Index[]
5956
-     */
5957
-    public function indexes()
5958
-    {
5959
-        return $this->_indexes;
5960
-    }
5961
-
5962
-
5963
-    /**
5964
-     * Gets all the Unique Indexes on this model
5965
-     *
5966
-     * @return EE_Unique_Index[]
5967
-     */
5968
-    public function unique_indexes()
5969
-    {
5970
-        $unique_indexes = [];
5971
-        foreach ($this->_indexes as $name => $index) {
5972
-            if ($index instanceof EE_Unique_Index) {
5973
-                $unique_indexes [ $name ] = $index;
5974
-            }
5975
-        }
5976
-        return $unique_indexes;
5977
-    }
5978
-
5979
-
5980
-    /**
5981
-     * Gets all the fields which, when combined, make the primary key.
5982
-     * This is usually just an array with 1 element (the primary key), but in cases
5983
-     * where there is no primary key, it's a combination of fields as defined
5984
-     * on a primary index
5985
-     *
5986
-     * @return EE_Model_Field_Base[] indexed by the field's name
5987
-     * @throws EE_Error
5988
-     */
5989
-    public function get_combined_primary_key_fields()
5990
-    {
5991
-        foreach ($this->indexes() as $index) {
5992
-            if ($index instanceof EE_Primary_Key_Index) {
5993
-                return $index->fields();
5994
-            }
5995
-        }
5996
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5997
-    }
5998
-
5999
-
6000
-    /**
6001
-     * Used to build a primary key string (when the model has no primary key),
6002
-     * which can be used a unique string to identify this model object.
6003
-     *
6004
-     * @param array $fields_n_values keys are field names, values are their values.
6005
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
6006
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
6007
-     *                               before passing it to this function (that will convert it from columns-n-values
6008
-     *                               to field-names-n-values).
6009
-     * @return string
6010
-     * @throws EE_Error
6011
-     */
6012
-    public function get_index_primary_key_string($fields_n_values)
6013
-    {
6014
-        $cols_n_values_for_primary_key_index = array_intersect_key(
6015
-            $fields_n_values,
6016
-            $this->get_combined_primary_key_fields()
6017
-        );
6018
-        return http_build_query($cols_n_values_for_primary_key_index);
6019
-    }
6020
-
6021
-
6022
-    /**
6023
-     * Gets the field values from the primary key string
6024
-     *
6025
-     * @param string $index_primary_key_string
6026
-     * @return null|array
6027
-     * @throws EE_Error
6028
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6029
-     */
6030
-    public function parse_index_primary_key_string($index_primary_key_string)
6031
-    {
6032
-        $key_fields = $this->get_combined_primary_key_fields();
6033
-        // check all of them are in the $id
6034
-        $key_vals_in_combined_pk = [];
6035
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6036
-        foreach ($key_fields as $key_field_name => $field_obj) {
6037
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6038
-                return null;
6039
-            }
6040
-        }
6041
-        return $key_vals_in_combined_pk;
6042
-    }
6043
-
6044
-
6045
-    /**
6046
-     * verifies that an array of key-value pairs for model fields has a key
6047
-     * for each field comprising the primary key index
6048
-     *
6049
-     * @param array $key_vals
6050
-     * @return boolean
6051
-     * @throws EE_Error
6052
-     */
6053
-    public function has_all_combined_primary_key_fields($key_vals)
6054
-    {
6055
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6056
-        foreach ($keys_it_should_have as $key) {
6057
-            if (! isset($key_vals[ $key ])) {
6058
-                return false;
6059
-            }
6060
-        }
6061
-        return true;
6062
-    }
6063
-
6064
-
6065
-    /**
6066
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6067
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
6068
-     *
6069
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6070
-     * @param array               $query_params                     @see
6071
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6072
-     * @throws EE_Error
6073
-     * @throws ReflectionException
6074
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6075
-     *                                                              indexed)
6076
-     */
6077
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6078
-    {
6079
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6080
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
6081
-        } elseif (is_array($model_object_or_attributes_array)) {
6082
-            $attributes_array = $model_object_or_attributes_array;
6083
-        } else {
6084
-            throw new EE_Error(
6085
-                sprintf(
6086
-                    esc_html__(
6087
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6088
-                        "event_espresso"
6089
-                    ),
6090
-                    $model_object_or_attributes_array
6091
-                )
6092
-            );
6093
-        }
6094
-        // even copies obviously won't have the same ID, so remove the primary key
6095
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6096
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6097
-            unset($attributes_array[ $this->primary_key_name() ]);
6098
-        }
6099
-        if (isset($query_params[0])) {
6100
-            $query_params[0] = array_merge($attributes_array, $query_params);
6101
-        } else {
6102
-            $query_params[0] = $attributes_array;
6103
-        }
6104
-        return $this->get_all($query_params);
6105
-    }
6106
-
6107
-
6108
-    /**
6109
-     * Gets the first copy we find. See get_all_copies for more details
6110
-     *
6111
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6112
-     * @param array $query_params
6113
-     * @return EE_Base_Class
6114
-     * @throws EE_Error
6115
-     * @throws ReflectionException
6116
-     */
6117
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6118
-    {
6119
-        if (! is_array($query_params)) {
6120
-            EE_Error::doing_it_wrong(
6121
-                'EEM_Base::get_one_copy',
6122
-                sprintf(
6123
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6124
-                    gettype($query_params)
6125
-                ),
6126
-                '4.6.0'
6127
-            );
6128
-            $query_params = [];
6129
-        }
6130
-        $query_params['limit'] = 1;
6131
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6132
-        if (is_array($copies)) {
6133
-            return array_shift($copies);
6134
-        }
6135
-        return null;
6136
-    }
6137
-
6138
-
6139
-    /**
6140
-     * Updates the item with the specified id. Ignores default query parameters because
6141
-     * we have specified the ID, and its assumed we KNOW what we're doing
6142
-     *
6143
-     * @param array      $fields_n_values keys are field names, values are their new values
6144
-     * @param int|string $id              the value of the primary key to update
6145
-     * @return int number of rows updated
6146
-     * @throws EE_Error
6147
-     * @throws ReflectionException
6148
-     */
6149
-    public function update_by_ID($fields_n_values, $id)
6150
-    {
6151
-        $query_params = [
6152
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6153
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6154
-        ];
6155
-        return $this->update($fields_n_values, $query_params);
6156
-    }
6157
-
6158
-
6159
-    /**
6160
-     * Changes an operator which was supplied to the models into one usable in SQL
6161
-     *
6162
-     * @param string $operator_supplied
6163
-     * @return string an operator which can be used in SQL
6164
-     * @throws EE_Error
6165
-     */
6166
-    private function _prepare_operator_for_sql($operator_supplied)
6167
-    {
6168
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6169
-        if ($sql_operator) {
6170
-            return $sql_operator;
6171
-        }
6172
-        throw new EE_Error(
6173
-            sprintf(
6174
-                esc_html__(
6175
-                    "The operator '%s' is not in the list of valid operators: %s",
6176
-                    "event_espresso"
6177
-                ),
6178
-                $operator_supplied,
6179
-                implode(",", array_keys($this->_valid_operators))
6180
-            )
6181
-        );
6182
-    }
6183
-
6184
-
6185
-    /**
6186
-     * Gets the valid operators
6187
-     *
6188
-     * @return array keys are accepted strings, values are the SQL they are converted to
6189
-     */
6190
-    public function valid_operators()
6191
-    {
6192
-        return $this->_valid_operators;
6193
-    }
6194
-
6195
-
6196
-    /**
6197
-     * Gets the between-style operators (take 2 arguments).
6198
-     *
6199
-     * @return array keys are accepted strings, values are the SQL they are converted to
6200
-     */
6201
-    public function valid_between_style_operators()
6202
-    {
6203
-        return array_intersect(
6204
-            $this->valid_operators(),
6205
-            $this->_between_style_operators
6206
-        );
6207
-    }
6208
-
6209
-
6210
-    /**
6211
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6212
-     *
6213
-     * @return array keys are accepted strings, values are the SQL they are converted to
6214
-     */
6215
-    public function valid_like_style_operators()
6216
-    {
6217
-        return array_intersect(
6218
-            $this->valid_operators(),
6219
-            $this->_like_style_operators
6220
-        );
6221
-    }
6222
-
6223
-
6224
-    /**
6225
-     * Gets the "in"-style operators
6226
-     *
6227
-     * @return array keys are accepted strings, values are the SQL they are converted to
6228
-     */
6229
-    public function valid_in_style_operators()
6230
-    {
6231
-        return array_intersect(
6232
-            $this->valid_operators(),
6233
-            $this->_in_style_operators
6234
-        );
6235
-    }
6236
-
6237
-
6238
-    /**
6239
-     * Gets the "null"-style operators (accept no arguments)
6240
-     *
6241
-     * @return array keys are accepted strings, values are the SQL they are converted to
6242
-     */
6243
-    public function valid_null_style_operators()
6244
-    {
6245
-        return array_intersect(
6246
-            $this->valid_operators(),
6247
-            $this->_null_style_operators
6248
-        );
6249
-    }
6250
-
6251
-
6252
-    /**
6253
-     * Gets an array where keys are the primary keys and values are their 'names'
6254
-     * (as determined by the model object's name() function, which is often overridden)
6255
-     *
6256
-     * @param array $query_params like get_all's
6257
-     * @return string[]
6258
-     * @throws EE_Error
6259
-     * @throws ReflectionException
6260
-     */
6261
-    public function get_all_names($query_params = [])
6262
-    {
6263
-        $objs  = $this->get_all($query_params);
6264
-        $names = [];
6265
-        foreach ($objs as $obj) {
6266
-            $names[ $obj->ID() ] = $obj->name();
6267
-        }
6268
-        return $names;
6269
-    }
6270
-
6271
-
6272
-    /**
6273
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6274
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6275
-     * this is duplicated effort and reduces efficiency) you would be better to use
6276
-     * array_keys() on $model_objects.
6277
-     *
6278
-     * @param \EE_Base_Class[] $model_objects
6279
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6280
-     *                                               in the returned array
6281
-     * @return array
6282
-     * @throws EE_Error
6283
-     * @throws ReflectionException
6284
-     */
6285
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6286
-    {
6287
-        if (! $this->has_primary_key_field()) {
6288
-            if (defined('WP_DEBUG') && WP_DEBUG) {
6289
-                EE_Error::add_error(
6290
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6291
-                    __FILE__,
6292
-                    __FUNCTION__,
6293
-                    __LINE__
6294
-                );
6295
-            }
6296
-        }
6297
-        $IDs = [];
6298
-        foreach ($model_objects as $model_object) {
6299
-            $id = $model_object->ID();
6300
-            if (! $id) {
6301
-                if ($filter_out_empty_ids) {
6302
-                    continue;
6303
-                }
6304
-                if (defined('WP_DEBUG') && WP_DEBUG) {
6305
-                    EE_Error::add_error(
6306
-                        esc_html__(
6307
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6308
-                            'event_espresso'
6309
-                        ),
6310
-                        __FILE__,
6311
-                        __FUNCTION__,
6312
-                        __LINE__
6313
-                    );
6314
-                }
6315
-            }
6316
-            $IDs[] = $id;
6317
-        }
6318
-        return $IDs;
6319
-    }
6320
-
6321
-
6322
-    /**
6323
-     * Returns the string used in capabilities relating to this model. If there
6324
-     * are no capabilities that relate to this model returns false
6325
-     *
6326
-     * @return string|false
6327
-     */
6328
-    public function cap_slug()
6329
-    {
6330
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6331
-    }
6332
-
6333
-
6334
-    /**
6335
-     * Returns the capability-restrictions array (@param string $context
6336
-     *
6337
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6338
-     * @throws EE_Error
6339
-     * @see EEM_Base::_cap_restrictions).
6340
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6341
-     *      only returns the cap restrictions array in that context (ie, the array
6342
-     *      at that key)
6343
-     */
6344
-    public function cap_restrictions($context = EEM_Base::caps_read)
6345
-    {
6346
-        EEM_Base::verify_is_valid_cap_context($context);
6347
-        // check if we ought to run the restriction generator first
6348
-        if (
6349
-            isset($this->_cap_restriction_generators[ $context ])
6350
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6351
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6352
-        ) {
6353
-            $this->_cap_restrictions[ $context ] = array_merge(
6354
-                $this->_cap_restrictions[ $context ],
6355
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6356
-            );
6357
-        }
6358
-        // and make sure we've finalized the construction of each restriction
6359
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6360
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6361
-                $where_conditions_obj->_finalize_construct($this);
6362
-            }
6363
-        }
6364
-        return $this->_cap_restrictions[ $context ];
6365
-    }
6366
-
6367
-
6368
-    /**
6369
-     * Indicating whether or not this model thinks its a wp core model
6370
-     *
6371
-     * @return boolean
6372
-     */
6373
-    public function is_wp_core_model()
6374
-    {
6375
-        return $this->_wp_core_model;
6376
-    }
6377
-
6378
-
6379
-    /**
6380
-     * Gets all the caps that are missing which impose a restriction on
6381
-     * queries made in this context
6382
-     *
6383
-     * @param string $context one of EEM_Base::caps_ constants
6384
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6385
-     * @throws EE_Error
6386
-     */
6387
-    public function caps_missing($context = EEM_Base::caps_read)
6388
-    {
6389
-        $missing_caps     = [];
6390
-        $cap_restrictions = $this->cap_restrictions($context);
6391
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6392
-            if (
6393
-                ! EE_Capabilities::instance()
6394
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6395
-            ) {
6396
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6397
-            }
6398
-        }
6399
-        return $missing_caps;
6400
-    }
6401
-
6402
-
6403
-    /**
6404
-     * Gets the mapping from capability contexts to action strings used in capability names
6405
-     *
6406
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6407
-     * one of 'read', 'edit', or 'delete'
6408
-     */
6409
-    public function cap_contexts_to_cap_action_map()
6410
-    {
6411
-        return apply_filters(
6412
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6413
-            $this->_cap_contexts_to_cap_action_map,
6414
-            $this
6415
-        );
6416
-    }
6417
-
6418
-
6419
-    /**
6420
-     * Gets the action string for the specified capability context
6421
-     *
6422
-     * @param string $context
6423
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6424
-     * @throws EE_Error
6425
-     */
6426
-    public function cap_action_for_context($context)
6427
-    {
6428
-        $mapping = $this->cap_contexts_to_cap_action_map();
6429
-        if (isset($mapping[ $context ])) {
6430
-            return $mapping[ $context ];
6431
-        }
6432
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6433
-            return $action;
6434
-        }
6435
-        throw new EE_Error(
6436
-            sprintf(
6437
-                esc_html__(
6438
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6439
-                    'event_espresso'
6440
-                ),
6441
-                $context,
6442
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6443
-            )
6444
-        );
6445
-    }
6446
-
6447
-
6448
-    /**
6449
-     * Returns all the capability contexts which are valid when querying models
6450
-     *
6451
-     * @return array
6452
-     */
6453
-    public static function valid_cap_contexts(): array
6454
-    {
6455
-        return (array) apply_filters(
6456
-            'FHEE__EEM_Base__valid_cap_contexts',
6457
-            [
6458
-                self::caps_read,
6459
-                self::caps_read_admin,
6460
-                self::caps_edit,
6461
-                self::caps_delete,
6462
-            ]
6463
-        );
6464
-    }
6465
-
6466
-
6467
-    /**
6468
-     * Returns all valid options for 'default_where_conditions'
6469
-     *
6470
-     * @return array
6471
-     */
6472
-    public static function valid_default_where_conditions(): array
6473
-    {
6474
-        return [
6475
-            EEM_Base::default_where_conditions_all,
6476
-            EEM_Base::default_where_conditions_this_only,
6477
-            EEM_Base::default_where_conditions_others_only,
6478
-            EEM_Base::default_where_conditions_minimum_all,
6479
-            EEM_Base::default_where_conditions_minimum_others,
6480
-            EEM_Base::default_where_conditions_none,
6481
-        ];
6482
-    }
6483
-
6484
-    // public static function default_where_conditions_full
6485
-
6486
-
6487
-    /**
6488
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6489
-     *
6490
-     * @param string $context
6491
-     * @return bool
6492
-     * @throws EE_Error
6493
-     */
6494
-    public static function verify_is_valid_cap_context($context): bool
6495
-    {
6496
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6497
-        if (in_array($context, $valid_cap_contexts)) {
6498
-            return true;
6499
-        }
6500
-        throw new EE_Error(
6501
-            sprintf(
6502
-                esc_html__(
6503
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6504
-                    'event_espresso'
6505
-                ),
6506
-                $context,
6507
-                'EEM_Base',
6508
-                implode(',', $valid_cap_contexts)
6509
-            )
6510
-        );
6511
-    }
6512
-
6513
-
6514
-    /**
6515
-     * Clears all the models field caches. This is only useful when a sub-class
6516
-     * might have added a field or something and these caches might be invalidated
6517
-     */
6518
-    protected function _invalidate_field_caches()
6519
-    {
6520
-        $this->_cache_foreign_key_to_fields = [];
6521
-        $this->_cached_fields               = null;
6522
-        $this->_cached_fields_non_db_only   = null;
6523
-    }
6524
-
6525
-
6526
-    /**
6527
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6528
-     * (eg "and", "or", "not").
6529
-     *
6530
-     * @return array
6531
-     */
6532
-    public function logic_query_param_keys(): array
6533
-    {
6534
-        return $this->_logic_query_param_keys;
6535
-    }
6536
-
6537
-
6538
-    /**
6539
-     * Determines whether or not the where query param array key is for a logic query param.
6540
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6541
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6542
-     *
6543
-     * @param $query_param_key
6544
-     * @return bool
6545
-     */
6546
-    public function is_logic_query_param_key($query_param_key): bool
6547
-    {
6548
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6549
-            if (
6550
-                $query_param_key === $logic_query_param_key
6551
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6552
-            ) {
6553
-                return true;
6554
-            }
6555
-        }
6556
-        return false;
6557
-    }
6558
-
6559
-
6560
-    /**
6561
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6562
-     *
6563
-     * @return boolean
6564
-     * @since 4.9.74.p
6565
-     */
6566
-    public function hasPassword(): bool
6567
-    {
6568
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6569
-        if ($this->has_password_field === null) {
6570
-            $password_field           = $this->getPasswordField();
6571
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6572
-        }
6573
-        return $this->has_password_field;
6574
-    }
6575
-
6576
-
6577
-    /**
6578
-     * Returns the password field on this model, if there is one
6579
-     *
6580
-     * @return EE_Password_Field|null
6581
-     * @since 4.9.74.p
6582
-     */
6583
-    public function getPasswordField()
6584
-    {
6585
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6586
-        // there's no need to search for it. If we don't know yet, then find out
6587
-        if ($this->has_password_field === null && $this->password_field === null) {
6588
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6589
-        }
6590
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6591
-        return $this->password_field;
6592
-    }
6593
-
6594
-
6595
-    /**
6596
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6597
-     *
6598
-     * @return EE_Model_Field_Base[]
6599
-     * @throws EE_Error
6600
-     * @since 4.9.74.p
6601
-     */
6602
-    public function getPasswordProtectedFields()
6603
-    {
6604
-        $password_field = $this->getPasswordField();
6605
-        $fields         = [];
6606
-        if ($password_field instanceof EE_Password_Field) {
6607
-            $field_names = $password_field->protectedFields();
6608
-            foreach ($field_names as $field_name) {
6609
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6610
-            }
6611
-        }
6612
-        return $fields;
6613
-    }
6614
-
6615
-
6616
-    /**
6617
-     * Checks if the current user can perform the requested action on this model
6618
-     *
6619
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6620
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6621
-     * @return bool
6622
-     * @throws EE_Error
6623
-     * @throws InvalidArgumentException
6624
-     * @throws InvalidDataTypeException
6625
-     * @throws InvalidInterfaceException
6626
-     * @throws ReflectionException
6627
-     * @throws UnexpectedEntityException
6628
-     * @since 4.9.74.p
6629
-     */
6630
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6631
-    {
6632
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6633
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6634
-        }
6635
-        if (! is_array($model_obj_or_fields_n_values)) {
6636
-            throw new UnexpectedEntityException(
6637
-                $model_obj_or_fields_n_values,
6638
-                'EE_Base_Class',
6639
-                sprintf(
6640
-                    esc_html__(
6641
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6642
-                        'event_espresso'
6643
-                    ),
6644
-                    __FUNCTION__
6645
-                )
6646
-            );
6647
-        }
6648
-        return $this->exists(
6649
-            $this->alter_query_params_to_restrict_by_ID(
6650
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6651
-                [
6652
-                    'default_where_conditions' => 'none',
6653
-                    'caps'                     => $cap_to_check,
6654
-                ]
6655
-            )
6656
-        );
6657
-    }
6658
-
6659
-
6660
-    /**
6661
-     * Returns the query param where conditions key to the password affecting this model.
6662
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6663
-     *
6664
-     * @return null|string
6665
-     * @throws EE_Error
6666
-     * @throws InvalidArgumentException
6667
-     * @throws InvalidDataTypeException
6668
-     * @throws InvalidInterfaceException
6669
-     * @throws ModelConfigurationException
6670
-     * @throws ReflectionException
6671
-     * @since 4.9.74.p
6672
-     */
6673
-    public function modelChainAndPassword()
6674
-    {
6675
-        if ($this->model_chain_to_password === null) {
6676
-            throw new ModelConfigurationException(
6677
-                $this,
6678
-                esc_html_x(
6679
-                // @codingStandardsIgnoreStart
6680
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6681
-                    // @codingStandardsIgnoreEnd
6682
-                    '1: model name',
6683
-                    'event_espresso'
6684
-                )
6685
-            );
6686
-        }
6687
-        if ($this->model_chain_to_password === '') {
6688
-            $model_with_password = $this;
6689
-        } else {
6690
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6691
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6692
-            } else {
6693
-                $last_model_in_chain = $this->model_chain_to_password;
6694
-            }
6695
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6696
-        }
6697
-
6698
-        $password_field = $model_with_password->getPasswordField();
6699
-        if ($password_field instanceof EE_Password_Field) {
6700
-            $password_field_name = $password_field->get_name();
6701
-        } else {
6702
-            throw new ModelConfigurationException(
6703
-                $this,
6704
-                sprintf(
6705
-                    esc_html_x(
6706
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6707
-                        '1: model name, 2: special string',
6708
-                        'event_espresso'
6709
-                    ),
6710
-                    $model_with_password->get_this_model_name(),
6711
-                    $this->model_chain_to_password
6712
-                )
6713
-            );
6714
-        }
6715
-        return (
6716
-               $this->model_chain_to_password
6717
-                   ? $this->model_chain_to_password . '.'
6718
-                   : ''
6719
-               ) . $password_field_name;
6720
-    }
6721
-
6722
-
6723
-    /**
6724
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6725
-     * or if this model itself has a password affecting access to some of its other fields.
6726
-     *
6727
-     * @return boolean
6728
-     * @since 4.9.74.p
6729
-     */
6730
-    public function restrictedByRelatedModelPassword(): bool
6731
-    {
6732
-        return $this->model_chain_to_password !== null;
6733
-    }
3970
+		}
3971
+		return $null_friendly_where_conditions;
3972
+	}
3973
+
3974
+
3975
+	/**
3976
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3977
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3978
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3979
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3980
+	 *
3981
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3982
+	 * @return array @see
3983
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3984
+	 * @throws EE_Error
3985
+	 * @throws EE_Error
3986
+	 */
3987
+	private function _get_default_where_conditions($model_relation_path = '')
3988
+	{
3989
+		if ($this->_ignore_where_strategy) {
3990
+			return [];
3991
+		}
3992
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3993
+	}
3994
+
3995
+
3996
+	/**
3997
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3998
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3999
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
4000
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
4001
+	 * Similar to _get_default_where_conditions
4002
+	 *
4003
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
4004
+	 * @return array @see
4005
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4006
+	 * @throws EE_Error
4007
+	 * @throws EE_Error
4008
+	 */
4009
+	protected function _get_minimum_where_conditions($model_relation_path = '')
4010
+	{
4011
+		if ($this->_ignore_where_strategy) {
4012
+			return [];
4013
+		}
4014
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
4015
+	}
4016
+
4017
+
4018
+	/**
4019
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4020
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4021
+	 *
4022
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
4023
+	 * @return string
4024
+	 * @throws EE_Error
4025
+	 */
4026
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4027
+	{
4028
+		$selects = $this->_get_columns_to_select_for_this_model();
4029
+		foreach (
4030
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4031
+		) {
4032
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4033
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4034
+			foreach ($other_model_selects as $key => $value) {
4035
+				$selects[] = $value;
4036
+			}
4037
+		}
4038
+		return implode(", ", $selects);
4039
+	}
4040
+
4041
+
4042
+	/**
4043
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4044
+	 * So that's going to be the columns for all the fields on the model
4045
+	 *
4046
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
4047
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4048
+	 */
4049
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4050
+	{
4051
+		$fields                                       = $this->field_settings();
4052
+		$selects                                      = [];
4053
+		$table_alias_with_model_relation_chain_prefix =
4054
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4055
+				$model_relation_chain,
4056
+				$this->get_this_model_name()
4057
+			);
4058
+		foreach ($fields as $field_obj) {
4059
+			$selects[] = $table_alias_with_model_relation_chain_prefix
4060
+						 . $field_obj->get_table_alias()
4061
+						 . "."
4062
+						 . $field_obj->get_table_column()
4063
+						 . " AS '"
4064
+						 . $table_alias_with_model_relation_chain_prefix
4065
+						 . $field_obj->get_table_alias()
4066
+						 . "."
4067
+						 . $field_obj->get_table_column()
4068
+						 . "'";
4069
+		}
4070
+		// make sure we are also getting the PKs of each table
4071
+		$tables = $this->get_tables();
4072
+		if (count($tables) > 1) {
4073
+			foreach ($tables as $table_obj) {
4074
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4075
+									   . $table_obj->get_fully_qualified_pk_column();
4076
+				if (! in_array($qualified_pk_column, $selects)) {
4077
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4078
+				}
4079
+			}
4080
+		}
4081
+		return $selects;
4082
+	}
4083
+
4084
+
4085
+	/**
4086
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4087
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4088
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4089
+	 * SQL for joining, and the data types
4090
+	 *
4091
+	 * @param null|string                 $original_query_param
4092
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4093
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4095
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4096
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4097
+	 *                                                          or 'Registration's
4098
+	 * @param string                      $original_query_param what it originally was (eg
4099
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4100
+	 *                                                          matches $query_param
4101
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4102
+	 * @throws EE_Error
4103
+	 */
4104
+	private function _extract_related_model_info_from_query_param(
4105
+		$query_param,
4106
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4107
+		$query_param_type,
4108
+		$original_query_param = null
4109
+	) {
4110
+		if ($original_query_param === null) {
4111
+			$original_query_param = $query_param;
4112
+		}
4113
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4114
+		// check to see if we have a field on this model
4115
+		$this_model_fields = $this->field_settings(true);
4116
+		if (array_key_exists($query_param, $this_model_fields)) {
4117
+			$field_is_allowed = in_array(
4118
+				$query_param_type,
4119
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4120
+				true
4121
+			);
4122
+			if ($field_is_allowed) {
4123
+				return;
4124
+			}
4125
+			throw new EE_Error(
4126
+				sprintf(
4127
+					esc_html__(
4128
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4129
+						"event_espresso"
4130
+					),
4131
+					$query_param,
4132
+					get_class($this),
4133
+					$query_param_type,
4134
+					$original_query_param
4135
+				)
4136
+			);
4137
+		}
4138
+		// check if this is a special logic query param
4139
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4140
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4141
+			if ($operator_is_allowed) {
4142
+				return;
4143
+			}
4144
+			throw new EE_Error(
4145
+				sprintf(
4146
+					esc_html__(
4147
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4148
+						'event_espresso'
4149
+					),
4150
+					implode('", "', $this->_logic_query_param_keys),
4151
+					$query_param,
4152
+					get_class($this),
4153
+					'<br />',
4154
+					"\t"
4155
+					. ' $passed_in_query_info = <pre>'
4156
+					. print_r($passed_in_query_info, true)
4157
+					. '</pre>'
4158
+					. "\n\t"
4159
+					. ' $query_param_type = '
4160
+					. $query_param_type
4161
+					. "\n\t"
4162
+					. ' $original_query_param = '
4163
+					. $original_query_param
4164
+				)
4165
+			);
4166
+		}
4167
+		// check if it's a custom selection
4168
+		if (
4169
+			$this->_custom_selections instanceof CustomSelects
4170
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4171
+		) {
4172
+			return;
4173
+		}
4174
+		// check if has a model name at the beginning
4175
+		// and
4176
+		// check if it's a field on a related model
4177
+		if (
4178
+			$this->extractJoinModelFromQueryParams(
4179
+				$passed_in_query_info,
4180
+				$query_param,
4181
+				$original_query_param,
4182
+				$query_param_type
4183
+			)
4184
+		) {
4185
+			return;
4186
+		}
4187
+
4188
+		// ok so $query_param didn't start with a model name
4189
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4190
+		// it's wack, that's what it is
4191
+		throw new EE_Error(
4192
+			sprintf(
4193
+				esc_html__(
4194
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4195
+					"event_espresso"
4196
+				),
4197
+				$query_param,
4198
+				get_class($this),
4199
+				$query_param_type,
4200
+				$original_query_param
4201
+			)
4202
+		);
4203
+	}
4204
+
4205
+
4206
+	/**
4207
+	 * Extracts any possible join model information from the provided possible_join_string.
4208
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4209
+	 * join
4210
+	 * parts that should be added to the query.
4211
+	 *
4212
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4213
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4214
+	 * @param null|string                 $original_query_param
4215
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4216
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4217
+	 *                                                           etc.)
4218
+	 * @return bool  returns true if a join was added and false if not.
4219
+	 * @throws EE_Error
4220
+	 */
4221
+	private function extractJoinModelFromQueryParams(
4222
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4223
+		$possible_join_string,
4224
+		$original_query_param,
4225
+		$query_parameter_type
4226
+	) {
4227
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4228
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4229
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4230
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4231
+				if ($possible_join_string === '') {
4232
+					// nothing left to $query_param
4233
+					// we should actually end in a field name, not a model like this!
4234
+					throw new EE_Error(
4235
+						sprintf(
4236
+							esc_html__(
4237
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4238
+								"event_espresso"
4239
+							),
4240
+							$possible_join_string,
4241
+							$query_parameter_type,
4242
+							get_class($this),
4243
+							$valid_related_model_name
4244
+						)
4245
+					);
4246
+				}
4247
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4248
+				$related_model_obj->_extract_related_model_info_from_query_param(
4249
+					$possible_join_string,
4250
+					$query_info_carrier,
4251
+					$query_parameter_type,
4252
+					$original_query_param
4253
+				);
4254
+				return true;
4255
+			}
4256
+			if ($possible_join_string === $valid_related_model_name) {
4257
+				$this->_add_join_to_model(
4258
+					$valid_related_model_name,
4259
+					$query_info_carrier,
4260
+					$original_query_param
4261
+				);
4262
+				return true;
4263
+			}
4264
+		}
4265
+		return false;
4266
+	}
4267
+
4268
+
4269
+	/**
4270
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4271
+	 *
4272
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4273
+	 * @throws EE_Error
4274
+	 */
4275
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4276
+	{
4277
+		if (
4278
+			$this->_custom_selections instanceof CustomSelects
4279
+			&& (
4280
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4281
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4282
+			)
4283
+		) {
4284
+			$original_selects = $this->_custom_selections->originalSelects();
4285
+			foreach ($original_selects as $alias => $select_configuration) {
4286
+				$this->extractJoinModelFromQueryParams(
4287
+					$query_info_carrier,
4288
+					$select_configuration[0],
4289
+					$select_configuration[0],
4290
+					'custom_selects'
4291
+				);
4292
+			}
4293
+		}
4294
+	}
4295
+
4296
+
4297
+	/**
4298
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4299
+	 * and store it on $passed_in_query_info
4300
+	 *
4301
+	 * @param string                      $model_name
4302
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4303
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4304
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4305
+	 *                                                          and are adding a join to 'Payment' with the original
4306
+	 *                                                          query param key
4307
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4308
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4309
+	 *                                                          Payment wants to add default query params so that it
4310
+	 *                                                          will know what models to prepend onto its default query
4311
+	 *                                                          params or in case it wants to rename tables (in case
4312
+	 *                                                          there are multiple joins to the same table)
4313
+	 * @return void
4314
+	 * @throws EE_Error
4315
+	 */
4316
+	private function _add_join_to_model(
4317
+		$model_name,
4318
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4319
+		$original_query_param
4320
+	) {
4321
+		$relation_obj         = $this->related_settings_for($model_name);
4322
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4323
+		// check if the relation is HABTM, because then we're essentially doing two joins
4324
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4325
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4326
+			$join_model_obj = $relation_obj->get_join_model();
4327
+			// replace the model specified with the join model for this relation chain, whi
4328
+			$relation_chain_to_join_model =
4329
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4330
+					$model_name,
4331
+					$join_model_obj->get_this_model_name(),
4332
+					$model_relation_chain
4333
+				);
4334
+			$passed_in_query_info->merge(
4335
+				new EE_Model_Query_Info_Carrier(
4336
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4337
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4338
+				)
4339
+			);
4340
+		}
4341
+		// now just join to the other table pointed to by the relation object, and add its data types
4342
+		$passed_in_query_info->merge(
4343
+			new EE_Model_Query_Info_Carrier(
4344
+				[$model_relation_chain => $model_name],
4345
+				$relation_obj->get_join_statement($model_relation_chain)
4346
+			)
4347
+		);
4348
+	}
4349
+
4350
+
4351
+	/**
4352
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4353
+	 *
4354
+	 * @param array $where_params @see
4355
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4356
+	 * @return string of SQL
4357
+	 * @throws EE_Error
4358
+	 */
4359
+	private function _construct_where_clause($where_params)
4360
+	{
4361
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4362
+		if ($SQL) {
4363
+			return " WHERE " . $SQL;
4364
+		}
4365
+		return '';
4366
+	}
4367
+
4368
+
4369
+	/**
4370
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4371
+	 * and should be passed HAVING parameters, not WHERE parameters
4372
+	 *
4373
+	 * @param array $having_params
4374
+	 * @return string
4375
+	 * @throws EE_Error
4376
+	 */
4377
+	private function _construct_having_clause($having_params)
4378
+	{
4379
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4380
+		if ($SQL) {
4381
+			return " HAVING " . $SQL;
4382
+		}
4383
+		return '';
4384
+	}
4385
+
4386
+
4387
+	/**
4388
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4389
+	 * Event_Meta.meta_value = 'foo'))"
4390
+	 *
4391
+	 * @param array  $where_params @see
4392
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4393
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4394
+	 * @return string of SQL
4395
+	 * @throws EE_Error
4396
+	 */
4397
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4398
+	{
4399
+		$where_clauses = [];
4400
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4401
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4402
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4403
+				switch ($query_param) {
4404
+					case 'not':
4405
+					case 'NOT':
4406
+						$where_clauses[] = "! ("
4407
+										   . $this->_construct_condition_clause_recursive(
4408
+											   $op_and_value_or_sub_condition,
4409
+											   $glue
4410
+										   )
4411
+										   . ")";
4412
+						break;
4413
+					case 'and':
4414
+					case 'AND':
4415
+						$where_clauses[] = " ("
4416
+										   . $this->_construct_condition_clause_recursive(
4417
+											   $op_and_value_or_sub_condition,
4418
+											   ' AND '
4419
+										   )
4420
+										   . ")";
4421
+						break;
4422
+					case 'or':
4423
+					case 'OR':
4424
+						$where_clauses[] = " ("
4425
+										   . $this->_construct_condition_clause_recursive(
4426
+											   $op_and_value_or_sub_condition,
4427
+											   ' OR '
4428
+										   )
4429
+										   . ")";
4430
+						break;
4431
+				}
4432
+			} else {
4433
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4434
+				// if it's not a normal field, maybe it's a custom selection?
4435
+				if (! $field_obj) {
4436
+					if ($this->_custom_selections instanceof CustomSelects) {
4437
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4438
+					} else {
4439
+						throw new EE_Error(
4440
+							sprintf(
4441
+								esc_html__(
4442
+									"%s is neither a valid model field name, nor a custom selection",
4443
+									"event_espresso"
4444
+								),
4445
+								$query_param
4446
+							)
4447
+						);
4448
+					}
4449
+				}
4450
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4451
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4452
+			}
4453
+		}
4454
+		return $where_clauses
4455
+			? implode($glue, $where_clauses)
4456
+			: '';
4457
+	}
4458
+
4459
+
4460
+	/**
4461
+	 * Takes the input parameter and extract the table name (alias) and column name
4462
+	 *
4463
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4464
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4465
+	 * @throws EE_Error
4466
+	 */
4467
+	private function _deduce_column_name_from_query_param($query_param)
4468
+	{
4469
+		$field = $this->_deduce_field_from_query_param($query_param);
4470
+		if ($field) {
4471
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4472
+				$field->get_model_name(),
4473
+				$query_param
4474
+			);
4475
+			return $table_alias_prefix . $field->get_qualified_column();
4476
+		}
4477
+		if (
4478
+			$this->_custom_selections instanceof CustomSelects
4479
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4480
+		) {
4481
+			// maybe it's custom selection item?
4482
+			// if so, just use it as the "column name"
4483
+			return $query_param;
4484
+		}
4485
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4486
+			? implode(',', $this->_custom_selections->columnAliases())
4487
+			: '';
4488
+		throw new EE_Error(
4489
+			sprintf(
4490
+				esc_html__(
4491
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4492
+					"event_espresso"
4493
+				),
4494
+				$query_param,
4495
+				$custom_select_aliases
4496
+			)
4497
+		);
4498
+	}
4499
+
4500
+
4501
+	/**
4502
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4503
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4504
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4505
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4506
+	 *
4507
+	 * @param string $condition_query_param_key
4508
+	 * @return string
4509
+	 */
4510
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4511
+	{
4512
+		$pos_of_star = strpos($condition_query_param_key, '*');
4513
+		if ($pos_of_star === false) {
4514
+			return $condition_query_param_key;
4515
+		}
4516
+		return substr($condition_query_param_key, 0, $pos_of_star);
4517
+	}
4518
+
4519
+
4520
+	/**
4521
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4522
+	 *
4523
+	 * @param array|string               $op_and_value
4524
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4525
+	 * @return string
4526
+	 * @throws EE_Error
4527
+	 */
4528
+	private function _construct_op_and_value($op_and_value, $field_obj)
4529
+	{
4530
+		$operator = '=';
4531
+		$value    = $op_and_value;
4532
+		if (is_array($op_and_value)) {
4533
+			$operator = isset($op_and_value[0])
4534
+				? $this->_prepare_operator_for_sql($op_and_value[0])
4535
+				: null;
4536
+			if (! $operator) {
4537
+				$php_array_like_string = [];
4538
+				foreach ($op_and_value as $key => $value) {
4539
+					$value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4540
+					$php_array_like_string[] = "$key=>$value";
4541
+				}
4542
+				throw new EE_Error(
4543
+					sprintf(
4544
+						esc_html__(
4545
+							"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))",
4546
+							"event_espresso"
4547
+						),
4548
+						implode(",", $php_array_like_string)
4549
+					)
4550
+				);
4551
+			}
4552
+			$value = $op_and_value[1] ?? null;
4553
+		}
4554
+
4555
+		// check to see if the value is actually another field
4556
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4557
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4558
+		}
4559
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4560
+			// in this case, the value should be an array, or at least a comma-separated list
4561
+			// it will need to handle a little differently
4562
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4563
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4564
+			return $operator . SP . $cleaned_value;
4565
+		}
4566
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4567
+			// the value should be an array with count of two.
4568
+			if (count($value) !== 2) {
4569
+				throw new EE_Error(
4570
+					sprintf(
4571
+						esc_html__(
4572
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4573
+							'event_espresso'
4574
+						),
4575
+						"BETWEEN"
4576
+					)
4577
+				);
4578
+			}
4579
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4580
+			return $operator . SP . $cleaned_value;
4581
+		}
4582
+		if (in_array($operator, $this->valid_null_style_operators())) {
4583
+			if ($value !== null) {
4584
+				throw new EE_Error(
4585
+					sprintf(
4586
+						esc_html__(
4587
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4588
+							"event_espresso"
4589
+						),
4590
+						$value,
4591
+						$operator
4592
+					)
4593
+				);
4594
+			}
4595
+			return $operator;
4596
+		}
4597
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4598
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4599
+			// remove other junk. So just treat it as a string.
4600
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4601
+		}
4602
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4603
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4604
+		}
4605
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4606
+			throw new EE_Error(
4607
+				sprintf(
4608
+					esc_html__(
4609
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4610
+						'event_espresso'
4611
+					),
4612
+					$operator,
4613
+					$operator
4614
+				)
4615
+			);
4616
+		}
4617
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4618
+			throw new EE_Error(
4619
+				sprintf(
4620
+					esc_html__(
4621
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4622
+						'event_espresso'
4623
+					),
4624
+					$operator,
4625
+					$operator
4626
+				)
4627
+			);
4628
+		}
4629
+		throw new EE_Error(
4630
+			sprintf(
4631
+				esc_html__(
4632
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4633
+					"event_espresso"
4634
+				),
4635
+				http_build_query($op_and_value)
4636
+			)
4637
+		);
4638
+	}
4639
+
4640
+
4641
+	/**
4642
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4643
+	 *
4644
+	 * @param array                      $values
4645
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4646
+	 *                                              '%s'
4647
+	 * @return string
4648
+	 * @throws EE_Error
4649
+	 */
4650
+	public function _construct_between_value($values, $field_obj)
4651
+	{
4652
+		$cleaned_values = [];
4653
+		foreach ($values as $value) {
4654
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4655
+		}
4656
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4657
+	}
4658
+
4659
+
4660
+	/**
4661
+	 * Takes an array or a comma-separated list of $values and cleans them
4662
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4663
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4664
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4665
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4666
+	 *
4667
+	 * @param mixed                      $values    array or comma-separated string
4668
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4669
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4670
+	 * @throws EE_Error
4671
+	 */
4672
+	public function _construct_in_value($values, $field_obj)
4673
+	{
4674
+		$prepped = [];
4675
+		// check if the value is a CSV list
4676
+		if (is_string($values)) {
4677
+			// in which case, turn it into an array
4678
+			$values = explode(',', $values);
4679
+		}
4680
+		// make sure we only have one of each value in the list
4681
+		$values = array_unique($values);
4682
+		foreach ($values as $value) {
4683
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4684
+		}
4685
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4686
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4687
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4688
+		if (empty($prepped)) {
4689
+			$all_fields  = $this->field_settings();
4690
+			$first_field = reset($all_fields);
4691
+			$main_table  = $this->_get_main_table();
4692
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4693
+		}
4694
+		return '(' . implode(',', $prepped) . ')';
4695
+	}
4696
+
4697
+
4698
+	/**
4699
+	 * @param mixed                      $value
4700
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4701
+	 * @return false|null|string
4702
+	 * @throws EE_Error
4703
+	 */
4704
+	private function _wpdb_prepare_using_field($value, $field_obj)
4705
+	{
4706
+		/** @type WPDB $wpdb */
4707
+		global $wpdb;
4708
+		if ($field_obj instanceof EE_Model_Field_Base) {
4709
+			return $wpdb->prepare(
4710
+				$field_obj->get_wpdb_data_type(),
4711
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4712
+			);
4713
+		} //$field_obj should really just be a data type
4714
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4715
+			throw new EE_Error(
4716
+				sprintf(
4717
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4718
+					$field_obj,
4719
+					implode(",", $this->_valid_wpdb_data_types)
4720
+				)
4721
+			);
4722
+		}
4723
+		return $wpdb->prepare($field_obj, $value);
4724
+	}
4725
+
4726
+
4727
+	/**
4728
+	 * Takes the input parameter and finds the model field that it indicates.
4729
+	 *
4730
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4731
+	 * @return EE_Model_Field_Base
4732
+	 * @throws EE_Error
4733
+	 */
4734
+	protected function _deduce_field_from_query_param($query_param_name)
4735
+	{
4736
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4737
+		// which will help us find the database table and column
4738
+		$query_param_parts = explode(".", $query_param_name);
4739
+		if (empty($query_param_parts)) {
4740
+			throw new EE_Error(
4741
+				sprintf(
4742
+					esc_html__(
4743
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4744
+						'event_espresso'
4745
+					),
4746
+					$query_param_name
4747
+				)
4748
+			);
4749
+		}
4750
+		$number_of_parts       = count($query_param_parts);
4751
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4752
+		if ($number_of_parts === 1) {
4753
+			$field_name = $last_query_param_part;
4754
+			$model_obj  = $this;
4755
+		} else {// $number_of_parts >= 2
4756
+			// the last part is the column name, and there are only 2parts. therefore...
4757
+			$field_name = $last_query_param_part;
4758
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4759
+		}
4760
+		try {
4761
+			return $model_obj->field_settings_for($field_name);
4762
+		} catch (EE_Error $e) {
4763
+			return null;
4764
+		}
4765
+	}
4766
+
4767
+
4768
+	/**
4769
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4770
+	 * alias and column which corresponds to it
4771
+	 *
4772
+	 * @param string $field_name
4773
+	 * @return string
4774
+	 * @throws EE_Error
4775
+	 */
4776
+	public function _get_qualified_column_for_field($field_name)
4777
+	{
4778
+		$all_fields = $this->field_settings();
4779
+		$field      = $all_fields[ $field_name ] ?? false;
4780
+		if ($field) {
4781
+			return $field->get_qualified_column();
4782
+		}
4783
+		throw new EE_Error(
4784
+			sprintf(
4785
+				esc_html__(
4786
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4787
+					'event_espresso'
4788
+				),
4789
+				$field_name,
4790
+				get_class($this)
4791
+			)
4792
+		);
4793
+	}
4794
+
4795
+
4796
+	/**
4797
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4798
+	 * Example usage:
4799
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4800
+	 *      array(),
4801
+	 *      ARRAY_A,
4802
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4803
+	 *  );
4804
+	 * is equivalent to
4805
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4806
+	 * and
4807
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4808
+	 *      array(
4809
+	 *          array(
4810
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4811
+	 *          ),
4812
+	 *          ARRAY_A,
4813
+	 *          implode(
4814
+	 *              ', ',
4815
+	 *              array_merge(
4816
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4817
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4818
+	 *              )
4819
+	 *          )
4820
+	 *      )
4821
+	 *  );
4822
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4823
+	 *
4824
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4825
+	 *                                            and the one whose fields you are selecting for example: when querying
4826
+	 *                                            tickets model and selecting fields from the tickets model you would
4827
+	 *                                            leave this parameter empty, because no models are needed to join
4828
+	 *                                            between the queried model and the selected one. Likewise when
4829
+	 *                                            querying the datetime model and selecting fields from the tickets
4830
+	 *                                            model, it would also be left empty, because there is a direct
4831
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4832
+	 *                                            them together. However, when querying from the event model and
4833
+	 *                                            selecting fields from the ticket model, you should provide the string
4834
+	 *                                            'Datetime', indicating that the event model must first join to the
4835
+	 *                                            datetime model in order to find its relation to ticket model.
4836
+	 *                                            Also, when querying from the venue model and selecting fields from
4837
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4838
+	 *                                            indicating you need to join the venue model to the event model,
4839
+	 *                                            to the datetime model, in order to find its relation to the ticket
4840
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4841
+	 *                                            the models' tables qualified columns
4842
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4843
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4844
+	 *                                            qualified column names
4845
+	 * @return array|string
4846
+	 */
4847
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4848
+	{
4849
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4850
+				? ''
4851
+				: '__');
4852
+		$qualified_columns = [];
4853
+		foreach ($this->field_settings() as $field_name => $field) {
4854
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4855
+		}
4856
+		return $return_string
4857
+			? implode(', ', $qualified_columns)
4858
+			: $qualified_columns;
4859
+	}
4860
+
4861
+
4862
+	/**
4863
+	 * constructs the select use on special limit joins
4864
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4865
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4866
+	 * (as that is typically where the limits would be set).
4867
+	 *
4868
+	 * @param string       $table_alias The table the select is being built for
4869
+	 * @param mixed|string $limit       The limit for this select
4870
+	 * @return string                The final select join element for the query.
4871
+	 * @throws EE_Error
4872
+	 * @throws EE_Error
4873
+	 */
4874
+	public function _construct_limit_join_select($table_alias, $limit)
4875
+	{
4876
+		$SQL = '';
4877
+		foreach ($this->_tables as $table_obj) {
4878
+			if ($table_obj instanceof EE_Primary_Table) {
4879
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4880
+					? $table_obj->get_select_join_limit($limit)
4881
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4882
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4883
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4884
+					? $table_obj->get_select_join_limit_join($limit)
4885
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4886
+			}
4887
+		}
4888
+		return $SQL;
4889
+	}
4890
+
4891
+
4892
+	/**
4893
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4894
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4895
+	 *
4896
+	 * @return string SQL
4897
+	 * @throws EE_Error
4898
+	 */
4899
+	public function _construct_internal_join()
4900
+	{
4901
+		$SQL = $this->_get_main_table()->get_table_sql();
4902
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4903
+		return $SQL;
4904
+	}
4905
+
4906
+
4907
+	/**
4908
+	 * Constructs the SQL for joining all the tables on this model.
4909
+	 * Normally $alias should be the primary table's alias, but in cases where
4910
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4911
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4912
+	 * alias, this will construct SQL like:
4913
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4914
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4915
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4916
+	 *
4917
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4918
+	 * @return string
4919
+	 * @throws EE_Error
4920
+	 * @throws EE_Error
4921
+	 */
4922
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4923
+	{
4924
+		$SQL               = '';
4925
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4926
+		foreach ($this->_tables as $table_obj) {
4927
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4928
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4929
+					// so we're joining to this table, meaning the table is already in
4930
+					// the FROM statement, BUT the primary table isn't. So we want
4931
+					// to add the inverse join sql
4932
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4933
+				} else {
4934
+					// just add a regular JOIN to this table from the primary table
4935
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4936
+				}
4937
+			}// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4938
+		}
4939
+		return $SQL;
4940
+	}
4941
+
4942
+
4943
+	/**
4944
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4945
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4946
+	 * their data type (eg, '%s', '%d', etc)
4947
+	 *
4948
+	 * @return array
4949
+	 */
4950
+	public function _get_data_types()
4951
+	{
4952
+		$data_types = [];
4953
+		foreach ($this->field_settings() as $field_obj) {
4954
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4955
+			/** @var $field_obj EE_Model_Field_Base */
4956
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4957
+		}
4958
+		return $data_types;
4959
+	}
4960
+
4961
+
4962
+	/**
4963
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4964
+	 *
4965
+	 * @param string $model_name
4966
+	 * @return EEM_Base
4967
+	 * @throws EE_Error
4968
+	 */
4969
+	public function get_related_model_obj($model_name)
4970
+	{
4971
+		$model_classname = "EEM_" . $model_name;
4972
+		if (! class_exists($model_classname)) {
4973
+			throw new EE_Error(
4974
+				sprintf(
4975
+					esc_html__(
4976
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4977
+						'event_espresso'
4978
+					),
4979
+					$model_name,
4980
+					$model_classname
4981
+				)
4982
+			);
4983
+		}
4984
+		return call_user_func($model_classname . "::instance");
4985
+	}
4986
+
4987
+
4988
+	/**
4989
+	 * Returns the array of EE_ModelRelations for this model.
4990
+	 *
4991
+	 * @return EE_Model_Relation_Base[]
4992
+	 */
4993
+	public function relation_settings()
4994
+	{
4995
+		return $this->_model_relations;
4996
+	}
4997
+
4998
+
4999
+	/**
5000
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
5001
+	 * because without THOSE models, this model probably doesn't have much purpose.
5002
+	 * (Eg, without an event, datetimes have little purpose.)
5003
+	 *
5004
+	 * @return EE_Belongs_To_Relation[]
5005
+	 */
5006
+	public function belongs_to_relations()
5007
+	{
5008
+		$belongs_to_relations = [];
5009
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
5010
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
5011
+				$belongs_to_relations[ $model_name ] = $relation_obj;
5012
+			}
5013
+		}
5014
+		return $belongs_to_relations;
5015
+	}
5016
+
5017
+
5018
+	/**
5019
+	 * Returns the specified EE_Model_Relation, or throws an exception
5020
+	 *
5021
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
5022
+	 * @return EE_Model_Relation_Base
5023
+	 * @throws EE_Error
5024
+	 */
5025
+	public function related_settings_for($relation_name)
5026
+	{
5027
+		$relatedModels = $this->relation_settings();
5028
+		if (! array_key_exists($relation_name, $relatedModels)) {
5029
+			throw new EE_Error(
5030
+				sprintf(
5031
+					esc_html__(
5032
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5033
+						'event_espresso'
5034
+					),
5035
+					$relation_name,
5036
+					$this->_get_class_name(),
5037
+					implode(', ', array_keys($relatedModels))
5038
+				)
5039
+			);
5040
+		}
5041
+		return $relatedModels[ $relation_name ];
5042
+	}
5043
+
5044
+
5045
+	/**
5046
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5047
+	 * fields
5048
+	 *
5049
+	 * @param string  $fieldName
5050
+	 * @param boolean $include_db_only_fields
5051
+	 * @return EE_Model_Field_Base
5052
+	 * @throws EE_Error
5053
+	 */
5054
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
5055
+	{
5056
+		$fieldSettings = $this->field_settings($include_db_only_fields);
5057
+		if (! array_key_exists($fieldName, $fieldSettings)) {
5058
+			throw new EE_Error(
5059
+				sprintf(
5060
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5061
+					$fieldName,
5062
+					get_class($this)
5063
+				)
5064
+			);
5065
+		}
5066
+		return $fieldSettings[ $fieldName ];
5067
+	}
5068
+
5069
+
5070
+	/**
5071
+	 * Checks if this field exists on this model
5072
+	 *
5073
+	 * @param string $fieldName a key in the model's _field_settings array
5074
+	 * @return boolean
5075
+	 */
5076
+	public function has_field($fieldName)
5077
+	{
5078
+		$fieldSettings = $this->field_settings(true);
5079
+		if (isset($fieldSettings[ $fieldName ])) {
5080
+			return true;
5081
+		}
5082
+		return false;
5083
+	}
5084
+
5085
+
5086
+	/**
5087
+	 * Returns whether or not this model has a relation to the specified model
5088
+	 *
5089
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5090
+	 * @return boolean
5091
+	 */
5092
+	public function has_relation($relation_name)
5093
+	{
5094
+		$relations = $this->relation_settings();
5095
+		if (isset($relations[ $relation_name ])) {
5096
+			return true;
5097
+		}
5098
+		return false;
5099
+	}
5100
+
5101
+
5102
+	/**
5103
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5104
+	 * Eg, on EE_Answer that would be ANS_ID field object
5105
+	 *
5106
+	 * @param $field_obj
5107
+	 * @return boolean
5108
+	 */
5109
+	public function is_primary_key_field($field_obj): bool
5110
+	{
5111
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5112
+	}
5113
+
5114
+
5115
+	/**
5116
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5117
+	 * Eg, on EE_Answer that would be ANS_ID field object
5118
+	 *
5119
+	 * @return EE_Primary_Key_Field_Base
5120
+	 * @throws EE_Error
5121
+	 */
5122
+	public function get_primary_key_field()
5123
+	{
5124
+		if ($this->_primary_key_field === null) {
5125
+			foreach ($this->field_settings(true) as $field_obj) {
5126
+				if ($this->is_primary_key_field($field_obj)) {
5127
+					$this->_primary_key_field = $field_obj;
5128
+					break;
5129
+				}
5130
+			}
5131
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5132
+				throw new EE_Error(
5133
+					sprintf(
5134
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5135
+						get_class($this)
5136
+					)
5137
+				);
5138
+			}
5139
+		}
5140
+		return $this->_primary_key_field;
5141
+	}
5142
+
5143
+
5144
+	/**
5145
+	 * Returns whether or not not there is a primary key on this model.
5146
+	 * Internally does some caching.
5147
+	 *
5148
+	 * @return boolean
5149
+	 */
5150
+	public function has_primary_key_field()
5151
+	{
5152
+		if ($this->_has_primary_key_field === null) {
5153
+			try {
5154
+				$this->get_primary_key_field();
5155
+				$this->_has_primary_key_field = true;
5156
+			} catch (EE_Error $e) {
5157
+				$this->_has_primary_key_field = false;
5158
+			}
5159
+		}
5160
+		return $this->_has_primary_key_field;
5161
+	}
5162
+
5163
+
5164
+	/**
5165
+	 * Finds the first field of type $field_class_name.
5166
+	 *
5167
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5168
+	 *                                 EE_Foreign_Key_Field, etc
5169
+	 * @return EE_Model_Field_Base or null if none is found
5170
+	 */
5171
+	public function get_a_field_of_type($field_class_name)
5172
+	{
5173
+		foreach ($this->field_settings() as $field) {
5174
+			if ($field instanceof $field_class_name) {
5175
+				return $field;
5176
+			}
5177
+		}
5178
+		return null;
5179
+	}
5180
+
5181
+
5182
+	/**
5183
+	 * Gets a foreign key field pointing to model.
5184
+	 *
5185
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5186
+	 * @return EE_Foreign_Key_Field_Base
5187
+	 * @throws EE_Error
5188
+	 */
5189
+	public function get_foreign_key_to($model_name)
5190
+	{
5191
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5192
+			foreach ($this->field_settings() as $field) {
5193
+				if (
5194
+					$field instanceof EE_Foreign_Key_Field_Base
5195
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5196
+				) {
5197
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5198
+					break;
5199
+				}
5200
+			}
5201
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5202
+				throw new EE_Error(
5203
+					sprintf(
5204
+						esc_html__(
5205
+							"There is no foreign key field pointing to model %s on model %s",
5206
+							'event_espresso'
5207
+						),
5208
+						$model_name,
5209
+						get_class($this)
5210
+					)
5211
+				);
5212
+			}
5213
+		}
5214
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5215
+	}
5216
+
5217
+
5218
+	/**
5219
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5220
+	 *
5221
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5222
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5223
+	 *                            Either one works
5224
+	 * @return string
5225
+	 */
5226
+	public function get_table_for_alias($table_alias)
5227
+	{
5228
+		$table_alias_sans_model_relation_chain_prefix =
5229
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5230
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5231
+	}
5232
+
5233
+
5234
+	/**
5235
+	 * Returns a flat array of all field son this model, instead of organizing them
5236
+	 * by table_alias as they are in the constructor.
5237
+	 *
5238
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5239
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5240
+	 */
5241
+	public function field_settings($include_db_only_fields = false)
5242
+	{
5243
+		if ($include_db_only_fields) {
5244
+			if ($this->_cached_fields === null) {
5245
+				$this->_cached_fields = [];
5246
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5247
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
+						$this->_cached_fields[ $field_name ] = $field_obj;
5249
+					}
5250
+				}
5251
+			}
5252
+			return $this->_cached_fields;
5253
+		}
5254
+		if ($this->_cached_fields_non_db_only === null) {
5255
+			$this->_cached_fields_non_db_only = [];
5256
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5257
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5258
+					/** @var $field_obj EE_Model_Field_Base */
5259
+					if (! $field_obj->is_db_only_field()) {
5260
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5261
+					}
5262
+				}
5263
+			}
5264
+		}
5265
+		return $this->_cached_fields_non_db_only;
5266
+	}
5267
+
5268
+
5269
+	/**
5270
+	 *        cycle though array of attendees and create objects out of each item
5271
+	 *
5272
+	 * @access        private
5273
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5274
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5275
+	 *                           numerically indexed)
5276
+	 * @throws EE_Error
5277
+	 * @throws ReflectionException
5278
+	 */
5279
+	protected function _create_objects($rows = [])
5280
+	{
5281
+		$array_of_objects = [];
5282
+		if (empty($rows)) {
5283
+			return [];
5284
+		}
5285
+		$count_if_model_has_no_primary_key = 0;
5286
+		$has_primary_key                   = $this->has_primary_key_field();
5287
+		$primary_key_field                 = $has_primary_key
5288
+			? $this->get_primary_key_field()
5289
+			: null;
5290
+		foreach ((array) $rows as $row) {
5291
+			if (empty($row)) {
5292
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5293
+				return [];
5294
+			}
5295
+			// check if we've already set this object in the results array,
5296
+			// in which case there's no need to process it further (again)
5297
+			if ($has_primary_key) {
5298
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5299
+					$row,
5300
+					$primary_key_field->get_qualified_column(),
5301
+					$primary_key_field->get_table_column()
5302
+				);
5303
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5304
+					continue;
5305
+				}
5306
+			}
5307
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5308
+			if (! $classInstance) {
5309
+				throw new EE_Error(
5310
+					sprintf(
5311
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5312
+						$this->get_this_model_name(),
5313
+						http_build_query($row)
5314
+					)
5315
+				);
5316
+			}
5317
+			// set the timezone on the instantiated objects
5318
+			$classInstance->set_timezone($this->_timezone);
5319
+			// make sure if there is any timezone setting present that we set the timezone for the object
5320
+			$key                      = $has_primary_key
5321
+				? $classInstance->ID()
5322
+				: $count_if_model_has_no_primary_key++;
5323
+			$array_of_objects[ $key ] = $classInstance;
5324
+			// also, for all the relations of type BelongsTo, see if we can cache
5325
+			// those related models
5326
+			// (we could do this for other relations too, but if there are conditions
5327
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5328
+			// so it requires a little more thought than just caching them immediately...)
5329
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5330
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5331
+					// check if this model's INFO is present. If so, cache it on the model
5332
+					$other_model           = $relation_obj->get_other_model();
5333
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5334
+					// if we managed to make a model object from the results, cache it on the main model object
5335
+					if ($other_model_obj_maybe) {
5336
+						// set timezone on these other model objects if they are present
5337
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5338
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5339
+					}
5340
+				}
5341
+			}
5342
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5343
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5344
+			// the field in the CustomSelects object
5345
+			if ($this->_custom_selections instanceof CustomSelects) {
5346
+				$classInstance->setCustomSelectsValues(
5347
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5348
+				);
5349
+			}
5350
+		}
5351
+		return $array_of_objects;
5352
+	}
5353
+
5354
+
5355
+	/**
5356
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5357
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5358
+	 *
5359
+	 * @param array $db_results_row
5360
+	 * @return array
5361
+	 */
5362
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5363
+	{
5364
+		$results = [];
5365
+		if ($this->_custom_selections instanceof CustomSelects) {
5366
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5367
+				if (isset($db_results_row[ $alias ])) {
5368
+					$results[ $alias ] = $this->convertValueToDataType(
5369
+						$db_results_row[ $alias ],
5370
+						$this->_custom_selections->getDataTypeForAlias($alias)
5371
+					);
5372
+				}
5373
+			}
5374
+		}
5375
+		return $results;
5376
+	}
5377
+
5378
+
5379
+	/**
5380
+	 * This will set the value for the given alias
5381
+	 *
5382
+	 * @param string $value
5383
+	 * @param string $datatype (one of %d, %s, %f)
5384
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5385
+	 */
5386
+	protected function convertValueToDataType($value, $datatype)
5387
+	{
5388
+		switch ($datatype) {
5389
+			case '%f':
5390
+				return (float) $value;
5391
+			case '%d':
5392
+				return (int) $value;
5393
+			default:
5394
+				return (string) $value;
5395
+		}
5396
+	}
5397
+
5398
+
5399
+	/**
5400
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5401
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5402
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5403
+	 * object (as set in the model_field!).
5404
+	 *
5405
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5406
+	 * @throws EE_Error
5407
+	 * @throws ReflectionException
5408
+	 */
5409
+	public function create_default_object()
5410
+	{
5411
+		$this_model_fields_and_values = [];
5412
+		// setup the row using default values;
5413
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5414
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5415
+		}
5416
+		$className = $this->_get_class_name();
5417
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5418
+	}
5419
+
5420
+
5421
+	/**
5422
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5423
+	 *                             or an stdClass where each property is the name of a column,
5424
+	 * @return EE_Base_Class
5425
+	 * @throws EE_Error
5426
+	 * @throws ReflectionException
5427
+	 */
5428
+	public function instantiate_class_from_array_or_object($cols_n_values)
5429
+	{
5430
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5431
+			$cols_n_values = get_object_vars($cols_n_values);
5432
+		}
5433
+		$primary_key = null;
5434
+		// make sure the array only has keys that are fields/columns on this model
5435
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5436
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5437
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5438
+		}
5439
+		$className = $this->_get_class_name();
5440
+		// check we actually found results that we can use to build our model object
5441
+		// if not, return null
5442
+		if ($this->has_primary_key_field()) {
5443
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5444
+				return null;
5445
+			}
5446
+		} elseif ($this->unique_indexes()) {
5447
+			$first_column = reset($this_model_fields_n_values);
5448
+			if (empty($first_column)) {
5449
+				return null;
5450
+			}
5451
+		}
5452
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5453
+		if ($primary_key) {
5454
+			$classInstance = $this->get_from_entity_map($primary_key);
5455
+			if (! $classInstance) {
5456
+				$classInstance = EE_Registry::instance()
5457
+											->load_class(
5458
+												$className,
5459
+												[$this_model_fields_n_values, $this->_timezone],
5460
+												true,
5461
+												false
5462
+											);
5463
+				// add this new object to the entity map
5464
+				$classInstance = $this->add_to_entity_map($classInstance);
5465
+			}
5466
+		} else {
5467
+			$classInstance = EE_Registry::instance()->load_class(
5468
+				$className,
5469
+				[$this_model_fields_n_values, $this->_timezone],
5470
+				true,
5471
+				false
5472
+			);
5473
+		}
5474
+		return $classInstance;
5475
+	}
5476
+
5477
+
5478
+	/**
5479
+	 * Gets the model object from the  entity map if it exists
5480
+	 *
5481
+	 * @param int|string $id the ID of the model object
5482
+	 * @return EE_Base_Class
5483
+	 */
5484
+	public function get_from_entity_map($id)
5485
+	{
5486
+		return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5487
+	}
5488
+
5489
+
5490
+	/**
5491
+	 * add_to_entity_map
5492
+	 * Adds the object to the model's entity mappings
5493
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5494
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5495
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5496
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5497
+	 *        then this method should be called immediately after the update query
5498
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5499
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5500
+	 *
5501
+	 * @param EE_Base_Class $object
5502
+	 * @return EE_Base_Class
5503
+	 * @throws EE_Error
5504
+	 * @throws ReflectionException
5505
+	 */
5506
+	public function add_to_entity_map(EE_Base_Class $object)
5507
+	{
5508
+		$className = $this->_get_class_name();
5509
+		if (! $object instanceof $className) {
5510
+			throw new EE_Error(
5511
+				sprintf(
5512
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5513
+					is_object($object)
5514
+						? get_class($object)
5515
+						: $object,
5516
+					$className
5517
+				)
5518
+			);
5519
+		}
5520
+
5521
+		if (! $object->ID()) {
5522
+			throw new EE_Error(
5523
+				sprintf(
5524
+					esc_html__(
5525
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5526
+						"event_espresso"
5527
+					),
5528
+					get_class($this)
5529
+				)
5530
+			);
5531
+		}
5532
+		// double check it's not already there
5533
+		$classInstance = $this->get_from_entity_map($object->ID());
5534
+		if ($classInstance) {
5535
+			return $classInstance;
5536
+		}
5537
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5538
+		return $object;
5539
+	}
5540
+
5541
+
5542
+	/**
5543
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5544
+	 * if no identifier is provided, then the entire entity map is emptied
5545
+	 *
5546
+	 * @param int|string $id the ID of the model object
5547
+	 * @return boolean
5548
+	 */
5549
+	public function clear_entity_map($id = null)
5550
+	{
5551
+		if (empty($id)) {
5552
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5553
+			return true;
5554
+		}
5555
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5556
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5557
+			return true;
5558
+		}
5559
+		return false;
5560
+	}
5561
+
5562
+
5563
+	/**
5564
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5565
+	 * Given an array where keys are column (or column alias) names and values,
5566
+	 * returns an array of their corresponding field names and database values
5567
+	 *
5568
+	 * @param array $cols_n_values
5569
+	 * @return array
5570
+	 * @throws EE_Error
5571
+	 * @throws ReflectionException
5572
+	 */
5573
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5574
+	{
5575
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5576
+	}
5577
+
5578
+
5579
+	/**
5580
+	 * _deduce_fields_n_values_from_cols_n_values
5581
+	 * Given an array where keys are column (or column alias) names and values,
5582
+	 * returns an array of their corresponding field names and database values
5583
+	 *
5584
+	 * @param array|stdClass $cols_n_values
5585
+	 * @return array
5586
+	 * @throws EE_Error
5587
+	 * @throws ReflectionException
5588
+	 */
5589
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5590
+	{
5591
+		if ($cols_n_values instanceof stdClass) {
5592
+			$cols_n_values = get_object_vars($cols_n_values);
5593
+		}
5594
+		$this_model_fields_n_values = [];
5595
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5596
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5597
+				$cols_n_values,
5598
+				$table_obj->get_fully_qualified_pk_column(),
5599
+				$table_obj->get_pk_column()
5600
+			);
5601
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5602
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5603
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
+					if (! $field_obj->is_db_only_field()) {
5605
+						// prepare field as if its coming from db
5606
+						$prepared_value                            =
5607
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5608
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5609
+					}
5610
+				}
5611
+			} else {
5612
+				// the table's rows existed. Use their values
5613
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5614
+					if (! $field_obj->is_db_only_field()) {
5615
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5616
+							$cols_n_values,
5617
+							$field_obj->get_qualified_column(),
5618
+							$field_obj->get_table_column()
5619
+						);
5620
+					}
5621
+				}
5622
+			}
5623
+		}
5624
+		return $this_model_fields_n_values;
5625
+	}
5626
+
5627
+
5628
+	/**
5629
+	 * @param $cols_n_values
5630
+	 * @param $qualified_column
5631
+	 * @param $regular_column
5632
+	 * @return null
5633
+	 * @throws EE_Error
5634
+	 * @throws ReflectionException
5635
+	 */
5636
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5637
+	{
5638
+		$value = null;
5639
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5640
+		// does the field on the model relate to this column retrieved from the db?
5641
+		// or is it a db-only field? (not relating to the model)
5642
+		if (isset($cols_n_values[ $qualified_column ])) {
5643
+			$value = $cols_n_values[ $qualified_column ];
5644
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5645
+			$value = $cols_n_values[ $regular_column ];
5646
+		} elseif (! empty($this->foreign_key_aliases)) {
5647
+			// no PK?  ok check if there is a foreign key alias set for this table
5648
+			// then check if that alias exists in the incoming data
5649
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5650
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5651
+				if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5652
+					$value = $cols_n_values[ $FK_alias ];
5653
+					[$pk_class] = explode('.', $PK_column);
5654
+					$pk_model_name = "EEM_{$pk_class}";
5655
+					/** @var EEM_Base $pk_model */
5656
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5657
+					if ($pk_model instanceof EEM_Base) {
5658
+						// make sure object is pulled from db and added to entity map
5659
+						$pk_model->get_one_by_ID($value);
5660
+					}
5661
+					break;
5662
+				}
5663
+			}
5664
+		}
5665
+		return $value;
5666
+	}
5667
+
5668
+
5669
+	/**
5670
+	 * refresh_entity_map_from_db
5671
+	 * Makes sure the model object in the entity map at $id assumes the values
5672
+	 * of the database (opposite of EE_base_Class::save())
5673
+	 *
5674
+	 * @param int|string $id
5675
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5676
+	 * @throws EE_Error
5677
+	 * @throws ReflectionException
5678
+	 */
5679
+	public function refresh_entity_map_from_db($id)
5680
+	{
5681
+		$obj_in_map = $this->get_from_entity_map($id);
5682
+		if ($obj_in_map) {
5683
+			$wpdb_results = $this->_get_all_wpdb_results(
5684
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5685
+			);
5686
+			if ($wpdb_results && is_array($wpdb_results)) {
5687
+				$one_row = reset($wpdb_results);
5688
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5689
+					$obj_in_map->set_from_db($field_name, $db_value);
5690
+				}
5691
+				// clear the cache of related model objects
5692
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5693
+					$obj_in_map->clear_cache($relation_name, null, true);
5694
+				}
5695
+			}
5696
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5697
+			return $obj_in_map;
5698
+		}
5699
+		return $this->get_one_by_ID($id);
5700
+	}
5701
+
5702
+
5703
+	/**
5704
+	 * refresh_entity_map_with
5705
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5706
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5707
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5708
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5709
+	 *
5710
+	 * @param int|string    $id
5711
+	 * @param EE_Base_Class $replacing_model_obj
5712
+	 * @return EE_Base_Class
5713
+	 * @throws EE_Error
5714
+	 * @throws ReflectionException
5715
+	 */
5716
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5717
+	{
5718
+		$obj_in_map = $this->get_from_entity_map($id);
5719
+		if ($obj_in_map) {
5720
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5721
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5722
+					$obj_in_map->set($field_name, $value);
5723
+				}
5724
+				// make the model object in the entity map's cache match the $replacing_model_obj
5725
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5726
+					$obj_in_map->clear_cache($relation_name, null, true);
5727
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5728
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5729
+					}
5730
+				}
5731
+			}
5732
+			return $obj_in_map;
5733
+		}
5734
+		$this->add_to_entity_map($replacing_model_obj);
5735
+		return $replacing_model_obj;
5736
+	}
5737
+
5738
+
5739
+	/**
5740
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5741
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5742
+	 * require_once($this->_getClassName().".class.php");
5743
+	 *
5744
+	 * @return string
5745
+	 */
5746
+	private function _get_class_name()
5747
+	{
5748
+		return "EE_" . $this->get_this_model_name();
5749
+	}
5750
+
5751
+
5752
+	/**
5753
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5754
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5755
+	 * it would be 'Events'.
5756
+	 *
5757
+	 * @param int|float|null $quantity
5758
+	 * @return string
5759
+	 */
5760
+	public function item_name($quantity = 1): string
5761
+	{
5762
+		$quantity = floor($quantity);
5763
+		return apply_filters(
5764
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5765
+			$quantity > 1
5766
+				? $this->plural_item
5767
+				: $this->singular_item,
5768
+			$quantity,
5769
+			$this->plural_item,
5770
+			$this->singular_item
5771
+		);
5772
+	}
5773
+
5774
+
5775
+	/**
5776
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5777
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5778
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5779
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5780
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5781
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5782
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5783
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5784
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5785
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5786
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5787
+	 *        return $previousReturnValue.$returnString;
5788
+	 * }
5789
+	 * require('EEM_Answer.model.php');
5790
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5791
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5792
+	 *
5793
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5794
+	 * @param array  $args       array of original arguments passed to the function
5795
+	 * @return mixed whatever the plugin which calls add_filter decides
5796
+	 * @throws EE_Error
5797
+	 */
5798
+	public function __call($methodName, $args)
5799
+	{
5800
+		$className = get_class($this);
5801
+		$tagName   = "FHEE__{$className}__{$methodName}";
5802
+		if (! has_filter($tagName)) {
5803
+			throw new EE_Error(
5804
+				sprintf(
5805
+					esc_html__(
5806
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5807
+						'event_espresso'
5808
+					),
5809
+					$methodName,
5810
+					$className,
5811
+					$tagName,
5812
+					'<br />'
5813
+				)
5814
+			);
5815
+		}
5816
+		return apply_filters($tagName, null, $this, $args);
5817
+	}
5818
+
5819
+
5820
+	/**
5821
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5822
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5823
+	 *
5824
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5825
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5826
+	 *                                                       the object's class name
5827
+	 *                                                       or object's ID
5828
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5829
+	 *                                                       exists in the database. If it does not, we add it
5830
+	 * @return EE_Base_Class
5831
+	 * @throws EE_Error
5832
+	 * @throws ReflectionException
5833
+	 */
5834
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5835
+	{
5836
+		$className = $this->_get_class_name();
5837
+		if ($base_class_obj_or_id instanceof $className) {
5838
+			$model_object = $base_class_obj_or_id;
5839
+		} else {
5840
+			$primary_key_field = $this->get_primary_key_field();
5841
+			if (
5842
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5843
+				&& (
5844
+					is_int($base_class_obj_or_id)
5845
+					|| is_string($base_class_obj_or_id)
5846
+				)
5847
+			) {
5848
+				// assume it's an ID.
5849
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5850
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5851
+			} elseif (
5852
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5853
+				&& is_string($base_class_obj_or_id)
5854
+			) {
5855
+				// assume it's a string representation of the object
5856
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5857
+			} else {
5858
+				throw new EE_Error(
5859
+					sprintf(
5860
+						esc_html__(
5861
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5862
+							'event_espresso'
5863
+						),
5864
+						$base_class_obj_or_id,
5865
+						$this->_get_class_name(),
5866
+						print_r($base_class_obj_or_id, true)
5867
+					)
5868
+				);
5869
+			}
5870
+		}
5871
+		if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5872
+			$model_object->save();
5873
+		}
5874
+		return $model_object;
5875
+	}
5876
+
5877
+
5878
+	/**
5879
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5880
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5881
+	 * returns it ID.
5882
+	 *
5883
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5884
+	 * @return int|string depending on the type of this model object's ID
5885
+	 * @throws EE_Error
5886
+	 * @throws ReflectionException
5887
+	 */
5888
+	public function ensure_is_ID($base_class_obj_or_id)
5889
+	{
5890
+		$className = $this->_get_class_name();
5891
+		if ($base_class_obj_or_id instanceof $className) {
5892
+			/** @var $base_class_obj_or_id EE_Base_Class */
5893
+			$id = $base_class_obj_or_id->ID();
5894
+		} elseif (is_int($base_class_obj_or_id)) {
5895
+			// assume it's an ID
5896
+			$id = $base_class_obj_or_id;
5897
+		} elseif (is_string($base_class_obj_or_id)) {
5898
+			// assume its a string representation of the object
5899
+			$id = $base_class_obj_or_id;
5900
+		} else {
5901
+			throw new EE_Error(
5902
+				sprintf(
5903
+					esc_html__(
5904
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5905
+						'event_espresso'
5906
+					),
5907
+					$base_class_obj_or_id,
5908
+					$this->_get_class_name(),
5909
+					print_r($base_class_obj_or_id, true)
5910
+				)
5911
+			);
5912
+		}
5913
+		return $id;
5914
+	}
5915
+
5916
+
5917
+	/**
5918
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5919
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5920
+	 * been sanitized and converted into the appropriate domain.
5921
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5922
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5923
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5924
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5925
+	 * $EVT = EEM_Event::instance(); $old_setting =
5926
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5927
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5928
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5929
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5930
+	 *
5931
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5932
+	 * @return void
5933
+	 */
5934
+	public function assume_values_already_prepared_by_model_object(
5935
+		$values_already_prepared = self::not_prepared_by_model_object
5936
+	) {
5937
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5938
+	}
5939
+
5940
+
5941
+	/**
5942
+	 * Read comments for assume_values_already_prepared_by_model_object()
5943
+	 *
5944
+	 * @return int
5945
+	 */
5946
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5947
+	{
5948
+		return $this->_values_already_prepared_by_model_object;
5949
+	}
5950
+
5951
+
5952
+	/**
5953
+	 * Gets all the indexes on this model
5954
+	 *
5955
+	 * @return EE_Index[]
5956
+	 */
5957
+	public function indexes()
5958
+	{
5959
+		return $this->_indexes;
5960
+	}
5961
+
5962
+
5963
+	/**
5964
+	 * Gets all the Unique Indexes on this model
5965
+	 *
5966
+	 * @return EE_Unique_Index[]
5967
+	 */
5968
+	public function unique_indexes()
5969
+	{
5970
+		$unique_indexes = [];
5971
+		foreach ($this->_indexes as $name => $index) {
5972
+			if ($index instanceof EE_Unique_Index) {
5973
+				$unique_indexes [ $name ] = $index;
5974
+			}
5975
+		}
5976
+		return $unique_indexes;
5977
+	}
5978
+
5979
+
5980
+	/**
5981
+	 * Gets all the fields which, when combined, make the primary key.
5982
+	 * This is usually just an array with 1 element (the primary key), but in cases
5983
+	 * where there is no primary key, it's a combination of fields as defined
5984
+	 * on a primary index
5985
+	 *
5986
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5987
+	 * @throws EE_Error
5988
+	 */
5989
+	public function get_combined_primary_key_fields()
5990
+	{
5991
+		foreach ($this->indexes() as $index) {
5992
+			if ($index instanceof EE_Primary_Key_Index) {
5993
+				return $index->fields();
5994
+			}
5995
+		}
5996
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5997
+	}
5998
+
5999
+
6000
+	/**
6001
+	 * Used to build a primary key string (when the model has no primary key),
6002
+	 * which can be used a unique string to identify this model object.
6003
+	 *
6004
+	 * @param array $fields_n_values keys are field names, values are their values.
6005
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
6006
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
6007
+	 *                               before passing it to this function (that will convert it from columns-n-values
6008
+	 *                               to field-names-n-values).
6009
+	 * @return string
6010
+	 * @throws EE_Error
6011
+	 */
6012
+	public function get_index_primary_key_string($fields_n_values)
6013
+	{
6014
+		$cols_n_values_for_primary_key_index = array_intersect_key(
6015
+			$fields_n_values,
6016
+			$this->get_combined_primary_key_fields()
6017
+		);
6018
+		return http_build_query($cols_n_values_for_primary_key_index);
6019
+	}
6020
+
6021
+
6022
+	/**
6023
+	 * Gets the field values from the primary key string
6024
+	 *
6025
+	 * @param string $index_primary_key_string
6026
+	 * @return null|array
6027
+	 * @throws EE_Error
6028
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6029
+	 */
6030
+	public function parse_index_primary_key_string($index_primary_key_string)
6031
+	{
6032
+		$key_fields = $this->get_combined_primary_key_fields();
6033
+		// check all of them are in the $id
6034
+		$key_vals_in_combined_pk = [];
6035
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6036
+		foreach ($key_fields as $key_field_name => $field_obj) {
6037
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6038
+				return null;
6039
+			}
6040
+		}
6041
+		return $key_vals_in_combined_pk;
6042
+	}
6043
+
6044
+
6045
+	/**
6046
+	 * verifies that an array of key-value pairs for model fields has a key
6047
+	 * for each field comprising the primary key index
6048
+	 *
6049
+	 * @param array $key_vals
6050
+	 * @return boolean
6051
+	 * @throws EE_Error
6052
+	 */
6053
+	public function has_all_combined_primary_key_fields($key_vals)
6054
+	{
6055
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6056
+		foreach ($keys_it_should_have as $key) {
6057
+			if (! isset($key_vals[ $key ])) {
6058
+				return false;
6059
+			}
6060
+		}
6061
+		return true;
6062
+	}
6063
+
6064
+
6065
+	/**
6066
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6067
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
6068
+	 *
6069
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6070
+	 * @param array               $query_params                     @see
6071
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6072
+	 * @throws EE_Error
6073
+	 * @throws ReflectionException
6074
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6075
+	 *                                                              indexed)
6076
+	 */
6077
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6078
+	{
6079
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6080
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
6081
+		} elseif (is_array($model_object_or_attributes_array)) {
6082
+			$attributes_array = $model_object_or_attributes_array;
6083
+		} else {
6084
+			throw new EE_Error(
6085
+				sprintf(
6086
+					esc_html__(
6087
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6088
+						"event_espresso"
6089
+					),
6090
+					$model_object_or_attributes_array
6091
+				)
6092
+			);
6093
+		}
6094
+		// even copies obviously won't have the same ID, so remove the primary key
6095
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6096
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6097
+			unset($attributes_array[ $this->primary_key_name() ]);
6098
+		}
6099
+		if (isset($query_params[0])) {
6100
+			$query_params[0] = array_merge($attributes_array, $query_params);
6101
+		} else {
6102
+			$query_params[0] = $attributes_array;
6103
+		}
6104
+		return $this->get_all($query_params);
6105
+	}
6106
+
6107
+
6108
+	/**
6109
+	 * Gets the first copy we find. See get_all_copies for more details
6110
+	 *
6111
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6112
+	 * @param array $query_params
6113
+	 * @return EE_Base_Class
6114
+	 * @throws EE_Error
6115
+	 * @throws ReflectionException
6116
+	 */
6117
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6118
+	{
6119
+		if (! is_array($query_params)) {
6120
+			EE_Error::doing_it_wrong(
6121
+				'EEM_Base::get_one_copy',
6122
+				sprintf(
6123
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6124
+					gettype($query_params)
6125
+				),
6126
+				'4.6.0'
6127
+			);
6128
+			$query_params = [];
6129
+		}
6130
+		$query_params['limit'] = 1;
6131
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6132
+		if (is_array($copies)) {
6133
+			return array_shift($copies);
6134
+		}
6135
+		return null;
6136
+	}
6137
+
6138
+
6139
+	/**
6140
+	 * Updates the item with the specified id. Ignores default query parameters because
6141
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6142
+	 *
6143
+	 * @param array      $fields_n_values keys are field names, values are their new values
6144
+	 * @param int|string $id              the value of the primary key to update
6145
+	 * @return int number of rows updated
6146
+	 * @throws EE_Error
6147
+	 * @throws ReflectionException
6148
+	 */
6149
+	public function update_by_ID($fields_n_values, $id)
6150
+	{
6151
+		$query_params = [
6152
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6153
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6154
+		];
6155
+		return $this->update($fields_n_values, $query_params);
6156
+	}
6157
+
6158
+
6159
+	/**
6160
+	 * Changes an operator which was supplied to the models into one usable in SQL
6161
+	 *
6162
+	 * @param string $operator_supplied
6163
+	 * @return string an operator which can be used in SQL
6164
+	 * @throws EE_Error
6165
+	 */
6166
+	private function _prepare_operator_for_sql($operator_supplied)
6167
+	{
6168
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6169
+		if ($sql_operator) {
6170
+			return $sql_operator;
6171
+		}
6172
+		throw new EE_Error(
6173
+			sprintf(
6174
+				esc_html__(
6175
+					"The operator '%s' is not in the list of valid operators: %s",
6176
+					"event_espresso"
6177
+				),
6178
+				$operator_supplied,
6179
+				implode(",", array_keys($this->_valid_operators))
6180
+			)
6181
+		);
6182
+	}
6183
+
6184
+
6185
+	/**
6186
+	 * Gets the valid operators
6187
+	 *
6188
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6189
+	 */
6190
+	public function valid_operators()
6191
+	{
6192
+		return $this->_valid_operators;
6193
+	}
6194
+
6195
+
6196
+	/**
6197
+	 * Gets the between-style operators (take 2 arguments).
6198
+	 *
6199
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6200
+	 */
6201
+	public function valid_between_style_operators()
6202
+	{
6203
+		return array_intersect(
6204
+			$this->valid_operators(),
6205
+			$this->_between_style_operators
6206
+		);
6207
+	}
6208
+
6209
+
6210
+	/**
6211
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6212
+	 *
6213
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6214
+	 */
6215
+	public function valid_like_style_operators()
6216
+	{
6217
+		return array_intersect(
6218
+			$this->valid_operators(),
6219
+			$this->_like_style_operators
6220
+		);
6221
+	}
6222
+
6223
+
6224
+	/**
6225
+	 * Gets the "in"-style operators
6226
+	 *
6227
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6228
+	 */
6229
+	public function valid_in_style_operators()
6230
+	{
6231
+		return array_intersect(
6232
+			$this->valid_operators(),
6233
+			$this->_in_style_operators
6234
+		);
6235
+	}
6236
+
6237
+
6238
+	/**
6239
+	 * Gets the "null"-style operators (accept no arguments)
6240
+	 *
6241
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6242
+	 */
6243
+	public function valid_null_style_operators()
6244
+	{
6245
+		return array_intersect(
6246
+			$this->valid_operators(),
6247
+			$this->_null_style_operators
6248
+		);
6249
+	}
6250
+
6251
+
6252
+	/**
6253
+	 * Gets an array where keys are the primary keys and values are their 'names'
6254
+	 * (as determined by the model object's name() function, which is often overridden)
6255
+	 *
6256
+	 * @param array $query_params like get_all's
6257
+	 * @return string[]
6258
+	 * @throws EE_Error
6259
+	 * @throws ReflectionException
6260
+	 */
6261
+	public function get_all_names($query_params = [])
6262
+	{
6263
+		$objs  = $this->get_all($query_params);
6264
+		$names = [];
6265
+		foreach ($objs as $obj) {
6266
+			$names[ $obj->ID() ] = $obj->name();
6267
+		}
6268
+		return $names;
6269
+	}
6270
+
6271
+
6272
+	/**
6273
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6274
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6275
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6276
+	 * array_keys() on $model_objects.
6277
+	 *
6278
+	 * @param \EE_Base_Class[] $model_objects
6279
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6280
+	 *                                               in the returned array
6281
+	 * @return array
6282
+	 * @throws EE_Error
6283
+	 * @throws ReflectionException
6284
+	 */
6285
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6286
+	{
6287
+		if (! $this->has_primary_key_field()) {
6288
+			if (defined('WP_DEBUG') && WP_DEBUG) {
6289
+				EE_Error::add_error(
6290
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6291
+					__FILE__,
6292
+					__FUNCTION__,
6293
+					__LINE__
6294
+				);
6295
+			}
6296
+		}
6297
+		$IDs = [];
6298
+		foreach ($model_objects as $model_object) {
6299
+			$id = $model_object->ID();
6300
+			if (! $id) {
6301
+				if ($filter_out_empty_ids) {
6302
+					continue;
6303
+				}
6304
+				if (defined('WP_DEBUG') && WP_DEBUG) {
6305
+					EE_Error::add_error(
6306
+						esc_html__(
6307
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6308
+							'event_espresso'
6309
+						),
6310
+						__FILE__,
6311
+						__FUNCTION__,
6312
+						__LINE__
6313
+					);
6314
+				}
6315
+			}
6316
+			$IDs[] = $id;
6317
+		}
6318
+		return $IDs;
6319
+	}
6320
+
6321
+
6322
+	/**
6323
+	 * Returns the string used in capabilities relating to this model. If there
6324
+	 * are no capabilities that relate to this model returns false
6325
+	 *
6326
+	 * @return string|false
6327
+	 */
6328
+	public function cap_slug()
6329
+	{
6330
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6331
+	}
6332
+
6333
+
6334
+	/**
6335
+	 * Returns the capability-restrictions array (@param string $context
6336
+	 *
6337
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6338
+	 * @throws EE_Error
6339
+	 * @see EEM_Base::_cap_restrictions).
6340
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6341
+	 *      only returns the cap restrictions array in that context (ie, the array
6342
+	 *      at that key)
6343
+	 */
6344
+	public function cap_restrictions($context = EEM_Base::caps_read)
6345
+	{
6346
+		EEM_Base::verify_is_valid_cap_context($context);
6347
+		// check if we ought to run the restriction generator first
6348
+		if (
6349
+			isset($this->_cap_restriction_generators[ $context ])
6350
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6351
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6352
+		) {
6353
+			$this->_cap_restrictions[ $context ] = array_merge(
6354
+				$this->_cap_restrictions[ $context ],
6355
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6356
+			);
6357
+		}
6358
+		// and make sure we've finalized the construction of each restriction
6359
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6360
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6361
+				$where_conditions_obj->_finalize_construct($this);
6362
+			}
6363
+		}
6364
+		return $this->_cap_restrictions[ $context ];
6365
+	}
6366
+
6367
+
6368
+	/**
6369
+	 * Indicating whether or not this model thinks its a wp core model
6370
+	 *
6371
+	 * @return boolean
6372
+	 */
6373
+	public function is_wp_core_model()
6374
+	{
6375
+		return $this->_wp_core_model;
6376
+	}
6377
+
6378
+
6379
+	/**
6380
+	 * Gets all the caps that are missing which impose a restriction on
6381
+	 * queries made in this context
6382
+	 *
6383
+	 * @param string $context one of EEM_Base::caps_ constants
6384
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6385
+	 * @throws EE_Error
6386
+	 */
6387
+	public function caps_missing($context = EEM_Base::caps_read)
6388
+	{
6389
+		$missing_caps     = [];
6390
+		$cap_restrictions = $this->cap_restrictions($context);
6391
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6392
+			if (
6393
+				! EE_Capabilities::instance()
6394
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6395
+			) {
6396
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6397
+			}
6398
+		}
6399
+		return $missing_caps;
6400
+	}
6401
+
6402
+
6403
+	/**
6404
+	 * Gets the mapping from capability contexts to action strings used in capability names
6405
+	 *
6406
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6407
+	 * one of 'read', 'edit', or 'delete'
6408
+	 */
6409
+	public function cap_contexts_to_cap_action_map()
6410
+	{
6411
+		return apply_filters(
6412
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6413
+			$this->_cap_contexts_to_cap_action_map,
6414
+			$this
6415
+		);
6416
+	}
6417
+
6418
+
6419
+	/**
6420
+	 * Gets the action string for the specified capability context
6421
+	 *
6422
+	 * @param string $context
6423
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6424
+	 * @throws EE_Error
6425
+	 */
6426
+	public function cap_action_for_context($context)
6427
+	{
6428
+		$mapping = $this->cap_contexts_to_cap_action_map();
6429
+		if (isset($mapping[ $context ])) {
6430
+			return $mapping[ $context ];
6431
+		}
6432
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6433
+			return $action;
6434
+		}
6435
+		throw new EE_Error(
6436
+			sprintf(
6437
+				esc_html__(
6438
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6439
+					'event_espresso'
6440
+				),
6441
+				$context,
6442
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6443
+			)
6444
+		);
6445
+	}
6446
+
6447
+
6448
+	/**
6449
+	 * Returns all the capability contexts which are valid when querying models
6450
+	 *
6451
+	 * @return array
6452
+	 */
6453
+	public static function valid_cap_contexts(): array
6454
+	{
6455
+		return (array) apply_filters(
6456
+			'FHEE__EEM_Base__valid_cap_contexts',
6457
+			[
6458
+				self::caps_read,
6459
+				self::caps_read_admin,
6460
+				self::caps_edit,
6461
+				self::caps_delete,
6462
+			]
6463
+		);
6464
+	}
6465
+
6466
+
6467
+	/**
6468
+	 * Returns all valid options for 'default_where_conditions'
6469
+	 *
6470
+	 * @return array
6471
+	 */
6472
+	public static function valid_default_where_conditions(): array
6473
+	{
6474
+		return [
6475
+			EEM_Base::default_where_conditions_all,
6476
+			EEM_Base::default_where_conditions_this_only,
6477
+			EEM_Base::default_where_conditions_others_only,
6478
+			EEM_Base::default_where_conditions_minimum_all,
6479
+			EEM_Base::default_where_conditions_minimum_others,
6480
+			EEM_Base::default_where_conditions_none,
6481
+		];
6482
+	}
6483
+
6484
+	// public static function default_where_conditions_full
6485
+
6486
+
6487
+	/**
6488
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6489
+	 *
6490
+	 * @param string $context
6491
+	 * @return bool
6492
+	 * @throws EE_Error
6493
+	 */
6494
+	public static function verify_is_valid_cap_context($context): bool
6495
+	{
6496
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6497
+		if (in_array($context, $valid_cap_contexts)) {
6498
+			return true;
6499
+		}
6500
+		throw new EE_Error(
6501
+			sprintf(
6502
+				esc_html__(
6503
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6504
+					'event_espresso'
6505
+				),
6506
+				$context,
6507
+				'EEM_Base',
6508
+				implode(',', $valid_cap_contexts)
6509
+			)
6510
+		);
6511
+	}
6512
+
6513
+
6514
+	/**
6515
+	 * Clears all the models field caches. This is only useful when a sub-class
6516
+	 * might have added a field or something and these caches might be invalidated
6517
+	 */
6518
+	protected function _invalidate_field_caches()
6519
+	{
6520
+		$this->_cache_foreign_key_to_fields = [];
6521
+		$this->_cached_fields               = null;
6522
+		$this->_cached_fields_non_db_only   = null;
6523
+	}
6524
+
6525
+
6526
+	/**
6527
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6528
+	 * (eg "and", "or", "not").
6529
+	 *
6530
+	 * @return array
6531
+	 */
6532
+	public function logic_query_param_keys(): array
6533
+	{
6534
+		return $this->_logic_query_param_keys;
6535
+	}
6536
+
6537
+
6538
+	/**
6539
+	 * Determines whether or not the where query param array key is for a logic query param.
6540
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6541
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6542
+	 *
6543
+	 * @param $query_param_key
6544
+	 * @return bool
6545
+	 */
6546
+	public function is_logic_query_param_key($query_param_key): bool
6547
+	{
6548
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6549
+			if (
6550
+				$query_param_key === $logic_query_param_key
6551
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6552
+			) {
6553
+				return true;
6554
+			}
6555
+		}
6556
+		return false;
6557
+	}
6558
+
6559
+
6560
+	/**
6561
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6562
+	 *
6563
+	 * @return boolean
6564
+	 * @since 4.9.74.p
6565
+	 */
6566
+	public function hasPassword(): bool
6567
+	{
6568
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6569
+		if ($this->has_password_field === null) {
6570
+			$password_field           = $this->getPasswordField();
6571
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6572
+		}
6573
+		return $this->has_password_field;
6574
+	}
6575
+
6576
+
6577
+	/**
6578
+	 * Returns the password field on this model, if there is one
6579
+	 *
6580
+	 * @return EE_Password_Field|null
6581
+	 * @since 4.9.74.p
6582
+	 */
6583
+	public function getPasswordField()
6584
+	{
6585
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6586
+		// there's no need to search for it. If we don't know yet, then find out
6587
+		if ($this->has_password_field === null && $this->password_field === null) {
6588
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6589
+		}
6590
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6591
+		return $this->password_field;
6592
+	}
6593
+
6594
+
6595
+	/**
6596
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6597
+	 *
6598
+	 * @return EE_Model_Field_Base[]
6599
+	 * @throws EE_Error
6600
+	 * @since 4.9.74.p
6601
+	 */
6602
+	public function getPasswordProtectedFields()
6603
+	{
6604
+		$password_field = $this->getPasswordField();
6605
+		$fields         = [];
6606
+		if ($password_field instanceof EE_Password_Field) {
6607
+			$field_names = $password_field->protectedFields();
6608
+			foreach ($field_names as $field_name) {
6609
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6610
+			}
6611
+		}
6612
+		return $fields;
6613
+	}
6614
+
6615
+
6616
+	/**
6617
+	 * Checks if the current user can perform the requested action on this model
6618
+	 *
6619
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6620
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6621
+	 * @return bool
6622
+	 * @throws EE_Error
6623
+	 * @throws InvalidArgumentException
6624
+	 * @throws InvalidDataTypeException
6625
+	 * @throws InvalidInterfaceException
6626
+	 * @throws ReflectionException
6627
+	 * @throws UnexpectedEntityException
6628
+	 * @since 4.9.74.p
6629
+	 */
6630
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6631
+	{
6632
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6633
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6634
+		}
6635
+		if (! is_array($model_obj_or_fields_n_values)) {
6636
+			throw new UnexpectedEntityException(
6637
+				$model_obj_or_fields_n_values,
6638
+				'EE_Base_Class',
6639
+				sprintf(
6640
+					esc_html__(
6641
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6642
+						'event_espresso'
6643
+					),
6644
+					__FUNCTION__
6645
+				)
6646
+			);
6647
+		}
6648
+		return $this->exists(
6649
+			$this->alter_query_params_to_restrict_by_ID(
6650
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6651
+				[
6652
+					'default_where_conditions' => 'none',
6653
+					'caps'                     => $cap_to_check,
6654
+				]
6655
+			)
6656
+		);
6657
+	}
6658
+
6659
+
6660
+	/**
6661
+	 * Returns the query param where conditions key to the password affecting this model.
6662
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6663
+	 *
6664
+	 * @return null|string
6665
+	 * @throws EE_Error
6666
+	 * @throws InvalidArgumentException
6667
+	 * @throws InvalidDataTypeException
6668
+	 * @throws InvalidInterfaceException
6669
+	 * @throws ModelConfigurationException
6670
+	 * @throws ReflectionException
6671
+	 * @since 4.9.74.p
6672
+	 */
6673
+	public function modelChainAndPassword()
6674
+	{
6675
+		if ($this->model_chain_to_password === null) {
6676
+			throw new ModelConfigurationException(
6677
+				$this,
6678
+				esc_html_x(
6679
+				// @codingStandardsIgnoreStart
6680
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6681
+					// @codingStandardsIgnoreEnd
6682
+					'1: model name',
6683
+					'event_espresso'
6684
+				)
6685
+			);
6686
+		}
6687
+		if ($this->model_chain_to_password === '') {
6688
+			$model_with_password = $this;
6689
+		} else {
6690
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6691
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6692
+			} else {
6693
+				$last_model_in_chain = $this->model_chain_to_password;
6694
+			}
6695
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6696
+		}
6697
+
6698
+		$password_field = $model_with_password->getPasswordField();
6699
+		if ($password_field instanceof EE_Password_Field) {
6700
+			$password_field_name = $password_field->get_name();
6701
+		} else {
6702
+			throw new ModelConfigurationException(
6703
+				$this,
6704
+				sprintf(
6705
+					esc_html_x(
6706
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6707
+						'1: model name, 2: special string',
6708
+						'event_espresso'
6709
+					),
6710
+					$model_with_password->get_this_model_name(),
6711
+					$this->model_chain_to_password
6712
+				)
6713
+			);
6714
+		}
6715
+		return (
6716
+			   $this->model_chain_to_password
6717
+				   ? $this->model_chain_to_password . '.'
6718
+				   : ''
6719
+			   ) . $password_field_name;
6720
+	}
6721
+
6722
+
6723
+	/**
6724
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6725
+	 * or if this model itself has a password affecting access to some of its other fields.
6726
+	 *
6727
+	 * @return boolean
6728
+	 * @since 4.9.74.p
6729
+	 */
6730
+	public function restrictedByRelatedModelPassword(): bool
6731
+	{
6732
+		return $this->model_chain_to_password !== null;
6733
+	}
6734 6734
 }
Please login to merge, or discard this patch.
Spacing   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = '')
568 568
     {
569 569
         // check that the model has not been loaded too soon
570
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
570
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
571 571
             throw new EE_Error(
572 572
                 sprintf(
573 573
                     esc_html__(
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
          *
591 591
          * @var EE_Table_Base[] $_tables
592 592
          */
593
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
593
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
594 594
         foreach ($this->_tables as $table_alias => $table_obj) {
595 595
             /** @var $table_obj EE_Table_Base */
596 596
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -604,10 +604,10 @@  discard block
 block discarded – undo
604 604
          *
605 605
          * @param EE_Model_Field_Base[] $_fields
606 606
          */
607
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
608 608
         $this->_invalidate_field_caches();
609 609
         foreach ($this->_fields as $table_alias => $fields_for_table) {
610
-            if (! array_key_exists($table_alias, $this->_tables)) {
610
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
611 611
                 throw new EE_Error(
612 612
                     sprintf(
613 613
                         esc_html__(
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
          * @param EE_Model_Relation_Base[] $_model_relations
645 645
          */
646 646
         $this->_model_relations = (array) apply_filters(
647
-            'FHEE__' . get_class($this) . '__construct__model_relations',
647
+            'FHEE__'.get_class($this).'__construct__model_relations',
648 648
             $this->_model_relations
649 649
         );
650 650
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -656,12 +656,12 @@  discard block
 block discarded – undo
656 656
         }
657 657
         $this->set_timezone($timezone);
658 658
         // finalize default where condition strategy, or set default
659
-        if (! $this->_default_where_conditions_strategy) {
659
+        if ( ! $this->_default_where_conditions_strategy) {
660 660
             // nothing was set during child constructor, so set default
661 661
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
662 662
         }
663 663
         $this->_default_where_conditions_strategy->_finalize_construct($this);
664
-        if (! $this->_minimum_where_conditions_strategy) {
664
+        if ( ! $this->_minimum_where_conditions_strategy) {
665 665
             // nothing was set during child constructor, so set default
666 666
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
667 667
         }
@@ -674,8 +674,8 @@  discard block
 block discarded – undo
674 674
         // initialize the standard cap restriction generators if none were specified by the child constructor
675 675
         if (is_array($this->_cap_restriction_generators)) {
676 676
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
677
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
678
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
677
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
678
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
679 679
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
680 680
                         new EE_Restriction_Generator_Protected(),
681 681
                         $cap_context,
@@ -687,10 +687,10 @@  discard block
 block discarded – undo
687 687
         // if there are cap restriction generators, use them to make the default cap restrictions
688 688
         if (is_array($this->_cap_restriction_generators)) {
689 689
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
690
-                if (! $generator_object) {
690
+                if ( ! $generator_object) {
691 691
                     continue;
692 692
                 }
693
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
693
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
694 694
                     throw new EE_Error(
695 695
                         sprintf(
696 696
                             esc_html__(
@@ -703,12 +703,12 @@  discard block
 block discarded – undo
703 703
                     );
704 704
                 }
705 705
                 $action = $this->cap_action_for_context($context);
706
-                if (! $generator_object->construction_finalized()) {
706
+                if ( ! $generator_object->construction_finalized()) {
707 707
                     $generator_object->_construct_finalize($this, $action);
708 708
                 }
709 709
             }
710 710
         }
711
-        do_action('AHEE__' . get_class($this) . '__construct__end');
711
+        do_action('AHEE__'.get_class($this).'__construct__end');
712 712
     }
713 713
 
714 714
 
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
      */
721 721
     protected static function getLoader(): LoaderInterface
722 722
     {
723
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
723
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
724 724
             EEM_Base::$loader = LoaderFactory::getLoader();
725 725
         }
726 726
         return EEM_Base::$loader;
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
      */
734 734
     private static function getMirror(): Mirror
735 735
     {
736
-        if (! EEM_Base::$mirror instanceof Mirror) {
736
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
737 737
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
738 738
         }
739 739
         return EEM_Base::$mirror;
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
     public static function instance($timezone = '')
790 790
     {
791 791
         // check if instance of Espresso_model already exists
792
-        if (! static::$_instance instanceof static) {
792
+        if ( ! static::$_instance instanceof static) {
793 793
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
794 794
             $model     = new static(...$arguments);
795 795
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
      */
819 819
     public static function reset($timezone = '')
820 820
     {
821
-        if (! static::$_instance instanceof EEM_Base) {
821
+        if ( ! static::$_instance instanceof EEM_Base) {
822 822
             return null;
823 823
         }
824 824
         // Let's NOT swap out the current instance for a new one
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
830 830
             // don't set instance to null like it was originally,
831 831
             // but it's static anyways, and we're ignoring static properties (for now at least)
832
-            if (! isset($static_properties[ $property ])) {
832
+            if ( ! isset($static_properties[$property])) {
833 833
                 static::$_instance->{$property} = $value;
834 834
             }
835 835
         }
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
      */
879 879
     public function status_array($translated = false)
880 880
     {
881
-        if (! array_key_exists('Status', $this->_model_relations)) {
881
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
882 882
             return [];
883 883
         }
884 884
         $model_name   = $this->get_this_model_name();
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
887 887
         $status_array = [];
888 888
         foreach ($stati as $status) {
889
-            $status_array[ $status->ID() ] = $status->get('STS_code');
889
+            $status_array[$status->ID()] = $status->get('STS_code');
890 890
         }
891 891
         return $translated
892 892
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
     {
952 952
         $wp_user_field_name = $this->wp_user_field_name();
953 953
         if ($wp_user_field_name) {
954
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
954
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
955 955
         }
956 956
         return $query_params;
957 957
     }
@@ -970,17 +970,17 @@  discard block
 block discarded – undo
970 970
     public function wp_user_field_name()
971 971
     {
972 972
         try {
973
-            if (! empty($this->_model_chain_to_wp_user)) {
973
+            if ( ! empty($this->_model_chain_to_wp_user)) {
974 974
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
975 975
                 $last_model_name              = end($models_to_follow_to_wp_users);
976 976
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
977
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
977
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
978 978
             } else {
979 979
                 $model_with_fk_to_wp_users = $this;
980 980
                 $model_chain_to_wp_user    = '';
981 981
             }
982 982
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
983
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
983
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
984 984
         } catch (EE_Error $e) {
985 985
             return false;
986 986
         }
@@ -1056,11 +1056,11 @@  discard block
 block discarded – undo
1056 1056
         if ($this->_custom_selections instanceof CustomSelects) {
1057 1057
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1058 1058
             $select_expressions .= $select_expressions
1059
-                ? ', ' . $custom_expressions
1059
+                ? ', '.$custom_expressions
1060 1060
                 : $custom_expressions;
1061 1061
         }
1062 1062
 
1063
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1063
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1064 1064
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1065 1065
     }
1066 1066
 
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
      */
1078 1078
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1079 1079
     {
1080
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1080
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1081 1081
             return null;
1082 1082
         }
1083 1083
         $selects = $query_params['extra_selects'] ?? $columns_to_select;
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
         if (is_array($columns_to_select)) {
1129 1129
             $select_sql_array = [];
1130 1130
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1131
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1131
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132 1132
                     throw new EE_Error(
1133 1133
                         sprintf(
1134 1134
                             esc_html__(
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
                         )
1141 1141
                     );
1142 1142
                 }
1143
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1143
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1144 1144
                     throw new EE_Error(
1145 1145
                         sprintf(
1146 1146
                             esc_html__(
@@ -1202,7 +1202,7 @@  discard block
 block discarded – undo
1202 1202
                 ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1203 1203
             )
1204 1204
         );
1205
-        $className    = $this->_get_class_name();
1205
+        $className = $this->_get_class_name();
1206 1206
         if ($model_object instanceof $className) {
1207 1207
             // make sure valid objects get added to the entity map
1208 1208
             // so that the next call to this method doesn't trigger another trip to the db
@@ -1225,12 +1225,12 @@  discard block
 block discarded – undo
1225 1225
      */
1226 1226
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1227 1227
     {
1228
-        if (! isset($query_params[0])) {
1228
+        if ( ! isset($query_params[0])) {
1229 1229
             $query_params[0] = [];
1230 1230
         }
1231 1231
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1232 1232
         if ($conditions_from_id === null) {
1233
-            $query_params[0][ $this->primary_key_name() ] = $id;
1233
+            $query_params[0][$this->primary_key_name()] = $id;
1234 1234
         } else {
1235 1235
             // no primary key, so the $id must be from the get_index_primary_key_string()
1236 1236
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1250,7 +1250,7 @@  discard block
 block discarded – undo
1250 1250
      */
1251 1251
     public function get_one($query_params = [])
1252 1252
     {
1253
-        if (! is_array($query_params)) {
1253
+        if ( ! is_array($query_params)) {
1254 1254
             EE_Error::doing_it_wrong(
1255 1255
                 'EEM_Base::get_one',
1256 1256
                 sprintf(
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
                 return [];
1460 1460
             }
1461 1461
         }
1462
-        if (! is_array($query_params)) {
1462
+        if ( ! is_array($query_params)) {
1463 1463
             EE_Error::doing_it_wrong(
1464 1464
                 'EEM_Base::_get_consecutive',
1465 1465
                 sprintf(
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
             $query_params = [];
1472 1472
         }
1473 1473
         // let's add the where query param for consecutive look up.
1474
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1474
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1475 1475
         $query_params['limit']                 = $limit;
1476 1476
         // set direction
1477 1477
         $incoming_orderby         = isset($query_params['order_by'])
@@ -1497,7 +1497,7 @@  discard block
 block discarded – undo
1497 1497
      */
1498 1498
     public function set_timezone(?string $timezone = '')
1499 1499
     {
1500
-        if (! $timezone) {
1500
+        if ( ! $timezone) {
1501 1501
             return;
1502 1502
         }
1503 1503
         $this->_timezone = $timezone;
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
     {
1555 1555
         $field_settings = $this->field_settings_for($field_name);
1556 1556
         // if not a valid EE_Datetime_Field then throw error
1557
-        if (! $field_settings instanceof EE_Datetime_Field) {
1557
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1558 1558
             throw new EE_Error(
1559 1559
                 sprintf(
1560 1560
                     esc_html__(
@@ -1641,7 +1641,7 @@  discard block
 block discarded – undo
1641 1641
         // just using this to ensure the timezone is set correctly internally
1642 1642
         $this->get_formats_for($field_name);
1643 1643
         // load EEH_DTT_Helper
1644
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1644
+        $timezone_string = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1645 1645
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1646 1646
         EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1647 1647
         return DbSafeDateTime::createFromDateTime($incomingDateTime);
@@ -1711,7 +1711,7 @@  discard block
 block discarded – undo
1711 1711
      */
1712 1712
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1713 1713
     {
1714
-        if (! is_array($query_params)) {
1714
+        if ( ! is_array($query_params)) {
1715 1715
             EE_Error::doing_it_wrong(
1716 1716
                 'EEM_Base::update',
1717 1717
                 sprintf(
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
             $wpdb_result = (array) $wpdb_result;
1760 1760
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1761 1761
             if ($this->has_primary_key_field()) {
1762
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1762
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1763 1763
             } else {
1764 1764
                 // 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)
1765 1765
                 $main_table_pk_value = null;
@@ -1775,7 +1775,7 @@  discard block
 block discarded – undo
1775 1775
                     // in this table, right? so insert a row in the current table, using any fields available
1776 1776
                     if (
1777 1777
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1778
-                           && $wpdb_result[ $this_table_pk_column ])
1778
+                           && $wpdb_result[$this_table_pk_column])
1779 1779
                     ) {
1780 1780
                         $success = $this->_insert_into_specific_table(
1781 1781
                             $table_obj,
@@ -1783,7 +1783,7 @@  discard block
 block discarded – undo
1783 1783
                             $main_table_pk_value
1784 1784
                         );
1785 1785
                         // if we died here, report the error
1786
-                        if (! $success) {
1786
+                        if ( ! $success) {
1787 1787
                             return false;
1788 1788
                         }
1789 1789
                     }
@@ -1811,10 +1811,10 @@  discard block
 block discarded – undo
1811 1811
                 $model_objs_affected_ids     = [];
1812 1812
                 foreach ($models_affected_key_columns as $row) {
1813 1813
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1814
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1814
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1815 1815
                 }
1816 1816
             }
1817
-            if (! $model_objs_affected_ids) {
1817
+            if ( ! $model_objs_affected_ids) {
1818 1818
                 // wait wait wait- if nothing was affected let's stop here
1819 1819
                 return 0;
1820 1820
             }
@@ -1843,8 +1843,8 @@  discard block
 block discarded – undo
1843 1843
         $rows_affected = $this->_do_wpdb_query(
1844 1844
             'query',
1845 1845
             [
1846
-                "UPDATE " . $model_query_info->get_full_join_sql()
1847
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1846
+                "UPDATE ".$model_query_info->get_full_join_sql()
1847
+                . " SET ".$this->_construct_update_sql($fields_n_values)
1848 1848
                 . $model_query_info->get_where_sql(),
1849 1849
             ]
1850 1850
         );
@@ -1858,7 +1858,7 @@  discard block
 block discarded – undo
1858 1858
          * @param int      $rows_affected
1859 1859
          */
1860 1860
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1861
-        return $rows_affected;// how many supposedly got updated
1861
+        return $rows_affected; // how many supposedly got updated
1862 1862
     }
1863 1863
 
1864 1864
 
@@ -1891,7 +1891,7 @@  discard block
 block discarded – undo
1891 1891
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1892 1892
         $select_expressions = $field->get_qualified_column();
1893 1893
         $SQL                =
1894
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1894
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1895 1895
         return $this->_do_wpdb_query('get_col', [$SQL]);
1896 1896
     }
1897 1897
 
@@ -1910,7 +1910,7 @@  discard block
 block discarded – undo
1910 1910
     {
1911 1911
         $query_params['limit'] = 1;
1912 1912
         $col                   = $this->get_col($query_params, $field_to_select);
1913
-        if (! empty($col)) {
1913
+        if ( ! empty($col)) {
1914 1914
             return reset($col);
1915 1915
         }
1916 1916
         return null;
@@ -1941,7 +1941,7 @@  discard block
 block discarded – undo
1941 1941
             $value_sql       = $prepared_value === null
1942 1942
                 ? 'NULL'
1943 1943
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1944
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1944
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1945 1945
         }
1946 1946
         return implode(",", $cols_n_values);
1947 1947
     }
@@ -2079,7 +2079,7 @@  discard block
 block discarded – undo
2079 2079
                                 . $model_query_info->get_full_join_sql()
2080 2080
                                 . " WHERE "
2081 2081
                                 . $deletion_where_query_part;
2082
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2082
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
2083 2083
         }
2084 2084
 
2085 2085
         // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
@@ -2087,12 +2087,12 @@  discard block
 block discarded – undo
2087 2087
         if (
2088 2088
             $this->has_primary_key_field()
2089 2089
             && $rows_deleted !== false
2090
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2090
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2091 2091
         ) {
2092
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2092
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2093 2093
             foreach ($ids_for_removal as $id) {
2094
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2095
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2094
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2095
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2096 2096
                 }
2097 2097
             }
2098 2098
 
@@ -2132,7 +2132,7 @@  discard block
 block discarded – undo
2132 2132
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2133 2133
          */
2134 2134
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2135
-        return (int) $rows_deleted;// how many supposedly got deleted
2135
+        return (int) $rows_deleted; // how many supposedly got deleted
2136 2136
     }
2137 2137
 
2138 2138
 
@@ -2236,15 +2236,15 @@  discard block
 block discarded – undo
2236 2236
                 if (
2237 2237
                     $block_deletes
2238 2238
                     && $this->delete_is_blocked_by_related_models(
2239
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2239
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2240 2240
                     )
2241 2241
                 ) {
2242 2242
                     continue;
2243 2243
                 }
2244 2244
                 // primary table deletes
2245
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2246
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2247
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2245
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2246
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2247
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2248 2248
                 }
2249 2249
             }
2250 2250
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2253,8 +2253,8 @@  discard block
 block discarded – undo
2253 2253
                 $ids_to_delete_indexed_by_column_for_row = [];
2254 2254
                 foreach ($fields as $cpk_field) {
2255 2255
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2256
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2257
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2256
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2257
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2258 2258
                     }
2259 2259
                 }
2260 2260
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2292,7 +2292,7 @@  discard block
 block discarded – undo
2292 2292
         } elseif ($this->has_primary_key_field()) {
2293 2293
             $query = [];
2294 2294
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2295
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2295
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2296 2296
             }
2297 2297
             $query_part = ! empty($query)
2298 2298
                 ? implode(' AND ', $query)
@@ -2302,7 +2302,7 @@  discard block
 block discarded – undo
2302 2302
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2303 2303
                 $values_for_each_combined_primary_key_for_a_row = [];
2304 2304
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2305
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2305
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2306 2306
                 }
2307 2307
                 $ways_to_identify_a_row[] = '('
2308 2308
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2378,10 +2378,10 @@  discard block
 block discarded – undo
2378 2378
             }
2379 2379
         }
2380 2380
         $column_to_count = $distinct
2381
-            ? "DISTINCT " . $column_to_count
2381
+            ? "DISTINCT ".$column_to_count
2382 2382
             : $column_to_count;
2383 2383
         $SQL             =
2384
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2384
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2385 2385
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2386 2386
     }
2387 2387
 
@@ -2406,7 +2406,7 @@  discard block
 block discarded – undo
2406 2406
         }
2407 2407
         $column_to_count = $field_obj->get_qualified_column();
2408 2408
         $SQL             =
2409
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2409
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2410 2410
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2411 2411
         $data_type       = $field_obj->get_wpdb_data_type();
2412 2412
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2442,7 +2442,7 @@  discard block
 block discarded – undo
2442 2442
         }
2443 2443
         /** @type WPDB $wpdb */
2444 2444
         global $wpdb;
2445
-        if (! method_exists($wpdb, $wpdb_method)) {
2445
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2446 2446
             throw new DomainException(
2447 2447
                 sprintf(
2448 2448
                     esc_html__(
@@ -2461,7 +2461,7 @@  discard block
 block discarded – undo
2461 2461
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2462 2462
         if (defined('WP_DEBUG') && WP_DEBUG) {
2463 2463
             $wpdb->show_errors($old_show_errors_value);
2464
-            if (! empty($wpdb->last_error)) {
2464
+            if ( ! empty($wpdb->last_error)) {
2465 2465
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2466 2466
             }
2467 2467
             if ($result === false) {
@@ -2531,7 +2531,7 @@  discard block
 block discarded – undo
2531 2531
                     // ummmm... you in trouble
2532 2532
                     return $result;
2533 2533
             }
2534
-            if (! empty($error_message)) {
2534
+            if ( ! empty($error_message)) {
2535 2535
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2536 2536
                 trigger_error($error_message);
2537 2537
             }
@@ -2612,11 +2612,11 @@  discard block
 block discarded – undo
2612 2612
      */
2613 2613
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2614 2614
     {
2615
-        return " FROM " . $model_query_info->get_full_join_sql() .
2616
-               $model_query_info->get_where_sql() .
2617
-               $model_query_info->get_group_by_sql() .
2618
-               $model_query_info->get_having_sql() .
2619
-               $model_query_info->get_order_by_sql() .
2615
+        return " FROM ".$model_query_info->get_full_join_sql().
2616
+               $model_query_info->get_where_sql().
2617
+               $model_query_info->get_group_by_sql().
2618
+               $model_query_info->get_having_sql().
2619
+               $model_query_info->get_order_by_sql().
2620 2620
                $model_query_info->get_limit_sql();
2621 2621
     }
2622 2622
 
@@ -2641,7 +2641,7 @@  discard block
 block discarded – undo
2641 2641
             $left = is_admin() ? '12rem' : '2rem';
2642 2642
             echo "
2643 2643
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2644
-                " . esc_html($sql_query) . "
2644
+                ".esc_html($sql_query)."
2645 2645
             </div>";
2646 2646
             $this->_show_next_x_db_queries--;
2647 2647
         }
@@ -2817,12 +2817,12 @@  discard block
 block discarded – undo
2817 2817
         $related_model = $this->get_related_model_obj($model_name);
2818 2818
         // we're just going to use the query params on the related model's normal get_all query,
2819 2819
         // except add a condition to say to match the current mod
2820
-        if (! isset($query_params['default_where_conditions'])) {
2820
+        if ( ! isset($query_params['default_where_conditions'])) {
2821 2821
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2822 2822
         }
2823 2823
         $this_model_name                                                 = $this->get_this_model_name();
2824 2824
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2825
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2825
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2826 2826
         return $related_model->count($query_params, $field_to_count, $distinct);
2827 2827
     }
2828 2828
 
@@ -2843,7 +2843,7 @@  discard block
 block discarded – undo
2843 2843
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2844 2844
     {
2845 2845
         $related_model = $this->get_related_model_obj($model_name);
2846
-        if (! is_array($query_params)) {
2846
+        if ( ! is_array($query_params)) {
2847 2847
             EE_Error::doing_it_wrong(
2848 2848
                 'EEM_Base::sum_related',
2849 2849
                 sprintf(
@@ -2856,12 +2856,12 @@  discard block
 block discarded – undo
2856 2856
         }
2857 2857
         // we're just going to use the query params on the related model's normal get_all query,
2858 2858
         // except add a condition to say to match the current mod
2859
-        if (! isset($query_params['default_where_conditions'])) {
2859
+        if ( ! isset($query_params['default_where_conditions'])) {
2860 2860
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2861 2861
         }
2862 2862
         $this_model_name                                                 = $this->get_this_model_name();
2863 2863
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2864
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2864
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2865 2865
         return $related_model->sum($query_params, $field_to_sum);
2866 2866
     }
2867 2867
 
@@ -2913,7 +2913,7 @@  discard block
 block discarded – undo
2913 2913
                 $field_with_model_name = $field;
2914 2914
             }
2915 2915
         }
2916
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2916
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2917 2917
             throw new EE_Error(
2918 2918
                 sprintf(
2919 2919
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -3052,14 +3052,14 @@  discard block
 block discarded – undo
3052 3052
                 || $this->get_primary_key_field()
3053 3053
                    instanceof
3054 3054
                    EE_Primary_Key_String_Field)
3055
-            && isset($fields_n_values[ $this->primary_key_name() ])
3055
+            && isset($fields_n_values[$this->primary_key_name()])
3056 3056
         ) {
3057
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3057
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
3058 3058
         }
3059 3059
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3060 3060
             $uniqueness_where_params                              =
3061 3061
                 array_intersect_key($fields_n_values, $unique_index->fields());
3062
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3062
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
3063 3063
         }
3064 3064
         // if there is nothing to base this search on, then we shouldn't find anything
3065 3065
         if (empty($query_params)) {
@@ -3136,16 +3136,16 @@  discard block
 block discarded – undo
3136 3136
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3137 3137
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3138 3138
             if ($prepared_value !== null) {
3139
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3139
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3140 3140
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3141 3141
             }
3142 3142
         }
3143 3143
         if ($table instanceof EE_Secondary_Table && $new_id) {
3144 3144
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3145 3145
             // so add the fk to the main table as a column
3146
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3146
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3147 3147
             $format_for_insertion[]                              =
3148
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3148
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3149 3149
         }
3150 3150
 
3151 3151
         // insert the new entry
@@ -3163,7 +3163,7 @@  discard block
 block discarded – undo
3163 3163
             }
3164 3164
             // it's not an auto-increment primary key, so
3165 3165
             // it must have been supplied
3166
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3166
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3167 3167
         }
3168 3168
         // we can't return a  primary key because there is none. instead return
3169 3169
         // a unique string indicating this model
@@ -3185,10 +3185,10 @@  discard block
 block discarded – undo
3185 3185
     {
3186 3186
         $field_name = $field_obj->get_name();
3187 3187
         // if this field doesn't allow nullable, don't allow it
3188
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3189
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3188
+        if ( ! $field_obj->is_nullable() && ! isset($fields_n_values[$field_name])) {
3189
+            $fields_n_values[$field_name] = $field_obj->get_default_value();
3190 3190
         }
3191
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3191
+        $unprepared_value = $fields_n_values[$field_name] ?? null;
3192 3192
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3193 3193
     }
3194 3194
 
@@ -3291,7 +3291,7 @@  discard block
 block discarded – undo
3291 3291
      */
3292 3292
     public function get_table_obj_by_alias($table_alias = '')
3293 3293
     {
3294
-        return $this->_tables[ $table_alias ] ?? null;
3294
+        return $this->_tables[$table_alias] ?? null;
3295 3295
     }
3296 3296
 
3297 3297
 
@@ -3305,7 +3305,7 @@  discard block
 block discarded – undo
3305 3305
         $other_tables = [];
3306 3306
         foreach ($this->_tables as $table_alias => $table) {
3307 3307
             if ($table instanceof EE_Secondary_Table) {
3308
-                $other_tables[ $table_alias ] = $table;
3308
+                $other_tables[$table_alias] = $table;
3309 3309
             }
3310 3310
         }
3311 3311
         return $other_tables;
@@ -3320,7 +3320,7 @@  discard block
 block discarded – undo
3320 3320
      */
3321 3321
     public function _get_fields_for_table($table_alias)
3322 3322
     {
3323
-        return $this->_fields[ $table_alias ];
3323
+        return $this->_fields[$table_alias];
3324 3324
     }
3325 3325
 
3326 3326
 
@@ -3349,7 +3349,7 @@  discard block
 block discarded – undo
3349 3349
                     $query_info_carrier,
3350 3350
                     'group_by'
3351 3351
                 );
3352
-            } elseif (! empty($query_params['group_by'])) {
3352
+            } elseif ( ! empty($query_params['group_by'])) {
3353 3353
                 $this->_extract_related_model_info_from_query_param(
3354 3354
                     $query_params['group_by'],
3355 3355
                     $query_info_carrier,
@@ -3371,7 +3371,7 @@  discard block
 block discarded – undo
3371 3371
                     $query_info_carrier,
3372 3372
                     'order_by'
3373 3373
                 );
3374
-            } elseif (! empty($query_params['order_by'])) {
3374
+            } elseif ( ! empty($query_params['order_by'])) {
3375 3375
                 $this->_extract_related_model_info_from_query_param(
3376 3376
                     $query_params['order_by'],
3377 3377
                     $query_info_carrier,
@@ -3406,7 +3406,7 @@  discard block
 block discarded – undo
3406 3406
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3407 3407
         $query_param_type
3408 3408
     ) {
3409
-        if (! empty($sub_query_params)) {
3409
+        if ( ! empty($sub_query_params)) {
3410 3410
             $sub_query_params = (array) $sub_query_params;
3411 3411
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3412 3412
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3422,7 +3422,7 @@  discard block
 block discarded – undo
3422 3422
                 $query_param_sans_stars =
3423 3423
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3424 3424
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3425
-                    if (! is_array($possibly_array_of_params)) {
3425
+                    if ( ! is_array($possibly_array_of_params)) {
3426 3426
                         throw new EE_Error(
3427 3427
                             sprintf(
3428 3428
                                 esc_html__(
@@ -3448,7 +3448,7 @@  discard block
 block discarded – undo
3448 3448
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3449 3449
                     // indicating that $possible_array_of_params[1] is actually a field name,
3450 3450
                     // from which we should extract query parameters!
3451
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3451
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3452 3452
                         throw new EE_Error(
3453 3453
                             sprintf(
3454 3454
                                 esc_html__(
@@ -3488,8 +3488,8 @@  discard block
 block discarded – undo
3488 3488
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3489 3489
         $query_param_type
3490 3490
     ) {
3491
-        if (! empty($sub_query_params)) {
3492
-            if (! is_array($sub_query_params)) {
3491
+        if ( ! empty($sub_query_params)) {
3492
+            if ( ! is_array($sub_query_params)) {
3493 3493
                 throw new EE_Error(
3494 3494
                     sprintf(
3495 3495
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3527,7 +3527,7 @@  discard block
 block discarded – undo
3527 3527
      */
3528 3528
     public function _create_model_query_info_carrier($query_params)
3529 3529
     {
3530
-        if (! is_array($query_params)) {
3530
+        if ( ! is_array($query_params)) {
3531 3531
             EE_Error::doing_it_wrong(
3532 3532
                 'EEM_Base::_create_model_query_info_carrier',
3533 3533
                 sprintf(
@@ -3558,7 +3558,7 @@  discard block
 block discarded – undo
3558 3558
             // only include if related to a cpt where no password has been set
3559 3559
             $query_params[0]['OR*nopassword'] = [
3560 3560
                 $where_param_key_for_password       => '',
3561
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3561
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3562 3562
             ];
3563 3563
         }
3564 3564
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3612,7 +3612,7 @@  discard block
 block discarded – undo
3612 3612
         // set limit
3613 3613
         if (array_key_exists('limit', $query_params)) {
3614 3614
             if (is_array($query_params['limit'])) {
3615
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3615
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3616 3616
                     $e = sprintf(
3617 3617
                         esc_html__(
3618 3618
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3620,12 +3620,12 @@  discard block
 block discarded – undo
3620 3620
                         ),
3621 3621
                         http_build_query($query_params['limit'])
3622 3622
                     );
3623
-                    throw new EE_Error($e . "|" . $e);
3623
+                    throw new EE_Error($e."|".$e);
3624 3624
                 }
3625 3625
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3626
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3627
-            } elseif (! empty($query_params['limit'])) {
3628
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3626
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3627
+            } elseif ( ! empty($query_params['limit'])) {
3628
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3629 3629
             }
3630 3630
         }
3631 3631
         // set order by
@@ -3657,10 +3657,10 @@  discard block
 block discarded – undo
3657 3657
                 $order_array = [];
3658 3658
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3659 3659
                     $order         = $this->_extract_order($order);
3660
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3660
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3661 3661
                 }
3662
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3663
-            } elseif (! empty($query_params['order_by'])) {
3662
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3663
+            } elseif ( ! empty($query_params['order_by'])) {
3664 3664
                 $this->_extract_related_model_info_from_query_param(
3665 3665
                     $query_params['order_by'],
3666 3666
                     $query_object,
@@ -3671,7 +3671,7 @@  discard block
 block discarded – undo
3671 3671
                     ? $this->_extract_order($query_params['order'])
3672 3672
                     : 'DESC';
3673 3673
                 $query_object->set_order_by_sql(
3674
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3674
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3675 3675
                 );
3676 3676
             }
3677 3677
         }
@@ -3683,7 +3683,7 @@  discard block
 block discarded – undo
3683 3683
         ) {
3684 3684
             $pk_field = $this->get_primary_key_field();
3685 3685
             $order    = $this->_extract_order($query_params['order']);
3686
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3686
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3687 3687
         }
3688 3688
         // set group by
3689 3689
         if (array_key_exists('group_by', $query_params)) {
@@ -3693,10 +3693,10 @@  discard block
 block discarded – undo
3693 3693
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3694 3694
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3695 3695
                 }
3696
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3697
-            } elseif (! empty($query_params['group_by'])) {
3696
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3697
+            } elseif ( ! empty($query_params['group_by'])) {
3698 3698
                 $query_object->set_group_by_sql(
3699
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3699
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3700 3700
                 );
3701 3701
             }
3702 3702
         }
@@ -3706,7 +3706,7 @@  discard block
 block discarded – undo
3706 3706
         }
3707 3707
         // now, just verify they didn't pass anything wack
3708 3708
         foreach ($query_params as $query_key => $query_value) {
3709
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3709
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3710 3710
                 throw new EE_Error(
3711 3711
                     sprintf(
3712 3712
                         esc_html__(
@@ -3811,7 +3811,7 @@  discard block
 block discarded – undo
3811 3811
         $where_query_params = []
3812 3812
     ) {
3813 3813
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3814
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3814
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3815 3815
             throw new EE_Error(
3816 3816
                 sprintf(
3817 3817
                     esc_html__(
@@ -3841,7 +3841,7 @@  discard block
 block discarded – undo
3841 3841
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3842 3842
                 continue;
3843 3843
             }
3844
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3844
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3845 3845
                 $related_model_universal_where_params,
3846 3846
                 $where_query_params,
3847 3847
                 $related_model,
@@ -3950,19 +3950,19 @@  discard block
 block discarded – undo
3950 3950
     ) {
3951 3951
         $null_friendly_where_conditions = [];
3952 3952
         $none_overridden                = true;
3953
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3953
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3954 3954
         foreach ($default_where_conditions as $key => $val) {
3955
-            if (isset($provided_where_conditions[ $key ])) {
3955
+            if (isset($provided_where_conditions[$key])) {
3956 3956
                 $none_overridden = false;
3957 3957
             } else {
3958
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3958
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3959 3959
             }
3960 3960
         }
3961 3961
         if ($none_overridden && $default_where_conditions) {
3962 3962
             if ($model->has_primary_key_field()) {
3963
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3963
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3964 3964
                                                                                    . "."
3965
-                                                                                   . $model->primary_key_name() ] =
3965
+                                                                                   . $model->primary_key_name()] =
3966 3966
                     ['IS NULL'];
3967 3967
             }/*else{
3968 3968
                 //@todo NO PK, use other defaults
@@ -4073,7 +4073,7 @@  discard block
 block discarded – undo
4073 4073
             foreach ($tables as $table_obj) {
4074 4074
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4075 4075
                                        . $table_obj->get_fully_qualified_pk_column();
4076
-                if (! in_array($qualified_pk_column, $selects)) {
4076
+                if ( ! in_array($qualified_pk_column, $selects)) {
4077 4077
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4078 4078
                 }
4079 4079
             }
@@ -4225,9 +4225,9 @@  discard block
 block discarded – undo
4225 4225
         $query_parameter_type
4226 4226
     ) {
4227 4227
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4228
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4228
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4229 4229
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4230
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4230
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4231 4231
                 if ($possible_join_string === '') {
4232 4232
                     // nothing left to $query_param
4233 4233
                     // we should actually end in a field name, not a model like this!
@@ -4360,7 +4360,7 @@  discard block
 block discarded – undo
4360 4360
     {
4361 4361
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4362 4362
         if ($SQL) {
4363
-            return " WHERE " . $SQL;
4363
+            return " WHERE ".$SQL;
4364 4364
         }
4365 4365
         return '';
4366 4366
     }
@@ -4378,7 +4378,7 @@  discard block
 block discarded – undo
4378 4378
     {
4379 4379
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4380 4380
         if ($SQL) {
4381
-            return " HAVING " . $SQL;
4381
+            return " HAVING ".$SQL;
4382 4382
         }
4383 4383
         return '';
4384 4384
     }
@@ -4432,7 +4432,7 @@  discard block
 block discarded – undo
4432 4432
             } else {
4433 4433
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4434 4434
                 // if it's not a normal field, maybe it's a custom selection?
4435
-                if (! $field_obj) {
4435
+                if ( ! $field_obj) {
4436 4436
                     if ($this->_custom_selections instanceof CustomSelects) {
4437 4437
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4438 4438
                     } else {
@@ -4448,7 +4448,7 @@  discard block
 block discarded – undo
4448 4448
                     }
4449 4449
                 }
4450 4450
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4451
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4451
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4452 4452
             }
4453 4453
         }
4454 4454
         return $where_clauses
@@ -4472,7 +4472,7 @@  discard block
 block discarded – undo
4472 4472
                 $field->get_model_name(),
4473 4473
                 $query_param
4474 4474
             );
4475
-            return $table_alias_prefix . $field->get_qualified_column();
4475
+            return $table_alias_prefix.$field->get_qualified_column();
4476 4476
         }
4477 4477
         if (
4478 4478
             $this->_custom_selections instanceof CustomSelects
@@ -4533,10 +4533,10 @@  discard block
 block discarded – undo
4533 4533
             $operator = isset($op_and_value[0])
4534 4534
                 ? $this->_prepare_operator_for_sql($op_and_value[0])
4535 4535
                 : null;
4536
-            if (! $operator) {
4536
+            if ( ! $operator) {
4537 4537
                 $php_array_like_string = [];
4538 4538
                 foreach ($op_and_value as $key => $value) {
4539
-                    $value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4539
+                    $value = is_array($value) ? '['.implode(",", $value).']' : $value;
4540 4540
                     $php_array_like_string[] = "$key=>$value";
4541 4541
                 }
4542 4542
                 throw new EE_Error(
@@ -4554,14 +4554,14 @@  discard block
 block discarded – undo
4554 4554
 
4555 4555
         // check to see if the value is actually another field
4556 4556
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4557
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4557
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4558 4558
         }
4559 4559
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4560 4560
             // in this case, the value should be an array, or at least a comma-separated list
4561 4561
             // it will need to handle a little differently
4562 4562
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4563 4563
             // note: $cleaned_value has already been run through $wpdb->prepare()
4564
-            return $operator . SP . $cleaned_value;
4564
+            return $operator.SP.$cleaned_value;
4565 4565
         }
4566 4566
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4567 4567
             // the value should be an array with count of two.
@@ -4577,7 +4577,7 @@  discard block
 block discarded – undo
4577 4577
                 );
4578 4578
             }
4579 4579
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4580
-            return $operator . SP . $cleaned_value;
4580
+            return $operator.SP.$cleaned_value;
4581 4581
         }
4582 4582
         if (in_array($operator, $this->valid_null_style_operators())) {
4583 4583
             if ($value !== null) {
@@ -4597,10 +4597,10 @@  discard block
 block discarded – undo
4597 4597
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4598 4598
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4599 4599
             // remove other junk. So just treat it as a string.
4600
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4600
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4601 4601
         }
4602
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4603
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4602
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4603
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4604 4604
         }
4605 4605
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4606 4606
             throw new EE_Error(
@@ -4614,7 +4614,7 @@  discard block
 block discarded – undo
4614 4614
                 )
4615 4615
             );
4616 4616
         }
4617
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4617
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4618 4618
             throw new EE_Error(
4619 4619
                 sprintf(
4620 4620
                     esc_html__(
@@ -4653,7 +4653,7 @@  discard block
 block discarded – undo
4653 4653
         foreach ($values as $value) {
4654 4654
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4655 4655
         }
4656
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4656
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4657 4657
     }
4658 4658
 
4659 4659
 
@@ -4691,7 +4691,7 @@  discard block
 block discarded – undo
4691 4691
             $main_table  = $this->_get_main_table();
4692 4692
             $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4693 4693
         }
4694
-        return '(' . implode(',', $prepped) . ')';
4694
+        return '('.implode(',', $prepped).')';
4695 4695
     }
4696 4696
 
4697 4697
 
@@ -4711,7 +4711,7 @@  discard block
 block discarded – undo
4711 4711
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4712 4712
             );
4713 4713
         } //$field_obj should really just be a data type
4714
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4714
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4715 4715
             throw new EE_Error(
4716 4716
                 sprintf(
4717 4717
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4748,14 +4748,14 @@  discard block
 block discarded – undo
4748 4748
             );
4749 4749
         }
4750 4750
         $number_of_parts       = count($query_param_parts);
4751
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4751
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4752 4752
         if ($number_of_parts === 1) {
4753 4753
             $field_name = $last_query_param_part;
4754 4754
             $model_obj  = $this;
4755 4755
         } else {// $number_of_parts >= 2
4756 4756
             // the last part is the column name, and there are only 2parts. therefore...
4757 4757
             $field_name = $last_query_param_part;
4758
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4758
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4759 4759
         }
4760 4760
         try {
4761 4761
             return $model_obj->field_settings_for($field_name);
@@ -4776,7 +4776,7 @@  discard block
 block discarded – undo
4776 4776
     public function _get_qualified_column_for_field($field_name)
4777 4777
     {
4778 4778
         $all_fields = $this->field_settings();
4779
-        $field      = $all_fields[ $field_name ] ?? false;
4779
+        $field      = $all_fields[$field_name] ?? false;
4780 4780
         if ($field) {
4781 4781
             return $field->get_qualified_column();
4782 4782
         }
@@ -4846,12 +4846,12 @@  discard block
 block discarded – undo
4846 4846
      */
4847 4847
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4848 4848
     {
4849
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4849
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain)
4850 4850
                 ? ''
4851 4851
                 : '__');
4852 4852
         $qualified_columns = [];
4853 4853
         foreach ($this->field_settings() as $field_name => $field) {
4854
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4854
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4855 4855
         }
4856 4856
         return $return_string
4857 4857
             ? implode(', ', $qualified_columns)
@@ -4878,11 +4878,11 @@  discard block
 block discarded – undo
4878 4878
             if ($table_obj instanceof EE_Primary_Table) {
4879 4879
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4880 4880
                     ? $table_obj->get_select_join_limit($limit)
4881
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4881
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4882 4882
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4883 4883
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4884 4884
                     ? $table_obj->get_select_join_limit_join($limit)
4885
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4885
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4886 4886
             }
4887 4887
         }
4888 4888
         return $SQL;
@@ -4953,7 +4953,7 @@  discard block
 block discarded – undo
4953 4953
         foreach ($this->field_settings() as $field_obj) {
4954 4954
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4955 4955
             /** @var $field_obj EE_Model_Field_Base */
4956
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4956
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4957 4957
         }
4958 4958
         return $data_types;
4959 4959
     }
@@ -4968,8 +4968,8 @@  discard block
 block discarded – undo
4968 4968
      */
4969 4969
     public function get_related_model_obj($model_name)
4970 4970
     {
4971
-        $model_classname = "EEM_" . $model_name;
4972
-        if (! class_exists($model_classname)) {
4971
+        $model_classname = "EEM_".$model_name;
4972
+        if ( ! class_exists($model_classname)) {
4973 4973
             throw new EE_Error(
4974 4974
                 sprintf(
4975 4975
                     esc_html__(
@@ -4981,7 +4981,7 @@  discard block
 block discarded – undo
4981 4981
                 )
4982 4982
             );
4983 4983
         }
4984
-        return call_user_func($model_classname . "::instance");
4984
+        return call_user_func($model_classname."::instance");
4985 4985
     }
4986 4986
 
4987 4987
 
@@ -5008,7 +5008,7 @@  discard block
 block discarded – undo
5008 5008
         $belongs_to_relations = [];
5009 5009
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
5010 5010
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
5011
-                $belongs_to_relations[ $model_name ] = $relation_obj;
5011
+                $belongs_to_relations[$model_name] = $relation_obj;
5012 5012
             }
5013 5013
         }
5014 5014
         return $belongs_to_relations;
@@ -5025,7 +5025,7 @@  discard block
 block discarded – undo
5025 5025
     public function related_settings_for($relation_name)
5026 5026
     {
5027 5027
         $relatedModels = $this->relation_settings();
5028
-        if (! array_key_exists($relation_name, $relatedModels)) {
5028
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
5029 5029
             throw new EE_Error(
5030 5030
                 sprintf(
5031 5031
                     esc_html__(
@@ -5038,7 +5038,7 @@  discard block
 block discarded – undo
5038 5038
                 )
5039 5039
             );
5040 5040
         }
5041
-        return $relatedModels[ $relation_name ];
5041
+        return $relatedModels[$relation_name];
5042 5042
     }
5043 5043
 
5044 5044
 
@@ -5054,7 +5054,7 @@  discard block
 block discarded – undo
5054 5054
     public function field_settings_for($fieldName, $include_db_only_fields = true)
5055 5055
     {
5056 5056
         $fieldSettings = $this->field_settings($include_db_only_fields);
5057
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5057
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
5058 5058
             throw new EE_Error(
5059 5059
                 sprintf(
5060 5060
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -5063,7 +5063,7 @@  discard block
 block discarded – undo
5063 5063
                 )
5064 5064
             );
5065 5065
         }
5066
-        return $fieldSettings[ $fieldName ];
5066
+        return $fieldSettings[$fieldName];
5067 5067
     }
5068 5068
 
5069 5069
 
@@ -5076,7 +5076,7 @@  discard block
 block discarded – undo
5076 5076
     public function has_field($fieldName)
5077 5077
     {
5078 5078
         $fieldSettings = $this->field_settings(true);
5079
-        if (isset($fieldSettings[ $fieldName ])) {
5079
+        if (isset($fieldSettings[$fieldName])) {
5080 5080
             return true;
5081 5081
         }
5082 5082
         return false;
@@ -5092,7 +5092,7 @@  discard block
 block discarded – undo
5092 5092
     public function has_relation($relation_name)
5093 5093
     {
5094 5094
         $relations = $this->relation_settings();
5095
-        if (isset($relations[ $relation_name ])) {
5095
+        if (isset($relations[$relation_name])) {
5096 5096
             return true;
5097 5097
         }
5098 5098
         return false;
@@ -5128,7 +5128,7 @@  discard block
 block discarded – undo
5128 5128
                     break;
5129 5129
                 }
5130 5130
             }
5131
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5131
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5132 5132
                 throw new EE_Error(
5133 5133
                     sprintf(
5134 5134
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5188,17 +5188,17 @@  discard block
 block discarded – undo
5188 5188
      */
5189 5189
     public function get_foreign_key_to($model_name)
5190 5190
     {
5191
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5191
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5192 5192
             foreach ($this->field_settings() as $field) {
5193 5193
                 if (
5194 5194
                     $field instanceof EE_Foreign_Key_Field_Base
5195 5195
                     && in_array($model_name, $field->get_model_names_pointed_to())
5196 5196
                 ) {
5197
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5197
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5198 5198
                     break;
5199 5199
                 }
5200 5200
             }
5201
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5201
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5202 5202
                 throw new EE_Error(
5203 5203
                     sprintf(
5204 5204
                         esc_html__(
@@ -5211,7 +5211,7 @@  discard block
 block discarded – undo
5211 5211
                 );
5212 5212
             }
5213 5213
         }
5214
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5214
+        return $this->_cache_foreign_key_to_fields[$model_name];
5215 5215
     }
5216 5216
 
5217 5217
 
@@ -5227,7 +5227,7 @@  discard block
 block discarded – undo
5227 5227
     {
5228 5228
         $table_alias_sans_model_relation_chain_prefix =
5229 5229
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5230
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5230
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5231 5231
     }
5232 5232
 
5233 5233
 
@@ -5245,7 +5245,7 @@  discard block
 block discarded – undo
5245 5245
                 $this->_cached_fields = [];
5246 5246
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5247 5247
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5248
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5248
+                        $this->_cached_fields[$field_name] = $field_obj;
5249 5249
                     }
5250 5250
                 }
5251 5251
             }
@@ -5256,8 +5256,8 @@  discard block
 block discarded – undo
5256 5256
             foreach ($this->_fields as $fields_corresponding_to_table) {
5257 5257
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5258 5258
                     /** @var $field_obj EE_Model_Field_Base */
5259
-                    if (! $field_obj->is_db_only_field()) {
5260
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5259
+                    if ( ! $field_obj->is_db_only_field()) {
5260
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5261 5261
                     }
5262 5262
                 }
5263 5263
             }
@@ -5300,12 +5300,12 @@  discard block
 block discarded – undo
5300 5300
                     $primary_key_field->get_qualified_column(),
5301 5301
                     $primary_key_field->get_table_column()
5302 5302
                 );
5303
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5303
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5304 5304
                     continue;
5305 5305
                 }
5306 5306
             }
5307 5307
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5308
-            if (! $classInstance) {
5308
+            if ( ! $classInstance) {
5309 5309
                 throw new EE_Error(
5310 5310
                     sprintf(
5311 5311
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5320,7 +5320,7 @@  discard block
 block discarded – undo
5320 5320
             $key                      = $has_primary_key
5321 5321
                 ? $classInstance->ID()
5322 5322
                 : $count_if_model_has_no_primary_key++;
5323
-            $array_of_objects[ $key ] = $classInstance;
5323
+            $array_of_objects[$key] = $classInstance;
5324 5324
             // also, for all the relations of type BelongsTo, see if we can cache
5325 5325
             // those related models
5326 5326
             // (we could do this for other relations too, but if there are conditions
@@ -5364,9 +5364,9 @@  discard block
 block discarded – undo
5364 5364
         $results = [];
5365 5365
         if ($this->_custom_selections instanceof CustomSelects) {
5366 5366
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5367
-                if (isset($db_results_row[ $alias ])) {
5368
-                    $results[ $alias ] = $this->convertValueToDataType(
5369
-                        $db_results_row[ $alias ],
5367
+                if (isset($db_results_row[$alias])) {
5368
+                    $results[$alias] = $this->convertValueToDataType(
5369
+                        $db_results_row[$alias],
5370 5370
                         $this->_custom_selections->getDataTypeForAlias($alias)
5371 5371
                     );
5372 5372
                 }
@@ -5411,7 +5411,7 @@  discard block
 block discarded – undo
5411 5411
         $this_model_fields_and_values = [];
5412 5412
         // setup the row using default values;
5413 5413
         foreach ($this->field_settings() as $field_name => $field_obj) {
5414
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5414
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5415 5415
         }
5416 5416
         $className = $this->_get_class_name();
5417 5417
         return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
@@ -5427,20 +5427,20 @@  discard block
 block discarded – undo
5427 5427
      */
5428 5428
     public function instantiate_class_from_array_or_object($cols_n_values)
5429 5429
     {
5430
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5430
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5431 5431
             $cols_n_values = get_object_vars($cols_n_values);
5432 5432
         }
5433 5433
         $primary_key = null;
5434 5434
         // make sure the array only has keys that are fields/columns on this model
5435 5435
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5436
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5437
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5436
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5437
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5438 5438
         }
5439 5439
         $className = $this->_get_class_name();
5440 5440
         // check we actually found results that we can use to build our model object
5441 5441
         // if not, return null
5442 5442
         if ($this->has_primary_key_field()) {
5443
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5443
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5444 5444
                 return null;
5445 5445
             }
5446 5446
         } elseif ($this->unique_indexes()) {
@@ -5452,7 +5452,7 @@  discard block
 block discarded – undo
5452 5452
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5453 5453
         if ($primary_key) {
5454 5454
             $classInstance = $this->get_from_entity_map($primary_key);
5455
-            if (! $classInstance) {
5455
+            if ( ! $classInstance) {
5456 5456
                 $classInstance = EE_Registry::instance()
5457 5457
                                             ->load_class(
5458 5458
                                                 $className,
@@ -5483,7 +5483,7 @@  discard block
 block discarded – undo
5483 5483
      */
5484 5484
     public function get_from_entity_map($id)
5485 5485
     {
5486
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5486
+        return $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] ?? null;
5487 5487
     }
5488 5488
 
5489 5489
 
@@ -5506,7 +5506,7 @@  discard block
 block discarded – undo
5506 5506
     public function add_to_entity_map(EE_Base_Class $object)
5507 5507
     {
5508 5508
         $className = $this->_get_class_name();
5509
-        if (! $object instanceof $className) {
5509
+        if ( ! $object instanceof $className) {
5510 5510
             throw new EE_Error(
5511 5511
                 sprintf(
5512 5512
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5518,7 +5518,7 @@  discard block
 block discarded – undo
5518 5518
             );
5519 5519
         }
5520 5520
 
5521
-        if (! $object->ID()) {
5521
+        if ( ! $object->ID()) {
5522 5522
             throw new EE_Error(
5523 5523
                 sprintf(
5524 5524
                     esc_html__(
@@ -5534,7 +5534,7 @@  discard block
 block discarded – undo
5534 5534
         if ($classInstance) {
5535 5535
             return $classInstance;
5536 5536
         }
5537
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5537
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5538 5538
         return $object;
5539 5539
     }
5540 5540
 
@@ -5549,11 +5549,11 @@  discard block
 block discarded – undo
5549 5549
     public function clear_entity_map($id = null)
5550 5550
     {
5551 5551
         if (empty($id)) {
5552
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5552
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5553 5553
             return true;
5554 5554
         }
5555
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5556
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5555
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5556
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5557 5557
             return true;
5558 5558
         }
5559 5559
         return false;
@@ -5601,18 +5601,18 @@  discard block
 block discarded – undo
5601 5601
             // there is a primary key on this table and its not set. Use defaults for all its columns
5602 5602
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5603 5603
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5604
-                    if (! $field_obj->is_db_only_field()) {
5604
+                    if ( ! $field_obj->is_db_only_field()) {
5605 5605
                         // prepare field as if its coming from db
5606 5606
                         $prepared_value                            =
5607 5607
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5608
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5608
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5609 5609
                     }
5610 5610
                 }
5611 5611
             } else {
5612 5612
                 // the table's rows existed. Use their values
5613 5613
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5614
-                    if (! $field_obj->is_db_only_field()) {
5615
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5614
+                    if ( ! $field_obj->is_db_only_field()) {
5615
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5616 5616
                             $cols_n_values,
5617 5617
                             $field_obj->get_qualified_column(),
5618 5618
                             $field_obj->get_table_column()
@@ -5639,17 +5639,17 @@  discard block
 block discarded – undo
5639 5639
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5640 5640
         // does the field on the model relate to this column retrieved from the db?
5641 5641
         // or is it a db-only field? (not relating to the model)
5642
-        if (isset($cols_n_values[ $qualified_column ])) {
5643
-            $value = $cols_n_values[ $qualified_column ];
5644
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5645
-            $value = $cols_n_values[ $regular_column ];
5646
-        } elseif (! empty($this->foreign_key_aliases)) {
5642
+        if (isset($cols_n_values[$qualified_column])) {
5643
+            $value = $cols_n_values[$qualified_column];
5644
+        } elseif (isset($cols_n_values[$regular_column])) {
5645
+            $value = $cols_n_values[$regular_column];
5646
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5647 5647
             // no PK?  ok check if there is a foreign key alias set for this table
5648 5648
             // then check if that alias exists in the incoming data
5649 5649
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5650 5650
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5651
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5652
-                    $value = $cols_n_values[ $FK_alias ];
5651
+                if ($PK_column === $qualified_column && ! empty($cols_n_values[$FK_alias])) {
5652
+                    $value = $cols_n_values[$FK_alias];
5653 5653
                     [$pk_class] = explode('.', $PK_column);
5654 5654
                     $pk_model_name = "EEM_{$pk_class}";
5655 5655
                     /** @var EEM_Base $pk_model */
@@ -5693,7 +5693,7 @@  discard block
 block discarded – undo
5693 5693
                     $obj_in_map->clear_cache($relation_name, null, true);
5694 5694
                 }
5695 5695
             }
5696
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5696
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5697 5697
             return $obj_in_map;
5698 5698
         }
5699 5699
         return $this->get_one_by_ID($id);
@@ -5745,7 +5745,7 @@  discard block
 block discarded – undo
5745 5745
      */
5746 5746
     private function _get_class_name()
5747 5747
     {
5748
-        return "EE_" . $this->get_this_model_name();
5748
+        return "EE_".$this->get_this_model_name();
5749 5749
     }
5750 5750
 
5751 5751
 
@@ -5799,7 +5799,7 @@  discard block
 block discarded – undo
5799 5799
     {
5800 5800
         $className = get_class($this);
5801 5801
         $tagName   = "FHEE__{$className}__{$methodName}";
5802
-        if (! has_filter($tagName)) {
5802
+        if ( ! has_filter($tagName)) {
5803 5803
             throw new EE_Error(
5804 5804
                 sprintf(
5805 5805
                     esc_html__(
@@ -5970,7 +5970,7 @@  discard block
 block discarded – undo
5970 5970
         $unique_indexes = [];
5971 5971
         foreach ($this->_indexes as $name => $index) {
5972 5972
             if ($index instanceof EE_Unique_Index) {
5973
-                $unique_indexes [ $name ] = $index;
5973
+                $unique_indexes [$name] = $index;
5974 5974
             }
5975 5975
         }
5976 5976
         return $unique_indexes;
@@ -6034,7 +6034,7 @@  discard block
 block discarded – undo
6034 6034
         $key_vals_in_combined_pk = [];
6035 6035
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6036 6036
         foreach ($key_fields as $key_field_name => $field_obj) {
6037
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6037
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
6038 6038
                 return null;
6039 6039
             }
6040 6040
         }
@@ -6054,7 +6054,7 @@  discard block
 block discarded – undo
6054 6054
     {
6055 6055
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6056 6056
         foreach ($keys_it_should_have as $key) {
6057
-            if (! isset($key_vals[ $key ])) {
6057
+            if ( ! isset($key_vals[$key])) {
6058 6058
                 return false;
6059 6059
             }
6060 6060
         }
@@ -6093,8 +6093,8 @@  discard block
 block discarded – undo
6093 6093
         }
6094 6094
         // even copies obviously won't have the same ID, so remove the primary key
6095 6095
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
6096
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6097
-            unset($attributes_array[ $this->primary_key_name() ]);
6096
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
6097
+            unset($attributes_array[$this->primary_key_name()]);
6098 6098
         }
6099 6099
         if (isset($query_params[0])) {
6100 6100
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -6116,7 +6116,7 @@  discard block
 block discarded – undo
6116 6116
      */
6117 6117
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6118 6118
     {
6119
-        if (! is_array($query_params)) {
6119
+        if ( ! is_array($query_params)) {
6120 6120
             EE_Error::doing_it_wrong(
6121 6121
                 'EEM_Base::get_one_copy',
6122 6122
                 sprintf(
@@ -6165,7 +6165,7 @@  discard block
 block discarded – undo
6165 6165
      */
6166 6166
     private function _prepare_operator_for_sql($operator_supplied)
6167 6167
     {
6168
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6168
+        $sql_operator = $this->_valid_operators[$operator_supplied] ?? null;
6169 6169
         if ($sql_operator) {
6170 6170
             return $sql_operator;
6171 6171
         }
@@ -6263,7 +6263,7 @@  discard block
 block discarded – undo
6263 6263
         $objs  = $this->get_all($query_params);
6264 6264
         $names = [];
6265 6265
         foreach ($objs as $obj) {
6266
-            $names[ $obj->ID() ] = $obj->name();
6266
+            $names[$obj->ID()] = $obj->name();
6267 6267
         }
6268 6268
         return $names;
6269 6269
     }
@@ -6284,7 +6284,7 @@  discard block
 block discarded – undo
6284 6284
      */
6285 6285
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6286 6286
     {
6287
-        if (! $this->has_primary_key_field()) {
6287
+        if ( ! $this->has_primary_key_field()) {
6288 6288
             if (defined('WP_DEBUG') && WP_DEBUG) {
6289 6289
                 EE_Error::add_error(
6290 6290
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6297,7 +6297,7 @@  discard block
 block discarded – undo
6297 6297
         $IDs = [];
6298 6298
         foreach ($model_objects as $model_object) {
6299 6299
             $id = $model_object->ID();
6300
-            if (! $id) {
6300
+            if ( ! $id) {
6301 6301
                 if ($filter_out_empty_ids) {
6302 6302
                     continue;
6303 6303
                 }
@@ -6346,22 +6346,22 @@  discard block
 block discarded – undo
6346 6346
         EEM_Base::verify_is_valid_cap_context($context);
6347 6347
         // check if we ought to run the restriction generator first
6348 6348
         if (
6349
-            isset($this->_cap_restriction_generators[ $context ])
6350
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6351
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6349
+            isset($this->_cap_restriction_generators[$context])
6350
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6351
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6352 6352
         ) {
6353
-            $this->_cap_restrictions[ $context ] = array_merge(
6354
-                $this->_cap_restrictions[ $context ],
6355
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6353
+            $this->_cap_restrictions[$context] = array_merge(
6354
+                $this->_cap_restrictions[$context],
6355
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6356 6356
             );
6357 6357
         }
6358 6358
         // and make sure we've finalized the construction of each restriction
6359
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6359
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6360 6360
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6361 6361
                 $where_conditions_obj->_finalize_construct($this);
6362 6362
             }
6363 6363
         }
6364
-        return $this->_cap_restrictions[ $context ];
6364
+        return $this->_cap_restrictions[$context];
6365 6365
     }
6366 6366
 
6367 6367
 
@@ -6391,9 +6391,9 @@  discard block
 block discarded – undo
6391 6391
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6392 6392
             if (
6393 6393
                 ! EE_Capabilities::instance()
6394
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6394
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6395 6395
             ) {
6396
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6396
+                $missing_caps[$cap] = $restriction_if_no_cap;
6397 6397
             }
6398 6398
         }
6399 6399
         return $missing_caps;
@@ -6426,8 +6426,8 @@  discard block
 block discarded – undo
6426 6426
     public function cap_action_for_context($context)
6427 6427
     {
6428 6428
         $mapping = $this->cap_contexts_to_cap_action_map();
6429
-        if (isset($mapping[ $context ])) {
6430
-            return $mapping[ $context ];
6429
+        if (isset($mapping[$context])) {
6430
+            return $mapping[$context];
6431 6431
         }
6432 6432
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6433 6433
             return $action;
@@ -6548,7 +6548,7 @@  discard block
 block discarded – undo
6548 6548
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6549 6549
             if (
6550 6550
                 $query_param_key === $logic_query_param_key
6551
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6551
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6552 6552
             ) {
6553 6553
                 return true;
6554 6554
             }
@@ -6606,7 +6606,7 @@  discard block
 block discarded – undo
6606 6606
         if ($password_field instanceof EE_Password_Field) {
6607 6607
             $field_names = $password_field->protectedFields();
6608 6608
             foreach ($field_names as $field_name) {
6609
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6609
+                $fields[$field_name] = $this->field_settings_for($field_name);
6610 6610
             }
6611 6611
         }
6612 6612
         return $fields;
@@ -6632,7 +6632,7 @@  discard block
 block discarded – undo
6632 6632
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6633 6633
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6634 6634
         }
6635
-        if (! is_array($model_obj_or_fields_n_values)) {
6635
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6636 6636
             throw new UnexpectedEntityException(
6637 6637
                 $model_obj_or_fields_n_values,
6638 6638
                 'EE_Base_Class',
@@ -6714,9 +6714,9 @@  discard block
 block discarded – undo
6714 6714
         }
6715 6715
         return (
6716 6716
                $this->model_chain_to_password
6717
-                   ? $this->model_chain_to_password . '.'
6717
+                   ? $this->model_chain_to_password.'.'
6718 6718
                    : ''
6719
-               ) . $password_field_name;
6719
+               ).$password_field_name;
6720 6720
     }
6721 6721
 
6722 6722
 
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +1200 added lines, -1200 removed lines patch added patch discarded remove patch
@@ -20,1204 +20,1204 @@
 block discarded – undo
20 20
  */
21 21
 class EE_Dependency_Map
22 22
 {
23
-    /**
24
-     * This means that the requested class dependency is not present in the dependency map
25
-     */
26
-    const not_registered = 0;
27
-
28
-    /**
29
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
30
-     */
31
-    const load_new_object = 1;
32
-
33
-    /**
34
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
35
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
36
-     */
37
-    const load_from_cache = 2;
38
-
39
-    /**
40
-     * When registering a dependency,
41
-     * this indicates to keep any existing dependencies that already exist,
42
-     * and simply discard any new dependencies declared in the incoming data
43
-     */
44
-    const KEEP_EXISTING_DEPENDENCIES = 0;
45
-
46
-    /**
47
-     * When registering a dependency,
48
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
49
-     */
50
-    const OVERWRITE_DEPENDENCIES = 1;
51
-
52
-    protected static ?EE_Dependency_Map $_instance = null;
53
-
54
-    private ClassInterfaceCache $class_cache;
55
-
56
-    protected ?RequestInterface $request = null;
57
-
58
-    protected ?LegacyRequestInterface $legacy_request = null;
59
-
60
-    protected ?ResponseInterface $response = null;
61
-
62
-    protected ?LoaderInterface $loader = null;
63
-
64
-    protected array $_dependency_map = [];
65
-
66
-    protected array $_class_loaders = [];
67
-
68
-
69
-    /**
70
-     * EE_Dependency_Map constructor.
71
-     *
72
-     * @param ClassInterfaceCache $class_cache
73
-     */
74
-    protected function __construct(ClassInterfaceCache $class_cache)
75
-    {
76
-        $this->class_cache = $class_cache;
77
-        do_action('EE_Dependency_Map____construct', $this);
78
-    }
79
-
80
-
81
-    /**
82
-     * @return void
83
-     * @throws InvalidAliasException
84
-     */
85
-    public function initialize()
86
-    {
87
-        $this->_register_core_dependencies();
88
-        $this->_register_core_class_loaders();
89
-        $this->_register_core_aliases();
90
-    }
91
-
92
-
93
-    /**
94
-     * @singleton method used to instantiate class object
95
-     * @param ClassInterfaceCache|null $class_cache
96
-     * @return EE_Dependency_Map
97
-     */
98
-    public static function instance(ClassInterfaceCache $class_cache = null): EE_Dependency_Map
99
-    {
100
-        // check if class object is instantiated, and instantiated properly
101
-        if (
102
-            ! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
103
-            && $class_cache instanceof ClassInterfaceCache
104
-        ) {
105
-            EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
106
-        }
107
-        return EE_Dependency_Map::$_instance;
108
-    }
109
-
110
-
111
-    /**
112
-     * @param RequestInterface $request
113
-     */
114
-    public function setRequest(RequestInterface $request)
115
-    {
116
-        $this->request = $request;
117
-    }
118
-
119
-
120
-    /**
121
-     * @param LegacyRequestInterface $legacy_request
122
-     */
123
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
124
-    {
125
-        $this->legacy_request = $legacy_request;
126
-    }
127
-
128
-
129
-    /**
130
-     * @param ResponseInterface $response
131
-     */
132
-    public function setResponse(ResponseInterface $response)
133
-    {
134
-        $this->response = $response;
135
-    }
136
-
137
-
138
-    /**
139
-     * @param LoaderInterface $loader
140
-     */
141
-    public function setLoader(LoaderInterface $loader)
142
-    {
143
-        $this->loader = $loader;
144
-    }
145
-
146
-
147
-    /**
148
-     * @param string $class
149
-     * @param array  $dependencies
150
-     * @param int    $overwrite
151
-     * @return bool
152
-     */
153
-    public static function register_dependencies(
154
-        string $class,
155
-        array $dependencies,
156
-        int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
157
-    ): bool {
158
-        return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
159
-    }
160
-
161
-
162
-    /**
163
-     * Assigns an array of class names and corresponding load sources (new or cached)
164
-     * to the class specified by the first parameter.
165
-     * IMPORTANT !!!
166
-     * The order of elements in the incoming $dependencies array MUST match
167
-     * the order of the constructor parameters for the class in question.
168
-     * This is especially important when overriding any existing dependencies that are registered.
169
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
170
-     *
171
-     * @param string $class
172
-     * @param array  $dependencies
173
-     * @param int    $overwrite
174
-     * @return bool
175
-     */
176
-    public function registerDependencies(
177
-        string $class,
178
-        array $dependencies,
179
-        int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
180
-    ): bool {
181
-        if (empty($dependencies)) {
182
-            return false;
183
-        }
184
-        $class      = trim($class, '\\');
185
-        $registered = false;
186
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
187
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
188
-        }
189
-        // we need to make sure that any aliases used when registering a dependency
190
-        // get resolved to the correct class name
191
-        foreach ($dependencies as $dependency => $load_source) {
192
-            $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
193
-            if (
194
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
195
-                || ! isset(
196
-                    EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $dependency ],
197
-                    EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ]
198
-                )
199
-            ) {
200
-                unset($dependencies[ $dependency ]);
201
-                $dependencies[ $alias ] = $load_source;
202
-                $registered             = true;
203
-            }
204
-        }
205
-        // now add our two lists of dependencies together.
206
-        // using Union (+=) favours the arrays in precedence from left to right,
207
-        // so $dependencies is NOT overwritten because it is listed first
208
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
209
-        // Union is way faster than array_merge() but should be used with caution...
210
-        // especially with numerically indexed arrays
211
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
212
-        // now we need to ensure that the resulting dependencies
213
-        // array only has the entries that are required for the class
214
-        // so first count how many dependencies were originally registered for the class
215
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
216
-        // if that count is non-zero (meaning dependencies were already registered)
217
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
218
-            // then truncate the  final array to match that count
219
-            ? array_slice($dependencies, 0, $dependency_count)
220
-            // otherwise just take the incoming array because nothing previously existed
221
-            : $dependencies;
222
-        return $registered
223
-            || count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]) === count($dependencies);
224
-    }
225
-
226
-
227
-    /**
228
-     * @param string          $class_name
229
-     * @param callable|string $loader
230
-     * @param bool            $overwrite
231
-     * @return bool
232
-     * @throws DomainException
233
-     */
234
-    public static function register_class_loader(
235
-        string $class_name,
236
-        $loader = 'load_core',
237
-        bool $overwrite = false
238
-    ): bool {
239
-        return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader, $overwrite);
240
-    }
241
-
242
-
243
-    /**
244
-     * @param string         $class_name
245
-     * @param Closure|string $loader
246
-     * @param bool           $overwrite
247
-     * @return bool
248
-     * @throws DomainException
249
-     */
250
-    public function registerClassLoader(string $class_name, $loader = 'load_core', bool $overwrite = false): bool
251
-    {
252
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
253
-            throw new DomainException(
254
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
255
-            );
256
-        }
257
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
258
-        if (
259
-            ! is_callable($loader)
260
-            && (
261
-                strpos($loader, 'load_') !== 0
262
-                || ! method_exists('EE_Registry', $loader)
263
-            )
264
-        ) {
265
-            throw new DomainException(
266
-                sprintf(
267
-                    esc_html__(
268
-                        '"%1$s" is not a valid loader method on EE_Registry.',
269
-                        'event_espresso'
270
-                    ),
271
-                    $loader
272
-                )
273
-            );
274
-        }
275
-        $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
276
-        if ($overwrite || ! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
277
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
278
-            return true;
279
-        }
280
-        return false;
281
-    }
282
-
283
-
284
-    /**
285
-     * @return array
286
-     */
287
-    public function dependency_map(): array
288
-    {
289
-        return $this->_dependency_map;
290
-    }
291
-
292
-
293
-    /**
294
-     * returns TRUE if dependency map contains a listing for the provided class name
295
-     *
296
-     * @param string $class_name
297
-     * @return boolean
298
-     */
299
-    public function has(string $class_name = ''): bool
300
-    {
301
-        // all legacy models have the same dependencies
302
-        if (strpos($class_name, 'EEM_') === 0) {
303
-            $class_name = 'LEGACY_MODELS';
304
-        }
305
-        return isset($this->_dependency_map[ $class_name ]);
306
-    }
307
-
308
-
309
-    /**
310
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
311
-     *
312
-     * @param string $class_name
313
-     * @param string $dependency
314
-     * @return bool
315
-     */
316
-    public function has_dependency_for_class(string $class_name = '', string $dependency = ''): bool
317
-    {
318
-        // all legacy models have the same dependencies
319
-        if (strpos($class_name, 'EEM_') === 0) {
320
-            $class_name = 'LEGACY_MODELS';
321
-        }
322
-        $dependency = $this->getFqnForAlias($dependency, $class_name);
323
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
324
-    }
325
-
326
-
327
-    /**
328
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
329
-     *
330
-     * @param string $class_name
331
-     * @param string $dependency
332
-     * @return int
333
-     */
334
-    public function loading_strategy_for_class_dependency(string $class_name = '', string $dependency = ''): int
335
-    {
336
-        // all legacy models have the same dependencies
337
-        if (strpos($class_name, 'EEM_') === 0) {
338
-            $class_name = 'LEGACY_MODELS';
339
-        }
340
-        $dependency = $this->getFqnForAlias($dependency);
341
-        return $this->has_dependency_for_class($class_name, $dependency)
342
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
343
-            : EE_Dependency_Map::not_registered;
344
-    }
345
-
346
-
347
-    /**
348
-     * @param string $class_name
349
-     * @return string | Closure
350
-     */
351
-    public function class_loader(string $class_name)
352
-    {
353
-        // all legacy models use load_model()
354
-        if (strpos($class_name, 'EEM_') === 0) {
355
-            return 'load_model';
356
-        }
357
-        // EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
358
-        // perform strpos() first to avoid loading regex every time we load a class
359
-        if (
360
-            strpos($class_name, 'EE_CPT_') === 0
361
-            && preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
362
-        ) {
363
-            return 'load_core';
364
-        }
365
-        $class_name = $this->getFqnForAlias($class_name);
366
-        return $this->_class_loaders[ $class_name ] ?? '';
367
-    }
368
-
369
-
370
-    /**
371
-     * @return array
372
-     */
373
-    public function class_loaders(): array
374
-    {
375
-        return $this->_class_loaders;
376
-    }
377
-
378
-
379
-    /**
380
-     * adds an alias for a classname
381
-     *
382
-     * @param string $fqcn      the class name that should be used (concrete class to replace interface)
383
-     * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
384
-     * @param string $for_class the class that has the dependency (is type hinting for the interface)
385
-     * @throws InvalidAliasException
386
-     */
387
-    public function add_alias(string $fqcn, string $alias, string $for_class = '')
388
-    {
389
-        $this->class_cache->addAlias($fqcn, $alias, $for_class);
390
-    }
391
-
392
-
393
-    /**
394
-     * Returns TRUE if the provided fully qualified name IS an alias
395
-     * WHY?
396
-     * Because if a class is type hinting for a concretion,
397
-     * then why would we need to find another class to supply it?
398
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
399
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
400
-     * Don't go looking for some substitute.
401
-     * Whereas if a class is type hinting for an interface...
402
-     * then we need to find an actual class to use.
403
-     * So the interface IS the alias for some other FQN,
404
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
405
-     * represents some other class.
406
-     *
407
-     * @param string $fqn
408
-     * @param string $for_class
409
-     * @return bool
410
-     */
411
-    public function isAlias(string $fqn = '', string $for_class = ''): bool
412
-    {
413
-        return $this->class_cache->isAlias($fqn, $for_class);
414
-    }
415
-
416
-
417
-    /**
418
-     * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
419
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
420
-     *  for example:
421
-     *      if the following two entries were added to the _aliases array:
422
-     *          array(
423
-     *              'interface_alias'           => 'some\namespace\interface'
424
-     *              'some\namespace\interface'  => 'some\namespace\classname'
425
-     *          )
426
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
427
-     *      to load an instance of 'some\namespace\classname'
428
-     *
429
-     * @param string $alias
430
-     * @param string $for_class
431
-     * @return string
432
-     */
433
-    public function getFqnForAlias(string $alias = '', string $for_class = ''): string
434
-    {
435
-        return $this->class_cache->getFqnForAlias($alias, $for_class);
436
-    }
437
-
438
-
439
-    /**
440
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
441
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
442
-     * This is done by using the following class constants:
443
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
444
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
445
-     */
446
-    protected function _register_core_dependencies()
447
-    {
448
-        $this->_dependency_map = [
449
-            'EE_Admin'                                                                                                           => [
450
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
451
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
452
-            ],
453
-            'EE_Maintenance_Mode'                                                                                                => [
454
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
455
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
456
-            ],
457
-            'EE_Request_Handler'                                                                                                 => [
458
-                'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
459
-                'EventEspresso\core\services\request\Response' => EE_Dependency_Map::load_from_cache,
460
-            ],
461
-            'EE_System'                                                                                                   => [
462
-                'EventEspresso\core\services\loaders\Loader'                   => EE_Dependency_Map::load_from_cache,
463
-                'EE_Maintenance_Mode'                                          => EE_Dependency_Map::load_from_cache,
464
-                'EE_Registry'                                                  => EE_Dependency_Map::load_from_cache,
465
-                'EventEspresso\core\services\request\Request'                  => EE_Dependency_Map::load_from_cache,
466
-                'EventEspresso\core\services\routing\Router'                   => EE_Dependency_Map::load_from_cache,
467
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
468
-            ],
469
-            'EE_Session'                                                                                                         => [
470
-                'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
471
-                'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
472
-                'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
473
-                'EventEspresso\core\services\session\SessionStartHandler'  => EE_Dependency_Map::load_from_cache,
474
-                'EventEspresso\core\services\encryption\Base64Encoder'     => EE_Dependency_Map::load_from_cache,
475
-            ],
476
-            'EventEspresso\core\services\session\SessionStartHandler'                                                            => [
477
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
478
-            ],
479
-            'EE_Cart'                                                                                                            => [
480
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
481
-            ],
482
-            'EE_Messenger_Collection_Loader'                                                                                     => [
483
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
484
-            ],
485
-            'EE_Message_Type_Collection_Loader'                                                                                  => [
486
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
487
-            ],
488
-            'EE_Message_Resource_Manager'                                                                                        => [
489
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
490
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
491
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
492
-            ],
493
-            'EE_Message_Factory'                                                                                                 => [
494
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
-            ],
496
-            'EE_messages'                                                                                                        => [
497
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
498
-            ],
499
-            'EE_Messages_Generator'                                                                                              => [
500
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
501
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
502
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
503
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
504
-            ],
505
-            'EE_Messages_Processor'                                                                                              => [
506
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
507
-            ],
508
-            'EE_Messages_Queue'                                                                                                  => [
509
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
510
-            ],
511
-            'EE_Messages_Template_Defaults'                                                                                      => [
512
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
513
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
514
-            ],
515
-            'EE_Message_To_Generate_From_Request'                                                                                => [
516
-                'EE_Message_Resource_Manager'                 => EE_Dependency_Map::load_from_cache,
517
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
518
-            ],
519
-            'EventEspresso\core\services\commands\CommandBus'                                                                    => [
520
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
521
-            ],
522
-            'EventEspresso\services\commands\CommandHandler'                                                                     => [
523
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
524
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
525
-            ],
526
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                         => [
527
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
528
-            ],
529
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                       => [
530
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
531
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
532
-            ],
533
-            'EventEspresso\core\services\commands\CommandFactory'                                                                => [
534
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
535
-            ],
536
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                         => [
537
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
538
-            ],
539
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                                => [
540
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
-            ],
542
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                            => [
543
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
544
-            ],
545
-            'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommandHandler'                          => [
546
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
547
-            ],
548
-            'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
549
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
-            ],
551
-            'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
552
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
553
-            ],
554
-            'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
555
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
556
-            ],
557
-            'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
558
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
559
-            ],
560
-            'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
561
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
-            ],
563
-            'EventEspresso\core\domain\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
564
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
-            ],
566
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                          => [
567
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
-            ],
569
-            'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
570
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
571
-            ],
572
-            'EventEspresso\core\domain\values\session\SessionLifespan'                                                           => [
573
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
574
-            ],
575
-            'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanForm'                                 => [
576
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
577
-                'EE_Registration_Config'                                         => EE_Dependency_Map::load_from_cache,
578
-            ],
579
-            'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanFormHandler'                          => [
580
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
581
-                'EE_Config'                                                      => EE_Dependency_Map::load_from_cache,
582
-            ],
583
-            'EventEspresso\core\services\database\TableManager'                                                                  => [
584
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
585
-            ],
586
-            'EE_Data_Migration_Class_Base'                                                                                       => [
587
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
-            ],
590
-            'EE_DMS_Core_4_1_0'                                                                                                  => [
591
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
-            ],
594
-            'EE_DMS_Core_4_2_0'                                                                                                  => [
595
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
596
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
597
-            ],
598
-            'EE_DMS_Core_4_3_0'                                                                                                  => [
599
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
600
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
601
-            ],
602
-            'EE_DMS_Core_4_4_0'                                                                                                  => [
603
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
604
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
605
-            ],
606
-            'EE_DMS_Core_4_5_0'                                                                                                  => [
607
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
608
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
609
-            ],
610
-            'EE_DMS_Core_4_6_0'                                                                                                  => [
611
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
612
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
613
-            ],
614
-            'EE_DMS_Core_4_7_0'                                                                                                  => [
615
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
616
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
617
-            ],
618
-            'EE_DMS_Core_4_8_0'                                                                                                  => [
619
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
-            ],
622
-            'EE_DMS_Core_4_9_0'                                                                                                  => [
623
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
624
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
625
-            ],
626
-            'EE_DMS_Core_4_10_0'                                                                                                 => [
627
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
628
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
629
-                'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
630
-            ],
631
-            'EE_DMS_Core_5_0_0'                                                                                                  => [
632
-                'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
633
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
634
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
635
-            ],
636
-            'EventEspresso\core\services\assets\I18nRegistry'                                                                    => [
637
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
638
-            ],
639
-            'EventEspresso\core\services\assets\Registry'                                                                        => [
640
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
641
-                'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
642
-            ],
643
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                                    => [
644
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
-            ],
646
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                                     => [
647
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
-            ],
649
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                               => [
650
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
-            ],
652
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                       => [
653
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
654
-            ],
655
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                                     => [
656
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
657
-            ],
658
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                               => [
659
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
660
-            ],
661
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                                      => [
662
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
663
-            ],
664
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                                => [
665
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
666
-            ],
667
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                          => [
668
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
669
-            ],
670
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                         => [
671
-                'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
672
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
673
-            ],
674
-            'EventEspresso\core\domain\values\EmailAddress'                                                                      => [
675
-                null,
676
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
677
-            ],
678
-            'EventEspresso\core\services\orm\ModelFieldFactory'                                                                  => [
679
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
680
-            ],
681
-            'LEGACY_MODELS'                                                                                                      => [
682
-                null,
683
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
684
-            ],
685
-            'EE_Module_Request_Router'                                                                                           => [
686
-                'EventEspresso\core\services\request\Request'             => EE_Dependency_Map::load_from_cache,
687
-                'EventEspresso\core\services\modules\ModuleRoutesManager' => EE_Dependency_Map::load_from_cache,
688
-            ],
689
-            'EE_Registration_Processor'                                                                                          => [
690
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
691
-            ],
692
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                             => [
693
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
694
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
695
-            ],
696
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                           => [
697
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
698
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
699
-            ],
700
-            'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                        => [
701
-                'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
702
-                'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
703
-                'EE_Ticket_Selector_Config'                            => EE_Dependency_Map::load_from_cache,
704
-            ],
705
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                        => [
706
-                'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
707
-                'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
708
-                'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
709
-                'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
710
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
711
-            ],
712
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelectorPostData'                                                => [
713
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
714
-                'EEM_Event'                                   => EE_Dependency_Map::load_from_cache,
715
-            ],
716
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                            => [
717
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
718
-            ],
719
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                                     => [
720
-                'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
721
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
722
-            ],
723
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                       => [
724
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
725
-            ],
726
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                                      => [
727
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
728
-            ],
729
-            'EE_CPT_Strategy'                                                                                                    => [
730
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
731
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
732
-            ],
733
-            'EventEspresso\core\services\loaders\ObjectIdentifier'                                                               => [
734
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
735
-            ],
736
-            'EventEspresso\core\CPTs\CptQueryModifier'                                                                           => [
737
-                null,
738
-                null,
739
-                null,
740
-                'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
741
-                'EventEspresso\core\services\request\Request'     => EE_Dependency_Map::load_from_cache,
742
-                'EventEspresso\core\services\loaders\Loader'      => EE_Dependency_Map::load_from_cache,
743
-            ],
744
-            'EventEspresso\core\services\dependencies\DependencyResolver'                                                        => [
745
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
746
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
747
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
748
-            ],
749
-            'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                                      => [
750
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
751
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
752
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
753
-            ],
754
-            'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                                 => [
755
-                'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
756
-                'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
757
-            ],
758
-            'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                                 => [
759
-                'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
760
-                'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
761
-            ],
762
-            'EventEspresso\core\services\request\files\FilesDataHandler'                                                         => [
763
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
764
-            ],
765
-            'EventEspresso\core\libraries\batch\BatchRequestProcessor'                                                           => [
766
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
767
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
768
-            ],
769
-            'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                       => [
770
-                'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
771
-                'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
772
-                'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
773
-                null,
774
-            ],
775
-            'EventEspresso\core\services\routing\RouteHandler'                                                                   => [
776
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
777
-                'EventEspresso\core\services\json\JsonDataNodeHandler'                => EE_Dependency_Map::load_from_cache,
778
-                'EventEspresso\core\services\loaders\Loader'                          => EE_Dependency_Map::load_from_cache,
779
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
780
-                'EventEspresso\core\services\routing\RouteCollection'                 => EE_Dependency_Map::load_from_cache,
781
-            ],
782
-            'EventEspresso\core\services\json\JsonDataNodeHandler'                                                               => [
783
-                'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
784
-            ],
785
-            'EventEspresso\core\services\routing\Router'                                                                         => [
786
-                'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
787
-                'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
788
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
789
-            ],
790
-            'EventEspresso\core\services\assets\AssetManifest'                                                                   => [
791
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
792
-            ],
793
-            'EventEspresso\core\services\assets\AssetManifestFactory'                                                            => [
794
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
795
-            ],
796
-            'EventEspresso\core\services\assets\BaristaFactory'                                                                  => [
797
-                'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
798
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
799
-            ],
800
-            'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig' => [
801
-                'EventEspresso\core\domain\Domain'                                    => EE_Dependency_Map::load_from_cache,
802
-                'EventEspresso\core\services\json\JsonDataHandler'                    => EE_Dependency_Map::load_from_cache,
803
-            ],
804
-            'EventEspresso\core\domain\services\capabilities\FeatureFlags'       => [
805
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
806
-                'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig'  => EE_Dependency_Map::load_from_cache,
807
-            ],
808
-            'EventEspresso\core\services\addon\AddonManager'                                                                     => [
809
-                'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
810
-                'EE_Dependency_Map'                                              => EE_Dependency_Map::load_from_cache,
811
-                'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
812
-                'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
813
-                'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
814
-            ],
815
-            'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'                                                      => [
816
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
817
-            ],
818
-            'EventEspresso\core\libraries\batch\JobHandlers\ExecuteBatchDeletion'                                                => [
819
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
820
-            ],
821
-            'EventEspresso\core\libraries\batch\JobHandlers\PreviewEventDeletion'                                                => [
822
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
823
-            ],
824
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'                                               => [
825
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
826
-                'EEM_Event'                                                   => EE_Dependency_Map::load_from_cache,
827
-                'EEM_Datetime'                                                => EE_Dependency_Map::load_from_cache,
828
-                'EEM_Registration'                                            => EE_Dependency_Map::load_from_cache,
829
-            ],
830
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'                                               => [
831
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
832
-            ],
833
-            'EventEspresso\core\services\request\CurrentPage'                                                                    => [
834
-                'EE_CPT_Strategy'                             => EE_Dependency_Map::load_from_cache,
835
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
836
-            ],
837
-            'EventEspresso\core\services\shortcodes\LegacyShortcodesManager'                                                     => [
838
-                'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
839
-                'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
840
-            ],
841
-            'EventEspresso\core\services\shortcodes\ShortcodesManager'                                                           => [
842
-                'EventEspresso\core\services\shortcodes\LegacyShortcodesManager' => EE_Dependency_Map::load_from_cache,
843
-                'EventEspresso\core\services\request\CurrentPage'                => EE_Dependency_Map::load_from_cache,
844
-            ],
845
-            'EventEspresso\core\domain\entities\users\CurrentUser'                                                               => [
846
-                'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
847
-            ],
848
-            'EventEspresso\core\services\form\meta\InputTypes'                                                                   => [
849
-                'EventEspresso\core\services\form\meta\inputs\Block'    => EE_Dependency_Map::load_from_cache,
850
-                'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
851
-                'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
852
-                'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
853
-                'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
854
-                'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
855
-                'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
856
-                'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
857
-            ],
858
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler'                                   => [
859
-                'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
860
-            ],
861
-            'EventEspresso\core\services\calculators\LineItemCalculator'                                                         => [
862
-                'EventEspresso\core\services\helpers\DecimalValues' => EE_Dependency_Map::load_from_cache,
863
-            ],
864
-            'EventEspresso\core\services\helpers\DecimalValues'                                                                  => [
865
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
866
-            ],
867
-            'EE_Brewing_Regular'                                                                                                 => [
868
-                'EE_Dependency_Map'                                  => EE_Dependency_Map::load_from_cache,
869
-                'EventEspresso\core\services\loaders\Loader'         => EE_Dependency_Map::load_from_cache,
870
-                'EventEspresso\core\services\routing\RouteHandler'   => EE_Dependency_Map::load_from_cache,
871
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
872
-            ],
873
-            'EventEspresso\core\domain\services\messages\MessageTemplateRequestData'                                             => [
874
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
875
-            ],
876
-            'EventEspresso\core\domain\services\messages\MessageTemplateValidator'                                               => [
877
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
878
-            ],
879
-            'EventEspresso\core\domain\services\messages\MessageTemplateManager'                                                 => [
880
-                'EEM_Message_Template'                                                   => EE_Dependency_Map::load_from_cache,
881
-                'EEM_Message_Template_Group'                                             => EE_Dependency_Map::load_from_cache,
882
-                'EventEspresso\core\domain\services\messages\MessageTemplateRequestData' => EE_Dependency_Map::load_from_cache,
883
-                'EventEspresso\core\domain\services\messages\MessageTemplateValidator'   => EE_Dependency_Map::load_from_cache,
884
-                'EventEspresso\core\services\request\Request'                            => EE_Dependency_Map::load_from_cache,
885
-            ],
886
-            'EventEspresso\core\services\request\sanitizers\RequestSanitizer'                                                    => [
887
-                'EventEspresso\core\domain\services\validation\email\strategies\Basic' => EE_Dependency_Map::load_from_cache,
888
-            ],
889
-            'EE_CPT_Event_Strategy'                                                    => [
890
-                null,
891
-                null,
892
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
893
-            ],
894
-            'EventEspresso\core\domain\services\licensing\LicenseKeyFormInput'                                                    => [
895
-                'EventEspresso\core\services\licensing\PluginLicense'  => EE_Dependency_Map::not_registered,
896
-                'EventEspresso\core\services\licensing\LicenseManager' => EE_Dependency_Map::load_from_cache,
897
-            ],
898
-            'EventEspresso\core\services\payments\IpnHandler' => [
899
-                'EEM_Payment_Method'                                    => EE_Dependency_Map::not_registered,
900
-                'EEM_Transaction'                                       => EE_Dependency_Map::load_from_cache,
901
-                'EE_Core_Config'                                        => EE_Dependency_Map::load_from_cache,
902
-                'EE_Organization_Config'                                => EE_Dependency_Map::load_from_cache,
903
-                'EventEspresso\core\services\payments\PaymentProcessor' => EE_Dependency_Map::load_from_cache,
904
-            ],
905
-            'EventEspresso\core\services\payments\PaymentProcessor' => [
906
-                'EEM_Payment_Method'                                           => EE_Dependency_Map::not_registered,
907
-                'EEM_Transaction'                                              => EE_Dependency_Map::load_from_cache,
908
-                'EE_Organization_Config'                                       => EE_Dependency_Map::load_from_cache,
909
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
910
-                'EventEspresso\core\services\payments\PaymentProcessorFees'    => EE_Dependency_Map::load_from_cache,
911
-                'EventEspresso\core\services\payments\PostPaymentProcessor'    => EE_Dependency_Map::load_from_cache,
912
-                'EventEspresso\core\services\payments\RegistrationPayments'    => EE_Dependency_Map::load_from_cache,
913
-            ],
914
-            'EventEspresso\core\services\payments\PostPaymentProcessor' => [
915
-                'EE_Transaction_Processor' => EE_Dependency_Map::load_from_cache,
916
-            ],
917
-            'EventEspresso\core\services\payments\PaymentProcessorFees' => [
918
-                'EventEspresso\core\domain\values\gateways\GracePeriod'    => EE_Dependency_Map::load_from_cache,
919
-                'EventEspresso\core\domain\services\licensing\LicenseData' => EE_Dependency_Map::load_from_cache,
920
-            ],
921
-            'EventEspresso\core\domain\services\licensing\LicenseData'  => [
922
-                'EventEspresso\core\domain\Domain'                             => EE_Dependency_Map::load_from_cache,
923
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
924
-            ],
925
-            'EventEspresso\core\domain\services\licensing\LicenseDataEDD' => [
926
-                'EventEspresso\core\services\licensing\LicenseKeyData' => EE_Dependency_Map::load_from_cache,
927
-            ],
928
-            'EventEspresso\core\domain\services\licensing\LicenseDataPue' => [
929
-                'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
930
-            ],
931
-            'EventEspresso\core\services\addon\api\DependencyHandlers' => [
932
-                'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
933
-            ],
934
-            'EventEspresso\core\services\addon\api\AddonRoutes' => [
935
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
936
-            ],
937
-        ];
938
-    }
939
-
940
-
941
-    /**
942
-     * Registers how core classes are loaded.
943
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
944
-     *        'EE_Request_Handler' => 'load_core'
945
-     *        'EE_Messages_Queue'  => 'load_lib'
946
-     *        'EEH_Debug_Tools'    => 'load_helper'
947
-     * or, if greater control is required, by providing a custom closure. For example:
948
-     *        'Some_Class' => function () {
949
-     *            return new Some_Class();
950
-     *        },
951
-     * This is required for instantiating dependencies
952
-     * where an interface has been type hinted in a class constructor. For example:
953
-     *        'Required_Interface' => function () {
954
-     *            return new A_Class_That_Implements_Required_Interface();
955
-     *        },
956
-     */
957
-    protected function _register_core_class_loaders()
958
-    {
959
-        $this->_class_loaders = [
960
-            // load_core
961
-            'EE_Dependency_Map'                            => function () {
962
-                return $this;
963
-            },
964
-            'EE_Capabilities'                              => 'load_core',
965
-            'EE_Encryption'                                => 'load_core',
966
-            'EE_Front_Controller'                          => 'load_core',
967
-            'EE_Module_Request_Router'                     => 'load_core',
968
-            'EE_Registry'                                  => 'load_core',
969
-            'EE_Request'                                   => function () {
970
-                return $this->legacy_request;
971
-            },
972
-            'EventEspresso\core\services\request\Request'  => function () {
973
-                return $this->request;
974
-            },
975
-            'EventEspresso\core\services\request\Response' => function () {
976
-                return $this->response;
977
-            },
978
-            'EE_Base'                                      => 'load_core',
979
-            'EE_Request_Handler'                           => 'load_core',
980
-            'EE_Session'                                   => 'load_core',
981
-            'EE_Cron_Tasks'                                => 'load_core',
982
-            'EE_System'                                    => 'load_core',
983
-            'EE_Maintenance_Mode'                          => 'load_core',
984
-            'EE_Register_CPTs'                             => 'load_core',
985
-            'EE_Admin'                                     => 'load_core',
986
-            'EE_CPT_Strategy'                              => 'load_core',
987
-            // load_class
988
-            'EE_Registration_Processor'                    => 'load_class',
989
-            'EE_Transaction_Payments'                      => 'load_class',
990
-            'EE_Transaction_Processor'                     => 'load_class',
991
-            // load_lib
992
-            'EE_Message_Resource_Manager'                  => 'load_lib',
993
-            'EE_Message_Type_Collection'                   => 'load_lib',
994
-            'EE_Message_Type_Collection_Loader'            => 'load_lib',
995
-            'EE_Messenger_Collection'                      => 'load_lib',
996
-            'EE_Messenger_Collection_Loader'               => 'load_lib',
997
-            'EE_Messages_Processor'                        => 'load_lib',
998
-            'EE_Message_Repository'                        => 'load_lib',
999
-            'EE_Messages_Queue'                            => 'load_lib',
1000
-            'EE_Messages_Data_Handler_Collection'          => 'load_lib',
1001
-            'EE_Message_Template_Group_Collection'         => 'load_lib',
1002
-            'EE_Payment_Method_Manager'                    => 'load_lib',
1003
-            'EE_Payment_Processor'                         => 'load_core',
1004
-            'EE_DMS_Core_4_1_0'                            => 'load_dms',
1005
-            'EE_DMS_Core_4_2_0'                            => 'load_dms',
1006
-            'EE_DMS_Core_4_3_0'                            => 'load_dms',
1007
-            'EE_DMS_Core_4_5_0'                            => 'load_dms',
1008
-            'EE_DMS_Core_4_6_0'                            => 'load_dms',
1009
-            'EE_DMS_Core_4_7_0'                            => 'load_dms',
1010
-            'EE_DMS_Core_4_8_0'                            => 'load_dms',
1011
-            'EE_DMS_Core_4_9_0'                            => 'load_dms',
1012
-            'EE_DMS_Core_4_10_0'                           => 'load_dms',
1013
-            'EE_DMS_Core_5_0_0'                            => 'load_dms',
1014
-            'EE_Messages_Generator'                        => static function () {
1015
-                return EE_Registry::instance()->load_lib(
1016
-                    'Messages_Generator',
1017
-                    [],
1018
-                    false,
1019
-                    false
1020
-                );
1021
-            },
1022
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
1023
-                return EE_Registry::instance()->load_lib(
1024
-                    'Messages_Template_Defaults',
1025
-                    $arguments,
1026
-                    false,
1027
-                    false
1028
-                );
1029
-            },
1030
-            // load_helper
1031
-            'EEH_Parse_Shortcodes'                         => static function () {
1032
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
1033
-                    return new EEH_Parse_Shortcodes();
1034
-                }
1035
-                return null;
1036
-            },
1037
-            'EE_Template_Config'                           => static function () {
1038
-                return EE_Config::instance()->template_settings;
1039
-            },
1040
-            'EE_Currency_Config'                           => static function () {
1041
-                return EE_Currency_Config::getCurrencyConfig();
1042
-            },
1043
-            'EE_Registration_Config'                       => static function () {
1044
-                return EE_Config::instance()->registration;
1045
-            },
1046
-            'EE_Core_Config'                               => static function () {
1047
-                return EE_Config::instance()->core;
1048
-            },
1049
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
1050
-                return LoaderFactory::getLoader();
1051
-            },
1052
-            'EE_Network_Config'                            => static function () {
1053
-                return EE_Network_Config::instance();
1054
-            },
1055
-            'EE_Config'                                    => static function () {
1056
-                return EE_Config::instance();
1057
-            },
1058
-            'EventEspresso\core\domain\Domain'             => static function () {
1059
-                return DomainFactory::getEventEspressoCoreDomain();
1060
-            },
1061
-            'EE_Admin_Config'                              => static function () {
1062
-                return EE_Config::instance()->admin;
1063
-            },
1064
-            'EE_Organization_Config'                       => static function () {
1065
-                return EE_Config::instance()->organization;
1066
-            },
1067
-            'EE_Network_Core_Config'                       => static function () {
1068
-                return EE_Network_Config::instance()->core;
1069
-            },
1070
-            'EE_Environment_Config'                        => static function () {
1071
-                return EE_Config::instance()->environment;
1072
-            },
1073
-            'EED_Core_Rest_Api'                            => static function () {
1074
-                return EED_Core_Rest_Api::instance();
1075
-            },
1076
-            'WP_REST_Server'                               => static function () {
1077
-                return rest_get_server();
1078
-            },
1079
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
1080
-                return EE_Psr4AutoloaderInit::psr4_loader();
1081
-            },
1082
-            'EE_Ticket_Selector_Config'                    => function () {
1083
-                return EE_Config::instance()->template_settings->EED_Ticket_Selector;
1084
-            },
1085
-        ];
1086
-    }
1087
-
1088
-
1089
-    /**
1090
-     * can be used for supplying alternate names for classes,
1091
-     * or for connecting interface names to instantiable classes
1092
-     *
1093
-     * @throws InvalidAliasException
1094
-     */
1095
-    protected function _register_core_aliases()
1096
-    {
1097
-        $aliases = [
1098
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
1099
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
1100
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
1101
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
1102
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
1103
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
1104
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1105
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
1106
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1107
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
1108
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommand',
1109
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommand',
1110
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommand',
1111
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
1112
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
1113
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommand',
1114
-            'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\domain\services\commands\transaction\CreateTransactionCommandHandler',
1115
-            'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler',
1116
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
1117
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
1118
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1119
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
1120
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1121
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
1122
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
1123
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
1124
-            'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
1125
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
1126
-            'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
1127
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
1128
-            'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
1129
-            'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
1130
-            'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
1131
-            'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
1132
-            'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
1133
-            'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1134
-            'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1135
-            'Registration_Processor'                                                       => 'EE_Registration_Processor',
1136
-            'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1137
-        ];
1138
-        foreach ($aliases as $alias => $fqn) {
1139
-            if (is_array($fqn)) {
1140
-                foreach ($fqn as $class => $for_class) {
1141
-                    $this->class_cache->addAlias($class, $alias, $for_class);
1142
-                }
1143
-                continue;
1144
-            }
1145
-            $this->class_cache->addAlias($fqn, $alias);
1146
-        }
1147
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1148
-            $this->class_cache->addAlias(
1149
-                'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1150
-                'EventEspresso\core\services\notices\NoticeConverterInterface'
1151
-            );
1152
-        }
1153
-    }
1154
-
1155
-
1156
-    public function debug($for_class = '')
1157
-    {
1158
-        if (method_exists($this->class_cache, 'debug')) {
1159
-            $this->class_cache->debug($for_class);
1160
-        }
1161
-    }
1162
-
1163
-
1164
-    /**
1165
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1166
-     * request Primarily used by unit tests.
1167
-     */
1168
-    public function reset()
1169
-    {
1170
-        $this->_register_core_class_loaders();
1171
-        $this->_register_core_dependencies();
1172
-    }
1173
-
1174
-
1175
-    /**
1176
-     * PLZ NOTE: a better name for this method would be is_alias()
1177
-     * because it returns TRUE if the provided fully qualified name IS an alias
1178
-     * WHY?
1179
-     * Because if a class is type hinting for a concretion,
1180
-     * then why would we need to find another class to supply it?
1181
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1182
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1183
-     * Don't go looking for some substitute.
1184
-     * Whereas if a class is type hinting for an interface...
1185
-     * then we need to find an actual class to use.
1186
-     * So the interface IS the alias for some other FQN,
1187
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1188
-     * represents some other class.
1189
-     *
1190
-     * @param string $fqn
1191
-     * @param string $for_class
1192
-     * @return bool
1193
-     * @deprecated 4.9.62.p
1194
-     */
1195
-    public function has_alias(string $fqn = '', string $for_class = ''): bool
1196
-    {
1197
-        return $this->isAlias($fqn, $for_class);
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1203
-     * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1204
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
1205
-     *  for example:
1206
-     *      if the following two entries were added to the _aliases array:
1207
-     *          array(
1208
-     *              'interface_alias'           => 'some\namespace\interface'
1209
-     *              'some\namespace\interface'  => 'some\namespace\classname'
1210
-     *          )
1211
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1212
-     *      to load an instance of 'some\namespace\classname'
1213
-     *
1214
-     * @param string $alias
1215
-     * @param string $for_class
1216
-     * @return string
1217
-     * @deprecated 4.9.62.p
1218
-     */
1219
-    public function get_alias(string $alias = '', string $for_class = ''): string
1220
-    {
1221
-        return $this->getFqnForAlias($alias, $for_class);
1222
-    }
23
+	/**
24
+	 * This means that the requested class dependency is not present in the dependency map
25
+	 */
26
+	const not_registered = 0;
27
+
28
+	/**
29
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
30
+	 */
31
+	const load_new_object = 1;
32
+
33
+	/**
34
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
35
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
36
+	 */
37
+	const load_from_cache = 2;
38
+
39
+	/**
40
+	 * When registering a dependency,
41
+	 * this indicates to keep any existing dependencies that already exist,
42
+	 * and simply discard any new dependencies declared in the incoming data
43
+	 */
44
+	const KEEP_EXISTING_DEPENDENCIES = 0;
45
+
46
+	/**
47
+	 * When registering a dependency,
48
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
49
+	 */
50
+	const OVERWRITE_DEPENDENCIES = 1;
51
+
52
+	protected static ?EE_Dependency_Map $_instance = null;
53
+
54
+	private ClassInterfaceCache $class_cache;
55
+
56
+	protected ?RequestInterface $request = null;
57
+
58
+	protected ?LegacyRequestInterface $legacy_request = null;
59
+
60
+	protected ?ResponseInterface $response = null;
61
+
62
+	protected ?LoaderInterface $loader = null;
63
+
64
+	protected array $_dependency_map = [];
65
+
66
+	protected array $_class_loaders = [];
67
+
68
+
69
+	/**
70
+	 * EE_Dependency_Map constructor.
71
+	 *
72
+	 * @param ClassInterfaceCache $class_cache
73
+	 */
74
+	protected function __construct(ClassInterfaceCache $class_cache)
75
+	{
76
+		$this->class_cache = $class_cache;
77
+		do_action('EE_Dependency_Map____construct', $this);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @return void
83
+	 * @throws InvalidAliasException
84
+	 */
85
+	public function initialize()
86
+	{
87
+		$this->_register_core_dependencies();
88
+		$this->_register_core_class_loaders();
89
+		$this->_register_core_aliases();
90
+	}
91
+
92
+
93
+	/**
94
+	 * @singleton method used to instantiate class object
95
+	 * @param ClassInterfaceCache|null $class_cache
96
+	 * @return EE_Dependency_Map
97
+	 */
98
+	public static function instance(ClassInterfaceCache $class_cache = null): EE_Dependency_Map
99
+	{
100
+		// check if class object is instantiated, and instantiated properly
101
+		if (
102
+			! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
103
+			&& $class_cache instanceof ClassInterfaceCache
104
+		) {
105
+			EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
106
+		}
107
+		return EE_Dependency_Map::$_instance;
108
+	}
109
+
110
+
111
+	/**
112
+	 * @param RequestInterface $request
113
+	 */
114
+	public function setRequest(RequestInterface $request)
115
+	{
116
+		$this->request = $request;
117
+	}
118
+
119
+
120
+	/**
121
+	 * @param LegacyRequestInterface $legacy_request
122
+	 */
123
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
124
+	{
125
+		$this->legacy_request = $legacy_request;
126
+	}
127
+
128
+
129
+	/**
130
+	 * @param ResponseInterface $response
131
+	 */
132
+	public function setResponse(ResponseInterface $response)
133
+	{
134
+		$this->response = $response;
135
+	}
136
+
137
+
138
+	/**
139
+	 * @param LoaderInterface $loader
140
+	 */
141
+	public function setLoader(LoaderInterface $loader)
142
+	{
143
+		$this->loader = $loader;
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param string $class
149
+	 * @param array  $dependencies
150
+	 * @param int    $overwrite
151
+	 * @return bool
152
+	 */
153
+	public static function register_dependencies(
154
+		string $class,
155
+		array $dependencies,
156
+		int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
157
+	): bool {
158
+		return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Assigns an array of class names and corresponding load sources (new or cached)
164
+	 * to the class specified by the first parameter.
165
+	 * IMPORTANT !!!
166
+	 * The order of elements in the incoming $dependencies array MUST match
167
+	 * the order of the constructor parameters for the class in question.
168
+	 * This is especially important when overriding any existing dependencies that are registered.
169
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
170
+	 *
171
+	 * @param string $class
172
+	 * @param array  $dependencies
173
+	 * @param int    $overwrite
174
+	 * @return bool
175
+	 */
176
+	public function registerDependencies(
177
+		string $class,
178
+		array $dependencies,
179
+		int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
180
+	): bool {
181
+		if (empty($dependencies)) {
182
+			return false;
183
+		}
184
+		$class      = trim($class, '\\');
185
+		$registered = false;
186
+		if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
187
+			EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
188
+		}
189
+		// we need to make sure that any aliases used when registering a dependency
190
+		// get resolved to the correct class name
191
+		foreach ($dependencies as $dependency => $load_source) {
192
+			$alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
193
+			if (
194
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
195
+				|| ! isset(
196
+					EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $dependency ],
197
+					EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ]
198
+				)
199
+			) {
200
+				unset($dependencies[ $dependency ]);
201
+				$dependencies[ $alias ] = $load_source;
202
+				$registered             = true;
203
+			}
204
+		}
205
+		// now add our two lists of dependencies together.
206
+		// using Union (+=) favours the arrays in precedence from left to right,
207
+		// so $dependencies is NOT overwritten because it is listed first
208
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
209
+		// Union is way faster than array_merge() but should be used with caution...
210
+		// especially with numerically indexed arrays
211
+		$dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
212
+		// now we need to ensure that the resulting dependencies
213
+		// array only has the entries that are required for the class
214
+		// so first count how many dependencies were originally registered for the class
215
+		$dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
216
+		// if that count is non-zero (meaning dependencies were already registered)
217
+		EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
218
+			// then truncate the  final array to match that count
219
+			? array_slice($dependencies, 0, $dependency_count)
220
+			// otherwise just take the incoming array because nothing previously existed
221
+			: $dependencies;
222
+		return $registered
223
+			|| count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]) === count($dependencies);
224
+	}
225
+
226
+
227
+	/**
228
+	 * @param string          $class_name
229
+	 * @param callable|string $loader
230
+	 * @param bool            $overwrite
231
+	 * @return bool
232
+	 * @throws DomainException
233
+	 */
234
+	public static function register_class_loader(
235
+		string $class_name,
236
+		$loader = 'load_core',
237
+		bool $overwrite = false
238
+	): bool {
239
+		return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader, $overwrite);
240
+	}
241
+
242
+
243
+	/**
244
+	 * @param string         $class_name
245
+	 * @param Closure|string $loader
246
+	 * @param bool           $overwrite
247
+	 * @return bool
248
+	 * @throws DomainException
249
+	 */
250
+	public function registerClassLoader(string $class_name, $loader = 'load_core', bool $overwrite = false): bool
251
+	{
252
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
253
+			throw new DomainException(
254
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
255
+			);
256
+		}
257
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
258
+		if (
259
+			! is_callable($loader)
260
+			&& (
261
+				strpos($loader, 'load_') !== 0
262
+				|| ! method_exists('EE_Registry', $loader)
263
+			)
264
+		) {
265
+			throw new DomainException(
266
+				sprintf(
267
+					esc_html__(
268
+						'"%1$s" is not a valid loader method on EE_Registry.',
269
+						'event_espresso'
270
+					),
271
+					$loader
272
+				)
273
+			);
274
+		}
275
+		$class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
276
+		if ($overwrite || ! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
277
+			EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
278
+			return true;
279
+		}
280
+		return false;
281
+	}
282
+
283
+
284
+	/**
285
+	 * @return array
286
+	 */
287
+	public function dependency_map(): array
288
+	{
289
+		return $this->_dependency_map;
290
+	}
291
+
292
+
293
+	/**
294
+	 * returns TRUE if dependency map contains a listing for the provided class name
295
+	 *
296
+	 * @param string $class_name
297
+	 * @return boolean
298
+	 */
299
+	public function has(string $class_name = ''): bool
300
+	{
301
+		// all legacy models have the same dependencies
302
+		if (strpos($class_name, 'EEM_') === 0) {
303
+			$class_name = 'LEGACY_MODELS';
304
+		}
305
+		return isset($this->_dependency_map[ $class_name ]);
306
+	}
307
+
308
+
309
+	/**
310
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
311
+	 *
312
+	 * @param string $class_name
313
+	 * @param string $dependency
314
+	 * @return bool
315
+	 */
316
+	public function has_dependency_for_class(string $class_name = '', string $dependency = ''): bool
317
+	{
318
+		// all legacy models have the same dependencies
319
+		if (strpos($class_name, 'EEM_') === 0) {
320
+			$class_name = 'LEGACY_MODELS';
321
+		}
322
+		$dependency = $this->getFqnForAlias($dependency, $class_name);
323
+		return isset($this->_dependency_map[ $class_name ][ $dependency ]);
324
+	}
325
+
326
+
327
+	/**
328
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
329
+	 *
330
+	 * @param string $class_name
331
+	 * @param string $dependency
332
+	 * @return int
333
+	 */
334
+	public function loading_strategy_for_class_dependency(string $class_name = '', string $dependency = ''): int
335
+	{
336
+		// all legacy models have the same dependencies
337
+		if (strpos($class_name, 'EEM_') === 0) {
338
+			$class_name = 'LEGACY_MODELS';
339
+		}
340
+		$dependency = $this->getFqnForAlias($dependency);
341
+		return $this->has_dependency_for_class($class_name, $dependency)
342
+			? $this->_dependency_map[ $class_name ][ $dependency ]
343
+			: EE_Dependency_Map::not_registered;
344
+	}
345
+
346
+
347
+	/**
348
+	 * @param string $class_name
349
+	 * @return string | Closure
350
+	 */
351
+	public function class_loader(string $class_name)
352
+	{
353
+		// all legacy models use load_model()
354
+		if (strpos($class_name, 'EEM_') === 0) {
355
+			return 'load_model';
356
+		}
357
+		// EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
358
+		// perform strpos() first to avoid loading regex every time we load a class
359
+		if (
360
+			strpos($class_name, 'EE_CPT_') === 0
361
+			&& preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
362
+		) {
363
+			return 'load_core';
364
+		}
365
+		$class_name = $this->getFqnForAlias($class_name);
366
+		return $this->_class_loaders[ $class_name ] ?? '';
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return array
372
+	 */
373
+	public function class_loaders(): array
374
+	{
375
+		return $this->_class_loaders;
376
+	}
377
+
378
+
379
+	/**
380
+	 * adds an alias for a classname
381
+	 *
382
+	 * @param string $fqcn      the class name that should be used (concrete class to replace interface)
383
+	 * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
384
+	 * @param string $for_class the class that has the dependency (is type hinting for the interface)
385
+	 * @throws InvalidAliasException
386
+	 */
387
+	public function add_alias(string $fqcn, string $alias, string $for_class = '')
388
+	{
389
+		$this->class_cache->addAlias($fqcn, $alias, $for_class);
390
+	}
391
+
392
+
393
+	/**
394
+	 * Returns TRUE if the provided fully qualified name IS an alias
395
+	 * WHY?
396
+	 * Because if a class is type hinting for a concretion,
397
+	 * then why would we need to find another class to supply it?
398
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
399
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
400
+	 * Don't go looking for some substitute.
401
+	 * Whereas if a class is type hinting for an interface...
402
+	 * then we need to find an actual class to use.
403
+	 * So the interface IS the alias for some other FQN,
404
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
405
+	 * represents some other class.
406
+	 *
407
+	 * @param string $fqn
408
+	 * @param string $for_class
409
+	 * @return bool
410
+	 */
411
+	public function isAlias(string $fqn = '', string $for_class = ''): bool
412
+	{
413
+		return $this->class_cache->isAlias($fqn, $for_class);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
419
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
420
+	 *  for example:
421
+	 *      if the following two entries were added to the _aliases array:
422
+	 *          array(
423
+	 *              'interface_alias'           => 'some\namespace\interface'
424
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
425
+	 *          )
426
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
427
+	 *      to load an instance of 'some\namespace\classname'
428
+	 *
429
+	 * @param string $alias
430
+	 * @param string $for_class
431
+	 * @return string
432
+	 */
433
+	public function getFqnForAlias(string $alias = '', string $for_class = ''): string
434
+	{
435
+		return $this->class_cache->getFqnForAlias($alias, $for_class);
436
+	}
437
+
438
+
439
+	/**
440
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
441
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
442
+	 * This is done by using the following class constants:
443
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
444
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
445
+	 */
446
+	protected function _register_core_dependencies()
447
+	{
448
+		$this->_dependency_map = [
449
+			'EE_Admin'                                                                                                           => [
450
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
451
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
452
+			],
453
+			'EE_Maintenance_Mode'                                                                                                => [
454
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
455
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
456
+			],
457
+			'EE_Request_Handler'                                                                                                 => [
458
+				'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
459
+				'EventEspresso\core\services\request\Response' => EE_Dependency_Map::load_from_cache,
460
+			],
461
+			'EE_System'                                                                                                   => [
462
+				'EventEspresso\core\services\loaders\Loader'                   => EE_Dependency_Map::load_from_cache,
463
+				'EE_Maintenance_Mode'                                          => EE_Dependency_Map::load_from_cache,
464
+				'EE_Registry'                                                  => EE_Dependency_Map::load_from_cache,
465
+				'EventEspresso\core\services\request\Request'                  => EE_Dependency_Map::load_from_cache,
466
+				'EventEspresso\core\services\routing\Router'                   => EE_Dependency_Map::load_from_cache,
467
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
468
+			],
469
+			'EE_Session'                                                                                                         => [
470
+				'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
471
+				'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
472
+				'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
473
+				'EventEspresso\core\services\session\SessionStartHandler'  => EE_Dependency_Map::load_from_cache,
474
+				'EventEspresso\core\services\encryption\Base64Encoder'     => EE_Dependency_Map::load_from_cache,
475
+			],
476
+			'EventEspresso\core\services\session\SessionStartHandler'                                                            => [
477
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
478
+			],
479
+			'EE_Cart'                                                                                                            => [
480
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
481
+			],
482
+			'EE_Messenger_Collection_Loader'                                                                                     => [
483
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
484
+			],
485
+			'EE_Message_Type_Collection_Loader'                                                                                  => [
486
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
487
+			],
488
+			'EE_Message_Resource_Manager'                                                                                        => [
489
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
490
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
491
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
492
+			],
493
+			'EE_Message_Factory'                                                                                                 => [
494
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
+			],
496
+			'EE_messages'                                                                                                        => [
497
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
498
+			],
499
+			'EE_Messages_Generator'                                                                                              => [
500
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
501
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
502
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
503
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
504
+			],
505
+			'EE_Messages_Processor'                                                                                              => [
506
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
507
+			],
508
+			'EE_Messages_Queue'                                                                                                  => [
509
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
510
+			],
511
+			'EE_Messages_Template_Defaults'                                                                                      => [
512
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
513
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
514
+			],
515
+			'EE_Message_To_Generate_From_Request'                                                                                => [
516
+				'EE_Message_Resource_Manager'                 => EE_Dependency_Map::load_from_cache,
517
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
518
+			],
519
+			'EventEspresso\core\services\commands\CommandBus'                                                                    => [
520
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
521
+			],
522
+			'EventEspresso\services\commands\CommandHandler'                                                                     => [
523
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
524
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
525
+			],
526
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                         => [
527
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
528
+			],
529
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                       => [
530
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
531
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
532
+			],
533
+			'EventEspresso\core\services\commands\CommandFactory'                                                                => [
534
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
535
+			],
536
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                         => [
537
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
538
+			],
539
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                                => [
540
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
+			],
542
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                            => [
543
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
544
+			],
545
+			'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommandHandler'                          => [
546
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
547
+			],
548
+			'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
549
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
+			],
551
+			'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
552
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
553
+			],
554
+			'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
555
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
556
+			],
557
+			'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
558
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
559
+			],
560
+			'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
561
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
+			],
563
+			'EventEspresso\core\domain\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
564
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
+			],
566
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                          => [
567
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
+			],
569
+			'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
570
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
571
+			],
572
+			'EventEspresso\core\domain\values\session\SessionLifespan'                                                           => [
573
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
574
+			],
575
+			'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanForm'                                 => [
576
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
577
+				'EE_Registration_Config'                                         => EE_Dependency_Map::load_from_cache,
578
+			],
579
+			'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanFormHandler'                          => [
580
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
581
+				'EE_Config'                                                      => EE_Dependency_Map::load_from_cache,
582
+			],
583
+			'EventEspresso\core\services\database\TableManager'                                                                  => [
584
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
585
+			],
586
+			'EE_Data_Migration_Class_Base'                                                                                       => [
587
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
+			],
590
+			'EE_DMS_Core_4_1_0'                                                                                                  => [
591
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
+			],
594
+			'EE_DMS_Core_4_2_0'                                                                                                  => [
595
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
596
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
597
+			],
598
+			'EE_DMS_Core_4_3_0'                                                                                                  => [
599
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
600
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
601
+			],
602
+			'EE_DMS_Core_4_4_0'                                                                                                  => [
603
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
604
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
605
+			],
606
+			'EE_DMS_Core_4_5_0'                                                                                                  => [
607
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
608
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
609
+			],
610
+			'EE_DMS_Core_4_6_0'                                                                                                  => [
611
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
612
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
613
+			],
614
+			'EE_DMS_Core_4_7_0'                                                                                                  => [
615
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
616
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
617
+			],
618
+			'EE_DMS_Core_4_8_0'                                                                                                  => [
619
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
+			],
622
+			'EE_DMS_Core_4_9_0'                                                                                                  => [
623
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
624
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
625
+			],
626
+			'EE_DMS_Core_4_10_0'                                                                                                 => [
627
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
628
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
629
+				'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
630
+			],
631
+			'EE_DMS_Core_5_0_0'                                                                                                  => [
632
+				'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
633
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
634
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
635
+			],
636
+			'EventEspresso\core\services\assets\I18nRegistry'                                                                    => [
637
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
638
+			],
639
+			'EventEspresso\core\services\assets\Registry'                                                                        => [
640
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
641
+				'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
642
+			],
643
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                                    => [
644
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
+			],
646
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                                     => [
647
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
+			],
649
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                               => [
650
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
+			],
652
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                       => [
653
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
654
+			],
655
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                                     => [
656
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
657
+			],
658
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                               => [
659
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
660
+			],
661
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                                      => [
662
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
663
+			],
664
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                                => [
665
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
666
+			],
667
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                          => [
668
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
669
+			],
670
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                         => [
671
+				'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
672
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
673
+			],
674
+			'EventEspresso\core\domain\values\EmailAddress'                                                                      => [
675
+				null,
676
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
677
+			],
678
+			'EventEspresso\core\services\orm\ModelFieldFactory'                                                                  => [
679
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
680
+			],
681
+			'LEGACY_MODELS'                                                                                                      => [
682
+				null,
683
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
684
+			],
685
+			'EE_Module_Request_Router'                                                                                           => [
686
+				'EventEspresso\core\services\request\Request'             => EE_Dependency_Map::load_from_cache,
687
+				'EventEspresso\core\services\modules\ModuleRoutesManager' => EE_Dependency_Map::load_from_cache,
688
+			],
689
+			'EE_Registration_Processor'                                                                                          => [
690
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
691
+			],
692
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                             => [
693
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
694
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
695
+			],
696
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                           => [
697
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
698
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
699
+			],
700
+			'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                        => [
701
+				'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
702
+				'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
703
+				'EE_Ticket_Selector_Config'                            => EE_Dependency_Map::load_from_cache,
704
+			],
705
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                        => [
706
+				'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
707
+				'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
708
+				'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
709
+				'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
710
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
711
+			],
712
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelectorPostData'                                                => [
713
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
714
+				'EEM_Event'                                   => EE_Dependency_Map::load_from_cache,
715
+			],
716
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                            => [
717
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
718
+			],
719
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                                     => [
720
+				'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
721
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
722
+			],
723
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                       => [
724
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
725
+			],
726
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                                      => [
727
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
728
+			],
729
+			'EE_CPT_Strategy'                                                                                                    => [
730
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
731
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
732
+			],
733
+			'EventEspresso\core\services\loaders\ObjectIdentifier'                                                               => [
734
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
735
+			],
736
+			'EventEspresso\core\CPTs\CptQueryModifier'                                                                           => [
737
+				null,
738
+				null,
739
+				null,
740
+				'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
741
+				'EventEspresso\core\services\request\Request'     => EE_Dependency_Map::load_from_cache,
742
+				'EventEspresso\core\services\loaders\Loader'      => EE_Dependency_Map::load_from_cache,
743
+			],
744
+			'EventEspresso\core\services\dependencies\DependencyResolver'                                                        => [
745
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
746
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
747
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
748
+			],
749
+			'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                                      => [
750
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
751
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
752
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
753
+			],
754
+			'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                                 => [
755
+				'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
756
+				'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
757
+			],
758
+			'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                                 => [
759
+				'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
760
+				'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
761
+			],
762
+			'EventEspresso\core\services\request\files\FilesDataHandler'                                                         => [
763
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
764
+			],
765
+			'EventEspresso\core\libraries\batch\BatchRequestProcessor'                                                           => [
766
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
767
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
768
+			],
769
+			'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                       => [
770
+				'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
771
+				'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
772
+				'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
773
+				null,
774
+			],
775
+			'EventEspresso\core\services\routing\RouteHandler'                                                                   => [
776
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
777
+				'EventEspresso\core\services\json\JsonDataNodeHandler'                => EE_Dependency_Map::load_from_cache,
778
+				'EventEspresso\core\services\loaders\Loader'                          => EE_Dependency_Map::load_from_cache,
779
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
780
+				'EventEspresso\core\services\routing\RouteCollection'                 => EE_Dependency_Map::load_from_cache,
781
+			],
782
+			'EventEspresso\core\services\json\JsonDataNodeHandler'                                                               => [
783
+				'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
784
+			],
785
+			'EventEspresso\core\services\routing\Router'                                                                         => [
786
+				'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
787
+				'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
788
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
789
+			],
790
+			'EventEspresso\core\services\assets\AssetManifest'                                                                   => [
791
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
792
+			],
793
+			'EventEspresso\core\services\assets\AssetManifestFactory'                                                            => [
794
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
795
+			],
796
+			'EventEspresso\core\services\assets\BaristaFactory'                                                                  => [
797
+				'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
798
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
799
+			],
800
+			'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig' => [
801
+				'EventEspresso\core\domain\Domain'                                    => EE_Dependency_Map::load_from_cache,
802
+				'EventEspresso\core\services\json\JsonDataHandler'                    => EE_Dependency_Map::load_from_cache,
803
+			],
804
+			'EventEspresso\core\domain\services\capabilities\FeatureFlags'       => [
805
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
806
+				'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig'  => EE_Dependency_Map::load_from_cache,
807
+			],
808
+			'EventEspresso\core\services\addon\AddonManager'                                                                     => [
809
+				'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
810
+				'EE_Dependency_Map'                                              => EE_Dependency_Map::load_from_cache,
811
+				'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
812
+				'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
813
+				'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
814
+			],
815
+			'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'                                                      => [
816
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
817
+			],
818
+			'EventEspresso\core\libraries\batch\JobHandlers\ExecuteBatchDeletion'                                                => [
819
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
820
+			],
821
+			'EventEspresso\core\libraries\batch\JobHandlers\PreviewEventDeletion'                                                => [
822
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
823
+			],
824
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'                                               => [
825
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
826
+				'EEM_Event'                                                   => EE_Dependency_Map::load_from_cache,
827
+				'EEM_Datetime'                                                => EE_Dependency_Map::load_from_cache,
828
+				'EEM_Registration'                                            => EE_Dependency_Map::load_from_cache,
829
+			],
830
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'                                               => [
831
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
832
+			],
833
+			'EventEspresso\core\services\request\CurrentPage'                                                                    => [
834
+				'EE_CPT_Strategy'                             => EE_Dependency_Map::load_from_cache,
835
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
836
+			],
837
+			'EventEspresso\core\services\shortcodes\LegacyShortcodesManager'                                                     => [
838
+				'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
839
+				'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
840
+			],
841
+			'EventEspresso\core\services\shortcodes\ShortcodesManager'                                                           => [
842
+				'EventEspresso\core\services\shortcodes\LegacyShortcodesManager' => EE_Dependency_Map::load_from_cache,
843
+				'EventEspresso\core\services\request\CurrentPage'                => EE_Dependency_Map::load_from_cache,
844
+			],
845
+			'EventEspresso\core\domain\entities\users\CurrentUser'                                                               => [
846
+				'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
847
+			],
848
+			'EventEspresso\core\services\form\meta\InputTypes'                                                                   => [
849
+				'EventEspresso\core\services\form\meta\inputs\Block'    => EE_Dependency_Map::load_from_cache,
850
+				'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
851
+				'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
852
+				'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
853
+				'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
854
+				'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
855
+				'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
856
+				'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
857
+			],
858
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler'                                   => [
859
+				'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
860
+			],
861
+			'EventEspresso\core\services\calculators\LineItemCalculator'                                                         => [
862
+				'EventEspresso\core\services\helpers\DecimalValues' => EE_Dependency_Map::load_from_cache,
863
+			],
864
+			'EventEspresso\core\services\helpers\DecimalValues'                                                                  => [
865
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
866
+			],
867
+			'EE_Brewing_Regular'                                                                                                 => [
868
+				'EE_Dependency_Map'                                  => EE_Dependency_Map::load_from_cache,
869
+				'EventEspresso\core\services\loaders\Loader'         => EE_Dependency_Map::load_from_cache,
870
+				'EventEspresso\core\services\routing\RouteHandler'   => EE_Dependency_Map::load_from_cache,
871
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
872
+			],
873
+			'EventEspresso\core\domain\services\messages\MessageTemplateRequestData'                                             => [
874
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
875
+			],
876
+			'EventEspresso\core\domain\services\messages\MessageTemplateValidator'                                               => [
877
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
878
+			],
879
+			'EventEspresso\core\domain\services\messages\MessageTemplateManager'                                                 => [
880
+				'EEM_Message_Template'                                                   => EE_Dependency_Map::load_from_cache,
881
+				'EEM_Message_Template_Group'                                             => EE_Dependency_Map::load_from_cache,
882
+				'EventEspresso\core\domain\services\messages\MessageTemplateRequestData' => EE_Dependency_Map::load_from_cache,
883
+				'EventEspresso\core\domain\services\messages\MessageTemplateValidator'   => EE_Dependency_Map::load_from_cache,
884
+				'EventEspresso\core\services\request\Request'                            => EE_Dependency_Map::load_from_cache,
885
+			],
886
+			'EventEspresso\core\services\request\sanitizers\RequestSanitizer'                                                    => [
887
+				'EventEspresso\core\domain\services\validation\email\strategies\Basic' => EE_Dependency_Map::load_from_cache,
888
+			],
889
+			'EE_CPT_Event_Strategy'                                                    => [
890
+				null,
891
+				null,
892
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
893
+			],
894
+			'EventEspresso\core\domain\services\licensing\LicenseKeyFormInput'                                                    => [
895
+				'EventEspresso\core\services\licensing\PluginLicense'  => EE_Dependency_Map::not_registered,
896
+				'EventEspresso\core\services\licensing\LicenseManager' => EE_Dependency_Map::load_from_cache,
897
+			],
898
+			'EventEspresso\core\services\payments\IpnHandler' => [
899
+				'EEM_Payment_Method'                                    => EE_Dependency_Map::not_registered,
900
+				'EEM_Transaction'                                       => EE_Dependency_Map::load_from_cache,
901
+				'EE_Core_Config'                                        => EE_Dependency_Map::load_from_cache,
902
+				'EE_Organization_Config'                                => EE_Dependency_Map::load_from_cache,
903
+				'EventEspresso\core\services\payments\PaymentProcessor' => EE_Dependency_Map::load_from_cache,
904
+			],
905
+			'EventEspresso\core\services\payments\PaymentProcessor' => [
906
+				'EEM_Payment_Method'                                           => EE_Dependency_Map::not_registered,
907
+				'EEM_Transaction'                                              => EE_Dependency_Map::load_from_cache,
908
+				'EE_Organization_Config'                                       => EE_Dependency_Map::load_from_cache,
909
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
910
+				'EventEspresso\core\services\payments\PaymentProcessorFees'    => EE_Dependency_Map::load_from_cache,
911
+				'EventEspresso\core\services\payments\PostPaymentProcessor'    => EE_Dependency_Map::load_from_cache,
912
+				'EventEspresso\core\services\payments\RegistrationPayments'    => EE_Dependency_Map::load_from_cache,
913
+			],
914
+			'EventEspresso\core\services\payments\PostPaymentProcessor' => [
915
+				'EE_Transaction_Processor' => EE_Dependency_Map::load_from_cache,
916
+			],
917
+			'EventEspresso\core\services\payments\PaymentProcessorFees' => [
918
+				'EventEspresso\core\domain\values\gateways\GracePeriod'    => EE_Dependency_Map::load_from_cache,
919
+				'EventEspresso\core\domain\services\licensing\LicenseData' => EE_Dependency_Map::load_from_cache,
920
+			],
921
+			'EventEspresso\core\domain\services\licensing\LicenseData'  => [
922
+				'EventEspresso\core\domain\Domain'                             => EE_Dependency_Map::load_from_cache,
923
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
924
+			],
925
+			'EventEspresso\core\domain\services\licensing\LicenseDataEDD' => [
926
+				'EventEspresso\core\services\licensing\LicenseKeyData' => EE_Dependency_Map::load_from_cache,
927
+			],
928
+			'EventEspresso\core\domain\services\licensing\LicenseDataPue' => [
929
+				'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
930
+			],
931
+			'EventEspresso\core\services\addon\api\DependencyHandlers' => [
932
+				'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
933
+			],
934
+			'EventEspresso\core\services\addon\api\AddonRoutes' => [
935
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
936
+			],
937
+		];
938
+	}
939
+
940
+
941
+	/**
942
+	 * Registers how core classes are loaded.
943
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
944
+	 *        'EE_Request_Handler' => 'load_core'
945
+	 *        'EE_Messages_Queue'  => 'load_lib'
946
+	 *        'EEH_Debug_Tools'    => 'load_helper'
947
+	 * or, if greater control is required, by providing a custom closure. For example:
948
+	 *        'Some_Class' => function () {
949
+	 *            return new Some_Class();
950
+	 *        },
951
+	 * This is required for instantiating dependencies
952
+	 * where an interface has been type hinted in a class constructor. For example:
953
+	 *        'Required_Interface' => function () {
954
+	 *            return new A_Class_That_Implements_Required_Interface();
955
+	 *        },
956
+	 */
957
+	protected function _register_core_class_loaders()
958
+	{
959
+		$this->_class_loaders = [
960
+			// load_core
961
+			'EE_Dependency_Map'                            => function () {
962
+				return $this;
963
+			},
964
+			'EE_Capabilities'                              => 'load_core',
965
+			'EE_Encryption'                                => 'load_core',
966
+			'EE_Front_Controller'                          => 'load_core',
967
+			'EE_Module_Request_Router'                     => 'load_core',
968
+			'EE_Registry'                                  => 'load_core',
969
+			'EE_Request'                                   => function () {
970
+				return $this->legacy_request;
971
+			},
972
+			'EventEspresso\core\services\request\Request'  => function () {
973
+				return $this->request;
974
+			},
975
+			'EventEspresso\core\services\request\Response' => function () {
976
+				return $this->response;
977
+			},
978
+			'EE_Base'                                      => 'load_core',
979
+			'EE_Request_Handler'                           => 'load_core',
980
+			'EE_Session'                                   => 'load_core',
981
+			'EE_Cron_Tasks'                                => 'load_core',
982
+			'EE_System'                                    => 'load_core',
983
+			'EE_Maintenance_Mode'                          => 'load_core',
984
+			'EE_Register_CPTs'                             => 'load_core',
985
+			'EE_Admin'                                     => 'load_core',
986
+			'EE_CPT_Strategy'                              => 'load_core',
987
+			// load_class
988
+			'EE_Registration_Processor'                    => 'load_class',
989
+			'EE_Transaction_Payments'                      => 'load_class',
990
+			'EE_Transaction_Processor'                     => 'load_class',
991
+			// load_lib
992
+			'EE_Message_Resource_Manager'                  => 'load_lib',
993
+			'EE_Message_Type_Collection'                   => 'load_lib',
994
+			'EE_Message_Type_Collection_Loader'            => 'load_lib',
995
+			'EE_Messenger_Collection'                      => 'load_lib',
996
+			'EE_Messenger_Collection_Loader'               => 'load_lib',
997
+			'EE_Messages_Processor'                        => 'load_lib',
998
+			'EE_Message_Repository'                        => 'load_lib',
999
+			'EE_Messages_Queue'                            => 'load_lib',
1000
+			'EE_Messages_Data_Handler_Collection'          => 'load_lib',
1001
+			'EE_Message_Template_Group_Collection'         => 'load_lib',
1002
+			'EE_Payment_Method_Manager'                    => 'load_lib',
1003
+			'EE_Payment_Processor'                         => 'load_core',
1004
+			'EE_DMS_Core_4_1_0'                            => 'load_dms',
1005
+			'EE_DMS_Core_4_2_0'                            => 'load_dms',
1006
+			'EE_DMS_Core_4_3_0'                            => 'load_dms',
1007
+			'EE_DMS_Core_4_5_0'                            => 'load_dms',
1008
+			'EE_DMS_Core_4_6_0'                            => 'load_dms',
1009
+			'EE_DMS_Core_4_7_0'                            => 'load_dms',
1010
+			'EE_DMS_Core_4_8_0'                            => 'load_dms',
1011
+			'EE_DMS_Core_4_9_0'                            => 'load_dms',
1012
+			'EE_DMS_Core_4_10_0'                           => 'load_dms',
1013
+			'EE_DMS_Core_5_0_0'                            => 'load_dms',
1014
+			'EE_Messages_Generator'                        => static function () {
1015
+				return EE_Registry::instance()->load_lib(
1016
+					'Messages_Generator',
1017
+					[],
1018
+					false,
1019
+					false
1020
+				);
1021
+			},
1022
+			'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
1023
+				return EE_Registry::instance()->load_lib(
1024
+					'Messages_Template_Defaults',
1025
+					$arguments,
1026
+					false,
1027
+					false
1028
+				);
1029
+			},
1030
+			// load_helper
1031
+			'EEH_Parse_Shortcodes'                         => static function () {
1032
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
1033
+					return new EEH_Parse_Shortcodes();
1034
+				}
1035
+				return null;
1036
+			},
1037
+			'EE_Template_Config'                           => static function () {
1038
+				return EE_Config::instance()->template_settings;
1039
+			},
1040
+			'EE_Currency_Config'                           => static function () {
1041
+				return EE_Currency_Config::getCurrencyConfig();
1042
+			},
1043
+			'EE_Registration_Config'                       => static function () {
1044
+				return EE_Config::instance()->registration;
1045
+			},
1046
+			'EE_Core_Config'                               => static function () {
1047
+				return EE_Config::instance()->core;
1048
+			},
1049
+			'EventEspresso\core\services\loaders\Loader'   => static function () {
1050
+				return LoaderFactory::getLoader();
1051
+			},
1052
+			'EE_Network_Config'                            => static function () {
1053
+				return EE_Network_Config::instance();
1054
+			},
1055
+			'EE_Config'                                    => static function () {
1056
+				return EE_Config::instance();
1057
+			},
1058
+			'EventEspresso\core\domain\Domain'             => static function () {
1059
+				return DomainFactory::getEventEspressoCoreDomain();
1060
+			},
1061
+			'EE_Admin_Config'                              => static function () {
1062
+				return EE_Config::instance()->admin;
1063
+			},
1064
+			'EE_Organization_Config'                       => static function () {
1065
+				return EE_Config::instance()->organization;
1066
+			},
1067
+			'EE_Network_Core_Config'                       => static function () {
1068
+				return EE_Network_Config::instance()->core;
1069
+			},
1070
+			'EE_Environment_Config'                        => static function () {
1071
+				return EE_Config::instance()->environment;
1072
+			},
1073
+			'EED_Core_Rest_Api'                            => static function () {
1074
+				return EED_Core_Rest_Api::instance();
1075
+			},
1076
+			'WP_REST_Server'                               => static function () {
1077
+				return rest_get_server();
1078
+			},
1079
+			'EventEspresso\core\Psr4Autoloader'            => static function () {
1080
+				return EE_Psr4AutoloaderInit::psr4_loader();
1081
+			},
1082
+			'EE_Ticket_Selector_Config'                    => function () {
1083
+				return EE_Config::instance()->template_settings->EED_Ticket_Selector;
1084
+			},
1085
+		];
1086
+	}
1087
+
1088
+
1089
+	/**
1090
+	 * can be used for supplying alternate names for classes,
1091
+	 * or for connecting interface names to instantiable classes
1092
+	 *
1093
+	 * @throws InvalidAliasException
1094
+	 */
1095
+	protected function _register_core_aliases()
1096
+	{
1097
+		$aliases = [
1098
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
1099
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
1100
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
1101
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
1102
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
1103
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
1104
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1105
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
1106
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1107
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
1108
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommand',
1109
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommand',
1110
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommand',
1111
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
1112
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
1113
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommand',
1114
+			'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\domain\services\commands\transaction\CreateTransactionCommandHandler',
1115
+			'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler',
1116
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
1117
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
1118
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1119
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
1120
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1121
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
1122
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
1123
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
1124
+			'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
1125
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
1126
+			'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
1127
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
1128
+			'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
1129
+			'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
1130
+			'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
1131
+			'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
1132
+			'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
1133
+			'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1134
+			'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1135
+			'Registration_Processor'                                                       => 'EE_Registration_Processor',
1136
+			'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1137
+		];
1138
+		foreach ($aliases as $alias => $fqn) {
1139
+			if (is_array($fqn)) {
1140
+				foreach ($fqn as $class => $for_class) {
1141
+					$this->class_cache->addAlias($class, $alias, $for_class);
1142
+				}
1143
+				continue;
1144
+			}
1145
+			$this->class_cache->addAlias($fqn, $alias);
1146
+		}
1147
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1148
+			$this->class_cache->addAlias(
1149
+				'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1150
+				'EventEspresso\core\services\notices\NoticeConverterInterface'
1151
+			);
1152
+		}
1153
+	}
1154
+
1155
+
1156
+	public function debug($for_class = '')
1157
+	{
1158
+		if (method_exists($this->class_cache, 'debug')) {
1159
+			$this->class_cache->debug($for_class);
1160
+		}
1161
+	}
1162
+
1163
+
1164
+	/**
1165
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1166
+	 * request Primarily used by unit tests.
1167
+	 */
1168
+	public function reset()
1169
+	{
1170
+		$this->_register_core_class_loaders();
1171
+		$this->_register_core_dependencies();
1172
+	}
1173
+
1174
+
1175
+	/**
1176
+	 * PLZ NOTE: a better name for this method would be is_alias()
1177
+	 * because it returns TRUE if the provided fully qualified name IS an alias
1178
+	 * WHY?
1179
+	 * Because if a class is type hinting for a concretion,
1180
+	 * then why would we need to find another class to supply it?
1181
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1182
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1183
+	 * Don't go looking for some substitute.
1184
+	 * Whereas if a class is type hinting for an interface...
1185
+	 * then we need to find an actual class to use.
1186
+	 * So the interface IS the alias for some other FQN,
1187
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1188
+	 * represents some other class.
1189
+	 *
1190
+	 * @param string $fqn
1191
+	 * @param string $for_class
1192
+	 * @return bool
1193
+	 * @deprecated 4.9.62.p
1194
+	 */
1195
+	public function has_alias(string $fqn = '', string $for_class = ''): bool
1196
+	{
1197
+		return $this->isAlias($fqn, $for_class);
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1203
+	 * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1204
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
1205
+	 *  for example:
1206
+	 *      if the following two entries were added to the _aliases array:
1207
+	 *          array(
1208
+	 *              'interface_alias'           => 'some\namespace\interface'
1209
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
1210
+	 *          )
1211
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1212
+	 *      to load an instance of 'some\namespace\classname'
1213
+	 *
1214
+	 * @param string $alias
1215
+	 * @param string $for_class
1216
+	 * @return string
1217
+	 * @deprecated 4.9.62.p
1218
+	 */
1219
+	public function get_alias(string $alias = '', string $for_class = ''): string
1220
+	{
1221
+		return $this->getFqnForAlias($alias, $for_class);
1222
+	}
1223 1223
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin.core.php 2 patches
Indentation   +1003 added lines, -1003 removed lines patch added patch discarded remove patch
@@ -24,1007 +24,1007 @@
 block discarded – undo
24 24
  */
25 25
 final class EE_Admin implements InterminableInterface
26 26
 {
27
-    private static ?EE_Admin $_instance = null;
28
-
29
-    private ?PersistentAdminNoticeManager $persistent_admin_notice_manager = null;
30
-
31
-    protected LoaderInterface $loader;
32
-
33
-    protected RequestInterface $request;
34
-
35
-
36
-    /**
37
-     * @singleton method used to instantiate class object
38
-     * @param LoaderInterface|null  $loader
39
-     * @param RequestInterface|null $request
40
-     * @return EE_Admin|null
41
-     * @throws EE_Error
42
-     */
43
-    public static function instance(?LoaderInterface $loader = null, ?RequestInterface $request = null): ?EE_Admin
44
-    {
45
-        // check if class object is instantiated
46
-        if (! EE_Admin::$_instance instanceof EE_Admin) {
47
-            EE_Admin::$_instance = new EE_Admin($loader, $request);
48
-        }
49
-        return EE_Admin::$_instance;
50
-    }
51
-
52
-
53
-    /**
54
-     * @return EE_Admin|null
55
-     * @throws EE_Error
56
-     */
57
-    public static function reset(): ?EE_Admin
58
-    {
59
-        EE_Admin::$_instance = null;
60
-        $loader = LoaderFactory::getLoader();
61
-        $request = $loader->getShared('EventEspresso\core\services\request\Request');
62
-        return EE_Admin::instance($loader, $request);
63
-    }
64
-
65
-
66
-    /**
67
-     * @param LoaderInterface  $loader
68
-     * @param RequestInterface $request
69
-     * @throws EE_Error
70
-     * @throws InvalidDataTypeException
71
-     * @throws InvalidInterfaceException
72
-     * @throws InvalidArgumentException
73
-     */
74
-    protected function __construct(LoaderInterface $loader, RequestInterface $request)
75
-    {
76
-        $this->loader = $loader;
77
-        $this->request = $request;
78
-        // define global EE_Admin constants
79
-        $this->_define_all_constants();
80
-        // set autoloaders for our admin page classes based on included path information
81
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_ADMIN);
82
-        // reset Environment config (we only do this on admin page loads);
83
-        EE_Registry::instance()->CFG->environment->recheck_values();
84
-        // load EE_Request_Handler early
85
-        add_action('AHEE__EE_System__initialize_last', [$this, 'init']);
86
-        add_action('admin_init', [$this, 'admin_init'], 100);
87
-        if (! $this->request->isActivation() && ! $this->request->isAjax()) {
88
-            // admin hooks
89
-            add_action('admin_notices', [$this, 'display_admin_notices']);
90
-            add_action('network_admin_notices', [$this, 'display_admin_notices']);
91
-            add_filter('pre_update_option', [$this, 'check_for_invalid_datetime_formats'], 100, 2);
92
-            add_filter('plugin_action_links', [$this, 'filter_plugin_actions'], 10, 2);
93
-            add_filter('admin_footer_text', [$this, 'beforeAdminFooterText'], -999);
94
-            add_filter('admin_footer_text', [$this, 'espresso_admin_footer'], 99);
95
-            add_filter('admin_footer_text', [$this, 'afterAdminFooterText'], 999);
96
-            add_action('display_post_states', [$this, 'displayStateForCriticalPages'], 10, 2);
97
-            add_filter('plugin_row_meta', [$this, 'addLinksToPluginRowMeta'], 10, 2);
98
-        }
99
-        do_action('AHEE__EE_Admin__loaded');
100
-    }
101
-
102
-
103
-    /**
104
-     * _define_all_constants
105
-     * define constants that are set globally for all admin pages
106
-     *
107
-     * @return void
108
-     */
109
-    private function _define_all_constants()
110
-    {
111
-        if (! defined('EE_ADMIN_URL')) {
112
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
113
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
114
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates/');
115
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
116
-            define('WP_AJAX_URL', admin_url('admin-ajax.php'));
117
-        }
118
-    }
119
-
120
-
121
-    /**
122
-     * filter_plugin_actions - adds links to the Plugins page listing
123
-     *
124
-     * @param array  $links
125
-     * @param string $plugin
126
-     * @return    array
127
-     */
128
-    public function filter_plugin_actions($links, $plugin)
129
-    {
130
-        // set $main_file in stone
131
-        static $main_file;
132
-        // if $main_file is not set yet
133
-        if (! $main_file) {
134
-            $main_file = EE_PLUGIN_BASENAME;
135
-        }
136
-        if ($plugin === $main_file) {
137
-            // compare current plugin to this one
138
-            if (MaintenanceStatus::isFullSite()) {
139
-                $maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
140
-                                    . ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
141
-                                    . esc_html__('Maintenance Mode Active', 'event_espresso')
142
-                                    . '</a>';
143
-                array_unshift($links, $maintenance_link);
144
-            } else {
145
-                $org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
146
-                                     . esc_html__('Settings', 'event_espresso')
147
-                                     . '</a>';
148
-                $events_link       = '<a href="admin.php?page=espresso_events">'
149
-                                     . esc_html__('Events', 'event_espresso')
150
-                                     . '</a>';
151
-                // add before other links
152
-                array_unshift($links, $org_settings_link, $events_link);
153
-            }
154
-        }
155
-        return $links;
156
-    }
157
-
158
-
159
-    /**
160
-     * hide_admin_pages_except_maintenance_mode
161
-     *
162
-     * @param array $admin_page_folder_names
163
-     * @return array
164
-     */
165
-    public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = [])
166
-    {
167
-        return [
168
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance/',
169
-            'about'       => EE_ADMIN_PAGES . 'about/',
170
-            'support'     => EE_ADMIN_PAGES . 'support/',
171
-        ];
172
-    }
173
-
174
-
175
-    /**
176
-     * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
177
-     * EE_Front_Controller's init phases have run
178
-     *
179
-     * @return void
180
-     * @throws EE_Error
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidDataTypeException
183
-     * @throws InvalidInterfaceException
184
-     * @throws ReflectionException
185
-     * @throws ServiceNotFoundException
186
-     */
187
-    public function init()
188
-    {
189
-        // only enable most of the EE_Admin IF we're not in full maintenance mode
190
-        if (DbStatus::isOnline()) {
191
-            $this->initModelsReady();
192
-        }
193
-        // run the admin page factory but ONLY if:
194
-        // - it is a regular non ajax admin request
195
-        // - we are doing an ee admin ajax request
196
-        if ($this->request->isAdmin() || $this->request->isAdminAjax() || $this->request->isActivation()) {
197
-            try {
198
-                // this loads the controller for the admin pages which will setup routing etc
199
-                $admin_page_loader = $this->loader->getShared('EE_Admin_Page_Loader', [$this->loader]);
200
-                /** @var EE_Admin_Page_Loader $admin_page_loader */
201
-                $admin_page_loader->init();
202
-            } catch (EE_Error $e) {
203
-                $e->get_error();
204
-            }
205
-        }
206
-        if ($this->request->isAjax()) {
207
-            return;
208
-        }
209
-        add_filter('content_save_pre', [$this, 'its_eSpresso']);
210
-        // make sure our CPTs and custom taxonomy metaboxes get shown for first time users
211
-        add_action('admin_head', [$this, 'enable_hidden_ee_nav_menu_metaboxes']);
212
-        add_action('admin_head', [$this, 'register_custom_nav_menu_boxes']);
213
-        // exclude EE critical pages from all nav menus and wp_list_pages
214
-        add_filter('nav_menu_meta_box_object', [$this, 'remove_pages_from_nav_menu']);
215
-    }
216
-
217
-
218
-    /**
219
-     * Gets the loader (and if it wasn't previously set, sets it)
220
-     *
221
-     * @return LoaderInterface
222
-     * @throws InvalidArgumentException
223
-     * @throws InvalidDataTypeException
224
-     * @throws InvalidInterfaceException
225
-     */
226
-    protected function getLoader()
227
-    {
228
-        return $this->loader;
229
-    }
230
-
231
-
232
-    /**
233
-     * Method that's fired on admin requests (including admin ajax) but only when the models are usable
234
-     * (ie, the site isn't in maintenance mode)
235
-     *
236
-     * @return void
237
-     * @throws EE_Error
238
-     * @throws ReflectionException
239
-     * @since 4.9.63.p
240
-     */
241
-    protected function initModelsReady()
242
-    {
243
-        $page = $this->request->getRequestParam('page', '');
244
-        // ok so we want to enable the entire admin
245
-        $this->persistent_admin_notice_manager = $this->loader->getShared(PersistentAdminNoticeManager::class);
246
-        $this->persistent_admin_notice_manager->setReturnUrl(
247
-            EE_Admin_Page::add_query_args_and_nonce(
248
-                [
249
-                    'page'   => $page,
250
-                    'action' => $this->request->getRequestParam('action', ''),
251
-                ],
252
-                EE_ADMIN_URL
253
-            )
254
-        );
255
-        if ($page === 'pricing' || strpos($page, 'espresso') !== false) {
256
-            $this->persistent_admin_notice_manager->loadAdminNotices();
257
-        }
258
-        $this->maybeSetDatetimeWarningNotice();
259
-        // at a glance dashboard widget
260
-        add_filter('dashboard_glance_items', [$this, 'dashboard_glance_items']);
261
-        // filter for get_edit_post_link used on comments for custom post types
262
-        add_filter('get_edit_post_link', [$this, 'modify_edit_post_link'], 10, 2);
263
-    }
264
-
265
-
266
-    /**
267
-     *    get_persistent_admin_notices
268
-     *
269
-     * @access    public
270
-     * @return void
271
-     * @throws EE_Error
272
-     * @throws InvalidArgumentException
273
-     * @throws InvalidDataTypeException
274
-     * @throws InvalidInterfaceException
275
-     * @throws ReflectionException
276
-     */
277
-    public function maybeSetDatetimeWarningNotice()
278
-    {
279
-        // add dismissible notice for datetime changes.  Only valid if site does not have a timezone_string set.
280
-        // @todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
281
-        // with this.  But after enough time (indeterminate at this point) we can just remove this notice.
282
-        // this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
283
-        if (
284
-            apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
285
-            && ! get_option('timezone_string')
286
-            && EEM_Event::instance()->count() > 0
287
-        ) {
288
-            new PersistentAdminNotice(
289
-                'datetime_fix_notice',
290
-                sprintf(
291
-                    esc_html__(
292
-                        '%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
293
-                        'event_espresso'
294
-                    ),
295
-                    '<strong>',
296
-                    '</strong>',
297
-                    '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
298
-                    '</a>',
299
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
300
-                        [
301
-                            'page'   => 'espresso_maintenance_settings',
302
-                            'action' => 'datetime_tools',
303
-                        ],
304
-                        admin_url('admin.php')
305
-                    ) . '">'
306
-                ),
307
-                false,
308
-                'manage_options',
309
-                'datetime_fix_persistent_notice'
310
-            );
311
-        }
312
-    }
313
-
314
-
315
-    /**
316
-     * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
317
-     * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
318
-     * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
319
-     * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
320
-     * normal property on the post_type object.  It's found ONLY in this particular context.
321
-     *
322
-     * @param WP_Post $post_type WP post type object
323
-     * @return WP_Post
324
-     * @throws InvalidArgumentException
325
-     * @throws InvalidDataTypeException
326
-     * @throws InvalidInterfaceException
327
-     */
328
-    public function remove_pages_from_nav_menu($post_type)
329
-    {
330
-        // if this isn't the "pages" post type let's get out
331
-        if ($post_type->name !== 'page') {
332
-            return $post_type;
333
-        }
334
-        $critical_pages            = EE_Registry::instance()->CFG->core->get_critical_pages_array();
335
-        $post_type->_default_query = [
336
-            'post__not_in' => $critical_pages,
337
-        ];
338
-        return $post_type;
339
-    }
340
-
341
-
342
-    /**
343
-     * WP by default only shows three metaboxes in "nav-menus.php" for first times users.
344
-     * We want to make sure our metaboxes get shown as well
345
-     *
346
-     * @return void
347
-     */
348
-    public function enable_hidden_ee_nav_menu_metaboxes()
349
-    {
350
-        global $wp_meta_boxes, $pagenow;
351
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
352
-            return;
353
-        }
354
-        $user = wp_get_current_user();
355
-        // has this been done yet?
356
-        if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
357
-            return;
358
-        }
359
-
360
-        $hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
361
-        $initial_meta_boxes = apply_filters(
362
-            'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
363
-            [
364
-                'nav-menu-theme-locations',
365
-                'add-page',
366
-                'add-custom-links',
367
-                'add-category',
368
-                'add-espresso_events',
369
-                'add-espresso_venues',
370
-                'add-espresso_event_categories',
371
-                'add-espresso_venue_categories',
372
-                'add-post-type-post',
373
-                'add-post-type-page',
374
-            ]
375
-        );
376
-
377
-        if (is_array($hidden_meta_boxes)) {
378
-            foreach ($hidden_meta_boxes as $key => $meta_box_id) {
379
-                if (in_array($meta_box_id, $initial_meta_boxes, true)) {
380
-                    unset($hidden_meta_boxes[ $key ]);
381
-                }
382
-            }
383
-        }
384
-        update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
385
-        update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
386
-    }
387
-
388
-
389
-    /**
390
-     * This method simply registers custom nav menu boxes for "nav_menus.php route"
391
-     * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
392
-     *
393
-     * @return void
394
-     * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
395
-     *         addons etc.
396
-     */
397
-    public function register_custom_nav_menu_boxes()
398
-    {
399
-        add_meta_box(
400
-            'add-extra-nav-menu-pages',
401
-            esc_html__('Event Espresso Pages', 'event_espresso'),
402
-            [$this, 'ee_cpt_archive_pages'],
403
-            'nav-menus',
404
-            'side',
405
-            'core'
406
-        );
407
-        add_filter(
408
-            "postbox_classes_nav-menus_add-extra-nav-menu-pages",
409
-            function ($classes) {
410
-                $classes[] = 'ee-admin-container';
411
-                return $classes;
412
-            }
413
-        );
414
-    }
415
-
416
-
417
-    /**
418
-     * Use this to edit the post link for our cpts so that the edit link points to the correct page.
419
-     *
420
-     * @param string $link the original link generated by wp
421
-     * @param int    $id   post id
422
-     * @return string  the (maybe) modified link
423
-     * @since   4.3.0
424
-     */
425
-    public function modify_edit_post_link($link, $id)
426
-    {
427
-        if (! $post = get_post($id)) {
428
-            return $link;
429
-        }
430
-        if ($post->post_type === EspressoPostType::ATTENDEES) {
431
-            $query_args = [
432
-                'action' => 'edit_attendee',
433
-                'post'   => $id,
434
-            ];
435
-            return EEH_URL::add_query_args_and_nonce(
436
-                $query_args,
437
-                admin_url('admin.php?page=espresso_registrations')
438
-            );
439
-        }
440
-        return $link;
441
-    }
442
-
443
-
444
-    public function ee_cpt_archive_pages()
445
-    {
446
-        global $nav_menu_selected_id;
447
-        $removed_args = [
448
-            'action',
449
-            'customlink-tab',
450
-            'edit-menu-item',
451
-            'menu-item',
452
-            'page-tab',
453
-            '_wpnonce',
454
-        ];
455
-        $nav_tab_link = $nav_menu_selected_id
456
-            ? esc_url(
457
-                add_query_arg(
458
-                    'extra-nav-menu-pages-tab',
459
-                    'event-archives',
460
-                    remove_query_arg($removed_args)
461
-                )
462
-            )
463
-            : '';
464
-        $select_all_link = esc_url(
465
-            add_query_arg(
466
-                [
467
-                    'extra-nav-menu-pages-tab' => 'event-archives',
468
-                    'selectall'                => 1,
469
-                ],
470
-                remove_query_arg($removed_args)
471
-            )
472
-        );
473
-        $pages = $this->_get_extra_nav_menu_pages_items();
474
-        $args['walker'] = new Walker_Nav_Menu_Checklist(false);
475
-        $nav_menu_pages_items = walk_nav_menu_tree(
476
-            array_map(
477
-                [$this, '_setup_extra_nav_menu_pages_items'],
478
-                $pages
479
-            ),
480
-            0,
481
-            (object) $args
482
-        );
483
-        EEH_Template::display_template(
484
-            EE_ADMIN_TEMPLATE . 'cpt_archive_page.template.php',
485
-            [
486
-                'nav_menu_selected_id' => $nav_menu_selected_id,
487
-                'nav_menu_pages_items' => $nav_menu_pages_items,
488
-                'nav_tab_link'         => $nav_tab_link,
489
-                'select_all_link'      => $select_all_link,
490
-            ]
491
-        );
492
-    }
493
-
494
-
495
-    /**
496
-     * Returns an array of event archive nav items.
497
-     *
498
-     * @return array
499
-     * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
500
-     *        method we use for getting the extra nav menu items
501
-     */
502
-    private function _get_extra_nav_menu_pages_items()
503
-    {
504
-        $menuitems[] = [
505
-            'title'       => esc_html__('Event List', 'event_espresso'),
506
-            'url'         => get_post_type_archive_link(EspressoPostType::EVENTS),
507
-            'description' => esc_html__('Archive page for all events.', 'event_espresso'),
508
-        ];
509
-        return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
510
-    }
511
-
512
-
513
-    /**
514
-     * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
515
-     * the properties and converts it to the menu item object.
516
-     *
517
-     * @param $menu_item_values
518
-     * @return stdClass
519
-     * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
520
-     */
521
-    private function _setup_extra_nav_menu_pages_items($menu_item_values)
522
-    {
523
-        $menu_item = new stdClass();
524
-        $keys      = [
525
-            'ID'               => 0,
526
-            'db_id'            => 0,
527
-            'menu_item_parent' => 0,
528
-            'object_id'        => -1,
529
-            'post_parent'      => 0,
530
-            'type'             => 'custom',
531
-            'object'           => '',
532
-            'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
533
-            'title'            => '',
534
-            'url'              => '',
535
-            'target'           => '',
536
-            'attr_title'       => '',
537
-            'description'      => '',
538
-            'classes'          => [],
539
-            'xfn'              => '',
540
-        ];
541
-        foreach ($keys as $key => $value) {
542
-            $menu_item->{$key} = $menu_item_values[ $key ] ?? $value;
543
-        }
544
-        return $menu_item;
545
-    }
546
-
547
-
548
-    /**
549
-     * admin_init
550
-     *
551
-     * @return void
552
-     * @throws InvalidArgumentException
553
-     * @throws InvalidDataTypeException
554
-     * @throws InvalidInterfaceException
555
-     */
556
-    public function admin_init()
557
-    {
558
-        /**
559
-         * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
560
-         * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
561
-         * - check if doing post processing.
562
-         * - check if doing post processing of one of EE CPTs
563
-         * - instantiate the corresponding EE CPT model for the post_type being processed.
564
-         */
565
-        $action    = $this->request->getRequestParam('action');
566
-        $post_type = $this->request->getRequestParam('post_type');
567
-        if ($post_type && $action === 'editpost') {
568
-            /** @var CustomPostTypeDefinitions $custom_post_types */
569
-            $custom_post_types = $this->loader->getShared(CustomPostTypeDefinitions::class);
570
-            $custom_post_types->getCustomPostTypeModels($post_type);
571
-        }
572
-
573
-
574
-        if (! $this->request->isAjax()) {
575
-            /**
576
-             * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
577
-             * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
578
-             * Pages" tab in the EE General Settings Admin page.
579
-             * This is for user-proofing.
580
-             */
581
-            add_filter('wp_dropdown_pages', [$this, 'modify_dropdown_pages']);
582
-            if (DbStatus::isOnline()) {
583
-                $this->adminInitModelsReady();
584
-            }
585
-        }
586
-    }
587
-
588
-
589
-    /**
590
-     * Runs on admin_init but only if models are usable (ie, we're not in maintenance mode)
591
-     */
592
-    protected function adminInitModelsReady()
593
-    {
594
-        if (function_exists('wp_add_privacy_policy_content')) {
595
-            $this->loader->getShared('EventEspresso\core\services\privacy\policy\PrivacyPolicyManager');
596
-        }
597
-    }
598
-
599
-
600
-    /**
601
-     * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
602
-     *
603
-     * @param string $output Current output.
604
-     * @return string
605
-     * @throws InvalidArgumentException
606
-     * @throws InvalidDataTypeException
607
-     * @throws InvalidInterfaceException
608
-     */
609
-    public function modify_dropdown_pages($output)
610
-    {
611
-        // get critical pages
612
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
613
-
614
-        // split current output by line break for easier parsing.
615
-        $split_output = explode("\n", $output);
616
-
617
-        // loop through to remove any critical pages from the array.
618
-        foreach ($critical_pages as $page_id) {
619
-            $needle = 'value="' . $page_id . '"';
620
-            foreach ($split_output as $key => $haystack) {
621
-                if (strpos($haystack, $needle) !== false) {
622
-                    unset($split_output[ $key ]);
623
-                }
624
-            }
625
-        }
626
-        // replace output with the new contents
627
-        return implode("\n", $split_output);
628
-    }
629
-
630
-
631
-    /**
632
-     * display_admin_notices
633
-     *
634
-     * @return void
635
-     */
636
-    public function display_admin_notices()
637
-    {
638
-        echo EE_Error::get_notices(); // already escaped
639
-    }
640
-
641
-
642
-    /**
643
-     * @param array $elements
644
-     * @return array
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function dashboard_glance_items($elements)
652
-    {
653
-        $elements                        = is_array($elements) ? $elements : [$elements];
654
-        $events                          = EEM_Event::instance()->count();
655
-        $items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
656
-            ['page' => 'espresso_events'],
657
-            admin_url('admin.php')
658
-        );
659
-        $items['events']['text']         = sprintf(
660
-            esc_html(
661
-                _n('%s Event', '%s Events', $events, 'event_espresso')
662
-            ),
663
-            number_format_i18n($events)
664
-        );
665
-        $items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
666
-        $registrations                   = EEM_Registration::instance()->count(
667
-            [
668
-                [
669
-                    'STS_ID' => ['!=', RegStatus::INCOMPLETE],
670
-                ],
671
-            ]
672
-        );
673
-        $items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
674
-            ['page' => 'espresso_registrations'],
675
-            admin_url('admin.php')
676
-        );
677
-        $items['registrations']['text']  = sprintf(
678
-            esc_html(
679
-                _n('%s Registration', '%s Registrations', $registrations, 'event_espresso')
680
-            ),
681
-            number_format_i18n($registrations)
682
-        );
683
-        $items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
684
-
685
-        $items = (array) apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
686
-
687
-        foreach ($items as $type => $item_properties) {
688
-            $elements[] = sprintf(
689
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
690
-                $item_properties['url'],
691
-                $item_properties['title'],
692
-                $item_properties['text']
693
-            );
694
-        }
695
-        return $elements;
696
-    }
697
-
698
-
699
-    /**
700
-     * check_for_invalid_datetime_formats
701
-     * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
702
-     * their selected format can be parsed by PHP
703
-     *
704
-     * @param    $value
705
-     * @param    $option
706
-     * @return    string
707
-     */
708
-    public function check_for_invalid_datetime_formats($value, $option)
709
-    {
710
-        // check for date_format or time_format
711
-        switch ($option) {
712
-            case 'date_format':
713
-                $date_time_format = $value . ' ' . get_option('time_format');
714
-                break;
715
-            case 'time_format':
716
-                $date_time_format = get_option('date_format') . ' ' . $value;
717
-                break;
718
-            default:
719
-                $date_time_format = false;
720
-        }
721
-        // do we have a date_time format to check ?
722
-        if ($date_time_format) {
723
-            $error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
724
-
725
-            if (is_array($error_msg)) {
726
-                $msg = '<p>'
727
-                       . sprintf(
728
-                           esc_html__(
729
-                               'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
730
-                               'event_espresso'
731
-                           ),
732
-                           date($date_time_format),
733
-                           $date_time_format
734
-                       )
735
-                       . '</p><p><ul>';
736
-
737
-
738
-                foreach ($error_msg as $error) {
739
-                    $msg .= '<li>' . $error . '</li>';
740
-                }
741
-
742
-                $msg .= '</ul></p><p>'
743
-                        . sprintf(
744
-                            esc_html__(
745
-                                '%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
746
-                                'event_espresso'
747
-                            ),
748
-                            '<span style="color:#D54E21;">',
749
-                            '</span>'
750
-                        )
751
-                        . '</p>';
752
-
753
-                // trigger WP settings error
754
-                add_settings_error(
755
-                    'date_format',
756
-                    'date_format',
757
-                    $msg
758
-                );
759
-
760
-                // set format to something valid
761
-                switch ($option) {
762
-                    case 'date_format':
763
-                        $value = 'F j, Y';
764
-                        break;
765
-                    case 'time_format':
766
-                        $value = 'g:i a';
767
-                        break;
768
-                }
769
-            }
770
-        }
771
-        return $value;
772
-    }
773
-
774
-
775
-    /**
776
-     * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
777
-     *
778
-     * @param $content
779
-     * @return    string
780
-     */
781
-    public function its_eSpresso($content)
782
-    {
783
-        return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
784
-    }
785
-
786
-
787
-    /**
788
-     * espresso_admin_footer
789
-     *
790
-     * @param string|null $text
791
-     * @return string
792
-     */
793
-    public function espresso_admin_footer(?string $text = ''): string
794
-    {
795
-        return "$text &nbsp " . EEH_Template::powered_by_event_espresso('', '', ['utm_content' => 'admin_footer']);
796
-    }
797
-
798
-    public function beforeAdminFooterText(?string $text = ''): string
799
-    {
800
-        return "<span class='ee-layout-row ee-layout-row--inline'>$text";
801
-    }
802
-
803
-    public function afterAdminFooterText(?string $text = ''): string
804
-    {
805
-        return "$text</span>";
806
-    }
807
-
808
-
809
-    /**
810
-     * Hooks into the "post states" filter in a wp post type list table.
811
-     *
812
-     * @param array   $post_states
813
-     * @param WP_Post $post
814
-     * @return array
815
-     * @throws InvalidArgumentException
816
-     * @throws InvalidDataTypeException
817
-     * @throws InvalidInterfaceException
818
-     */
819
-    public function displayStateForCriticalPages($post_states, $post)
820
-    {
821
-        $post_states = (array) $post_states;
822
-        if (! $post instanceof WP_Post || $post->post_type !== 'page') {
823
-            return $post_states;
824
-        }
825
-        /** @var EE_Core_Config $config */
826
-        $config = $this->loader->getShared('EE_Config')->core;
827
-        if (in_array($post->ID, $config->get_critical_pages_array(), true)) {
828
-            $post_states[] = sprintf(
829
-            /* Translators: Using company name - Event Espresso Critical Page */
830
-                esc_html__('%s Critical Page', 'event_espresso'),
831
-                'Event Espresso'
832
-            );
833
-        }
834
-        return $post_states;
835
-    }
836
-
837
-
838
-    /**
839
-     * Show documentation links on the plugins page
840
-     *
841
-     * @param mixed $meta Plugin Row Meta
842
-     * @param mixed $file Plugin Base file
843
-     * @return array
844
-     */
845
-    public function addLinksToPluginRowMeta($meta, $file)
846
-    {
847
-        if (EE_PLUGIN_BASENAME === $file) {
848
-            $row_meta = [
849
-                'docs' => '<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4"'
850
-                          . ' aria-label="'
851
-                          . esc_attr__('View Event Espresso documentation', 'event_espresso')
852
-                          . '">'
853
-                          . esc_html__('Docs', 'event_espresso')
854
-                          . '</a>',
855
-                'api'  => '<a href="https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API"'
856
-                          . ' aria-label="'
857
-                          . esc_attr__('View Event Espresso API docs', 'event_espresso')
858
-                          . '">'
859
-                          . esc_html__('API docs', 'event_espresso')
860
-                          . '</a>',
861
-            ];
862
-            return array_merge($meta, $row_meta);
863
-        }
864
-        return (array) $meta;
865
-    }
866
-
867
-     /**************************************************************************************/
868
-     /************************************* DEPRECATED *************************************/
869
-     /**************************************************************************************/
870
-
871
-
872
-    /**
873
-     * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
874
-     * EE_Admin_Page route is called.
875
-     *
876
-     * @return void
877
-     */
878
-    public function route_admin_request()
879
-    {
880
-    }
881
-
882
-
883
-    /**
884
-     * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
885
-     *
886
-     * @return void
887
-     */
888
-    public function wp_loaded()
889
-    {
890
-    }
891
-
892
-
893
-    /**
894
-     * static method for registering ee admin page.
895
-     * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
896
-     *
897
-     * @param       $page_basename
898
-     * @param       $page_path
899
-     * @param array $config
900
-     * @return void
901
-     * @throws EE_Error
902
-     * @see        EE_Register_Admin_Page::register()
903
-     * @since      4.3.0
904
-     * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
905
-     */
906
-    public static function register_ee_admin_page($page_basename, $page_path, $config = [])
907
-    {
908
-        EE_Error::doing_it_wrong(
909
-            __METHOD__,
910
-            sprintf(
911
-                esc_html__(
912
-                    'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
913
-                    'event_espresso'
914
-                ),
915
-                $page_basename
916
-            ),
917
-            '4.3'
918
-        );
919
-        if (class_exists('EE_Register_Admin_Page')) {
920
-            $config['page_path'] = $page_path;
921
-        }
922
-        EE_Register_Admin_Page::register($page_basename, $config);
923
-    }
924
-
925
-
926
-    /**
927
-     * @param int     $post_ID
928
-     * @param WP_Post $post
929
-     * @return void
930
-     * @deprecated 4.8.41
931
-     */
932
-    public static function parse_post_content_on_save($post_ID, $post)
933
-    {
934
-        EE_Error::doing_it_wrong(
935
-            __METHOD__,
936
-            esc_html__('Usage is deprecated', 'event_espresso'),
937
-            '4.8.41'
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * @param  $option
944
-     * @param  $old_value
945
-     * @param  $value
946
-     * @return void
947
-     * @deprecated 4.8.41
948
-     */
949
-    public function reset_page_for_posts_on_change($option, $old_value, $value)
950
-    {
951
-        EE_Error::doing_it_wrong(
952
-            __METHOD__,
953
-            esc_html__('Usage is deprecated', 'event_espresso'),
954
-            '4.8.41'
955
-        );
956
-    }
957
-
958
-
959
-    /**
960
-     * @return void
961
-     * @deprecated 4.9.27
962
-     */
963
-    public function get_persistent_admin_notices()
964
-    {
965
-        EE_Error::doing_it_wrong(
966
-            __METHOD__,
967
-            sprintf(
968
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
969
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
970
-            ),
971
-            '4.9.27'
972
-        );
973
-    }
974
-
975
-
976
-    /**
977
-     * @throws InvalidInterfaceException
978
-     * @throws InvalidDataTypeException
979
-     * @throws DomainException
980
-     * @deprecated 4.9.27
981
-     */
982
-    public function dismiss_ee_nag_notice_callback()
983
-    {
984
-        EE_Error::doing_it_wrong(
985
-            __METHOD__,
986
-            sprintf(
987
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
988
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
989
-            ),
990
-            '4.9.27'
991
-        );
992
-        $this->persistent_admin_notice_manager->dismissNotice();
993
-    }
994
-
995
-
996
-    /**
997
-     * @return void
998
-     * @deprecated 5.0.0.p
999
-     */
1000
-    public function enqueue_admin_scripts()
1001
-    {
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * @return RequestInterface
1008
-     * @deprecated 5.0.0.p
1009
-     */
1010
-    public function get_request()
1011
-    {
1012
-        EE_Error::doing_it_wrong(
1013
-            __METHOD__,
1014
-            sprintf(
1015
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1016
-                'EventEspresso\core\services\request\Request'
1017
-            ),
1018
-            '5.0.0.p'
1019
-        );
1020
-        return $this->request;
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * @deprecated 5.0.0.p
1026
-     */
1027
-    public function hookIntoWpPluginsPage()
1028
-    {
1029
-    }
27
+	private static ?EE_Admin $_instance = null;
28
+
29
+	private ?PersistentAdminNoticeManager $persistent_admin_notice_manager = null;
30
+
31
+	protected LoaderInterface $loader;
32
+
33
+	protected RequestInterface $request;
34
+
35
+
36
+	/**
37
+	 * @singleton method used to instantiate class object
38
+	 * @param LoaderInterface|null  $loader
39
+	 * @param RequestInterface|null $request
40
+	 * @return EE_Admin|null
41
+	 * @throws EE_Error
42
+	 */
43
+	public static function instance(?LoaderInterface $loader = null, ?RequestInterface $request = null): ?EE_Admin
44
+	{
45
+		// check if class object is instantiated
46
+		if (! EE_Admin::$_instance instanceof EE_Admin) {
47
+			EE_Admin::$_instance = new EE_Admin($loader, $request);
48
+		}
49
+		return EE_Admin::$_instance;
50
+	}
51
+
52
+
53
+	/**
54
+	 * @return EE_Admin|null
55
+	 * @throws EE_Error
56
+	 */
57
+	public static function reset(): ?EE_Admin
58
+	{
59
+		EE_Admin::$_instance = null;
60
+		$loader = LoaderFactory::getLoader();
61
+		$request = $loader->getShared('EventEspresso\core\services\request\Request');
62
+		return EE_Admin::instance($loader, $request);
63
+	}
64
+
65
+
66
+	/**
67
+	 * @param LoaderInterface  $loader
68
+	 * @param RequestInterface $request
69
+	 * @throws EE_Error
70
+	 * @throws InvalidDataTypeException
71
+	 * @throws InvalidInterfaceException
72
+	 * @throws InvalidArgumentException
73
+	 */
74
+	protected function __construct(LoaderInterface $loader, RequestInterface $request)
75
+	{
76
+		$this->loader = $loader;
77
+		$this->request = $request;
78
+		// define global EE_Admin constants
79
+		$this->_define_all_constants();
80
+		// set autoloaders for our admin page classes based on included path information
81
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_ADMIN);
82
+		// reset Environment config (we only do this on admin page loads);
83
+		EE_Registry::instance()->CFG->environment->recheck_values();
84
+		// load EE_Request_Handler early
85
+		add_action('AHEE__EE_System__initialize_last', [$this, 'init']);
86
+		add_action('admin_init', [$this, 'admin_init'], 100);
87
+		if (! $this->request->isActivation() && ! $this->request->isAjax()) {
88
+			// admin hooks
89
+			add_action('admin_notices', [$this, 'display_admin_notices']);
90
+			add_action('network_admin_notices', [$this, 'display_admin_notices']);
91
+			add_filter('pre_update_option', [$this, 'check_for_invalid_datetime_formats'], 100, 2);
92
+			add_filter('plugin_action_links', [$this, 'filter_plugin_actions'], 10, 2);
93
+			add_filter('admin_footer_text', [$this, 'beforeAdminFooterText'], -999);
94
+			add_filter('admin_footer_text', [$this, 'espresso_admin_footer'], 99);
95
+			add_filter('admin_footer_text', [$this, 'afterAdminFooterText'], 999);
96
+			add_action('display_post_states', [$this, 'displayStateForCriticalPages'], 10, 2);
97
+			add_filter('plugin_row_meta', [$this, 'addLinksToPluginRowMeta'], 10, 2);
98
+		}
99
+		do_action('AHEE__EE_Admin__loaded');
100
+	}
101
+
102
+
103
+	/**
104
+	 * _define_all_constants
105
+	 * define constants that are set globally for all admin pages
106
+	 *
107
+	 * @return void
108
+	 */
109
+	private function _define_all_constants()
110
+	{
111
+		if (! defined('EE_ADMIN_URL')) {
112
+			define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
113
+			define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
114
+			define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates/');
115
+			define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
116
+			define('WP_AJAX_URL', admin_url('admin-ajax.php'));
117
+		}
118
+	}
119
+
120
+
121
+	/**
122
+	 * filter_plugin_actions - adds links to the Plugins page listing
123
+	 *
124
+	 * @param array  $links
125
+	 * @param string $plugin
126
+	 * @return    array
127
+	 */
128
+	public function filter_plugin_actions($links, $plugin)
129
+	{
130
+		// set $main_file in stone
131
+		static $main_file;
132
+		// if $main_file is not set yet
133
+		if (! $main_file) {
134
+			$main_file = EE_PLUGIN_BASENAME;
135
+		}
136
+		if ($plugin === $main_file) {
137
+			// compare current plugin to this one
138
+			if (MaintenanceStatus::isFullSite()) {
139
+				$maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
140
+									. ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
141
+									. esc_html__('Maintenance Mode Active', 'event_espresso')
142
+									. '</a>';
143
+				array_unshift($links, $maintenance_link);
144
+			} else {
145
+				$org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
146
+									 . esc_html__('Settings', 'event_espresso')
147
+									 . '</a>';
148
+				$events_link       = '<a href="admin.php?page=espresso_events">'
149
+									 . esc_html__('Events', 'event_espresso')
150
+									 . '</a>';
151
+				// add before other links
152
+				array_unshift($links, $org_settings_link, $events_link);
153
+			}
154
+		}
155
+		return $links;
156
+	}
157
+
158
+
159
+	/**
160
+	 * hide_admin_pages_except_maintenance_mode
161
+	 *
162
+	 * @param array $admin_page_folder_names
163
+	 * @return array
164
+	 */
165
+	public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = [])
166
+	{
167
+		return [
168
+			'maintenance' => EE_ADMIN_PAGES . 'maintenance/',
169
+			'about'       => EE_ADMIN_PAGES . 'about/',
170
+			'support'     => EE_ADMIN_PAGES . 'support/',
171
+		];
172
+	}
173
+
174
+
175
+	/**
176
+	 * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
177
+	 * EE_Front_Controller's init phases have run
178
+	 *
179
+	 * @return void
180
+	 * @throws EE_Error
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws InvalidInterfaceException
184
+	 * @throws ReflectionException
185
+	 * @throws ServiceNotFoundException
186
+	 */
187
+	public function init()
188
+	{
189
+		// only enable most of the EE_Admin IF we're not in full maintenance mode
190
+		if (DbStatus::isOnline()) {
191
+			$this->initModelsReady();
192
+		}
193
+		// run the admin page factory but ONLY if:
194
+		// - it is a regular non ajax admin request
195
+		// - we are doing an ee admin ajax request
196
+		if ($this->request->isAdmin() || $this->request->isAdminAjax() || $this->request->isActivation()) {
197
+			try {
198
+				// this loads the controller for the admin pages which will setup routing etc
199
+				$admin_page_loader = $this->loader->getShared('EE_Admin_Page_Loader', [$this->loader]);
200
+				/** @var EE_Admin_Page_Loader $admin_page_loader */
201
+				$admin_page_loader->init();
202
+			} catch (EE_Error $e) {
203
+				$e->get_error();
204
+			}
205
+		}
206
+		if ($this->request->isAjax()) {
207
+			return;
208
+		}
209
+		add_filter('content_save_pre', [$this, 'its_eSpresso']);
210
+		// make sure our CPTs and custom taxonomy metaboxes get shown for first time users
211
+		add_action('admin_head', [$this, 'enable_hidden_ee_nav_menu_metaboxes']);
212
+		add_action('admin_head', [$this, 'register_custom_nav_menu_boxes']);
213
+		// exclude EE critical pages from all nav menus and wp_list_pages
214
+		add_filter('nav_menu_meta_box_object', [$this, 'remove_pages_from_nav_menu']);
215
+	}
216
+
217
+
218
+	/**
219
+	 * Gets the loader (and if it wasn't previously set, sets it)
220
+	 *
221
+	 * @return LoaderInterface
222
+	 * @throws InvalidArgumentException
223
+	 * @throws InvalidDataTypeException
224
+	 * @throws InvalidInterfaceException
225
+	 */
226
+	protected function getLoader()
227
+	{
228
+		return $this->loader;
229
+	}
230
+
231
+
232
+	/**
233
+	 * Method that's fired on admin requests (including admin ajax) but only when the models are usable
234
+	 * (ie, the site isn't in maintenance mode)
235
+	 *
236
+	 * @return void
237
+	 * @throws EE_Error
238
+	 * @throws ReflectionException
239
+	 * @since 4.9.63.p
240
+	 */
241
+	protected function initModelsReady()
242
+	{
243
+		$page = $this->request->getRequestParam('page', '');
244
+		// ok so we want to enable the entire admin
245
+		$this->persistent_admin_notice_manager = $this->loader->getShared(PersistentAdminNoticeManager::class);
246
+		$this->persistent_admin_notice_manager->setReturnUrl(
247
+			EE_Admin_Page::add_query_args_and_nonce(
248
+				[
249
+					'page'   => $page,
250
+					'action' => $this->request->getRequestParam('action', ''),
251
+				],
252
+				EE_ADMIN_URL
253
+			)
254
+		);
255
+		if ($page === 'pricing' || strpos($page, 'espresso') !== false) {
256
+			$this->persistent_admin_notice_manager->loadAdminNotices();
257
+		}
258
+		$this->maybeSetDatetimeWarningNotice();
259
+		// at a glance dashboard widget
260
+		add_filter('dashboard_glance_items', [$this, 'dashboard_glance_items']);
261
+		// filter for get_edit_post_link used on comments for custom post types
262
+		add_filter('get_edit_post_link', [$this, 'modify_edit_post_link'], 10, 2);
263
+	}
264
+
265
+
266
+	/**
267
+	 *    get_persistent_admin_notices
268
+	 *
269
+	 * @access    public
270
+	 * @return void
271
+	 * @throws EE_Error
272
+	 * @throws InvalidArgumentException
273
+	 * @throws InvalidDataTypeException
274
+	 * @throws InvalidInterfaceException
275
+	 * @throws ReflectionException
276
+	 */
277
+	public function maybeSetDatetimeWarningNotice()
278
+	{
279
+		// add dismissible notice for datetime changes.  Only valid if site does not have a timezone_string set.
280
+		// @todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
281
+		// with this.  But after enough time (indeterminate at this point) we can just remove this notice.
282
+		// this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
283
+		if (
284
+			apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
285
+			&& ! get_option('timezone_string')
286
+			&& EEM_Event::instance()->count() > 0
287
+		) {
288
+			new PersistentAdminNotice(
289
+				'datetime_fix_notice',
290
+				sprintf(
291
+					esc_html__(
292
+						'%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
293
+						'event_espresso'
294
+					),
295
+					'<strong>',
296
+					'</strong>',
297
+					'<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
298
+					'</a>',
299
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
300
+						[
301
+							'page'   => 'espresso_maintenance_settings',
302
+							'action' => 'datetime_tools',
303
+						],
304
+						admin_url('admin.php')
305
+					) . '">'
306
+				),
307
+				false,
308
+				'manage_options',
309
+				'datetime_fix_persistent_notice'
310
+			);
311
+		}
312
+	}
313
+
314
+
315
+	/**
316
+	 * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
317
+	 * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
318
+	 * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
319
+	 * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
320
+	 * normal property on the post_type object.  It's found ONLY in this particular context.
321
+	 *
322
+	 * @param WP_Post $post_type WP post type object
323
+	 * @return WP_Post
324
+	 * @throws InvalidArgumentException
325
+	 * @throws InvalidDataTypeException
326
+	 * @throws InvalidInterfaceException
327
+	 */
328
+	public function remove_pages_from_nav_menu($post_type)
329
+	{
330
+		// if this isn't the "pages" post type let's get out
331
+		if ($post_type->name !== 'page') {
332
+			return $post_type;
333
+		}
334
+		$critical_pages            = EE_Registry::instance()->CFG->core->get_critical_pages_array();
335
+		$post_type->_default_query = [
336
+			'post__not_in' => $critical_pages,
337
+		];
338
+		return $post_type;
339
+	}
340
+
341
+
342
+	/**
343
+	 * WP by default only shows three metaboxes in "nav-menus.php" for first times users.
344
+	 * We want to make sure our metaboxes get shown as well
345
+	 *
346
+	 * @return void
347
+	 */
348
+	public function enable_hidden_ee_nav_menu_metaboxes()
349
+	{
350
+		global $wp_meta_boxes, $pagenow;
351
+		if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
352
+			return;
353
+		}
354
+		$user = wp_get_current_user();
355
+		// has this been done yet?
356
+		if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
357
+			return;
358
+		}
359
+
360
+		$hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
361
+		$initial_meta_boxes = apply_filters(
362
+			'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
363
+			[
364
+				'nav-menu-theme-locations',
365
+				'add-page',
366
+				'add-custom-links',
367
+				'add-category',
368
+				'add-espresso_events',
369
+				'add-espresso_venues',
370
+				'add-espresso_event_categories',
371
+				'add-espresso_venue_categories',
372
+				'add-post-type-post',
373
+				'add-post-type-page',
374
+			]
375
+		);
376
+
377
+		if (is_array($hidden_meta_boxes)) {
378
+			foreach ($hidden_meta_boxes as $key => $meta_box_id) {
379
+				if (in_array($meta_box_id, $initial_meta_boxes, true)) {
380
+					unset($hidden_meta_boxes[ $key ]);
381
+				}
382
+			}
383
+		}
384
+		update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
385
+		update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
386
+	}
387
+
388
+
389
+	/**
390
+	 * This method simply registers custom nav menu boxes for "nav_menus.php route"
391
+	 * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
392
+	 *
393
+	 * @return void
394
+	 * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
395
+	 *         addons etc.
396
+	 */
397
+	public function register_custom_nav_menu_boxes()
398
+	{
399
+		add_meta_box(
400
+			'add-extra-nav-menu-pages',
401
+			esc_html__('Event Espresso Pages', 'event_espresso'),
402
+			[$this, 'ee_cpt_archive_pages'],
403
+			'nav-menus',
404
+			'side',
405
+			'core'
406
+		);
407
+		add_filter(
408
+			"postbox_classes_nav-menus_add-extra-nav-menu-pages",
409
+			function ($classes) {
410
+				$classes[] = 'ee-admin-container';
411
+				return $classes;
412
+			}
413
+		);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Use this to edit the post link for our cpts so that the edit link points to the correct page.
419
+	 *
420
+	 * @param string $link the original link generated by wp
421
+	 * @param int    $id   post id
422
+	 * @return string  the (maybe) modified link
423
+	 * @since   4.3.0
424
+	 */
425
+	public function modify_edit_post_link($link, $id)
426
+	{
427
+		if (! $post = get_post($id)) {
428
+			return $link;
429
+		}
430
+		if ($post->post_type === EspressoPostType::ATTENDEES) {
431
+			$query_args = [
432
+				'action' => 'edit_attendee',
433
+				'post'   => $id,
434
+			];
435
+			return EEH_URL::add_query_args_and_nonce(
436
+				$query_args,
437
+				admin_url('admin.php?page=espresso_registrations')
438
+			);
439
+		}
440
+		return $link;
441
+	}
442
+
443
+
444
+	public function ee_cpt_archive_pages()
445
+	{
446
+		global $nav_menu_selected_id;
447
+		$removed_args = [
448
+			'action',
449
+			'customlink-tab',
450
+			'edit-menu-item',
451
+			'menu-item',
452
+			'page-tab',
453
+			'_wpnonce',
454
+		];
455
+		$nav_tab_link = $nav_menu_selected_id
456
+			? esc_url(
457
+				add_query_arg(
458
+					'extra-nav-menu-pages-tab',
459
+					'event-archives',
460
+					remove_query_arg($removed_args)
461
+				)
462
+			)
463
+			: '';
464
+		$select_all_link = esc_url(
465
+			add_query_arg(
466
+				[
467
+					'extra-nav-menu-pages-tab' => 'event-archives',
468
+					'selectall'                => 1,
469
+				],
470
+				remove_query_arg($removed_args)
471
+			)
472
+		);
473
+		$pages = $this->_get_extra_nav_menu_pages_items();
474
+		$args['walker'] = new Walker_Nav_Menu_Checklist(false);
475
+		$nav_menu_pages_items = walk_nav_menu_tree(
476
+			array_map(
477
+				[$this, '_setup_extra_nav_menu_pages_items'],
478
+				$pages
479
+			),
480
+			0,
481
+			(object) $args
482
+		);
483
+		EEH_Template::display_template(
484
+			EE_ADMIN_TEMPLATE . 'cpt_archive_page.template.php',
485
+			[
486
+				'nav_menu_selected_id' => $nav_menu_selected_id,
487
+				'nav_menu_pages_items' => $nav_menu_pages_items,
488
+				'nav_tab_link'         => $nav_tab_link,
489
+				'select_all_link'      => $select_all_link,
490
+			]
491
+		);
492
+	}
493
+
494
+
495
+	/**
496
+	 * Returns an array of event archive nav items.
497
+	 *
498
+	 * @return array
499
+	 * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
500
+	 *        method we use for getting the extra nav menu items
501
+	 */
502
+	private function _get_extra_nav_menu_pages_items()
503
+	{
504
+		$menuitems[] = [
505
+			'title'       => esc_html__('Event List', 'event_espresso'),
506
+			'url'         => get_post_type_archive_link(EspressoPostType::EVENTS),
507
+			'description' => esc_html__('Archive page for all events.', 'event_espresso'),
508
+		];
509
+		return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
510
+	}
511
+
512
+
513
+	/**
514
+	 * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
515
+	 * the properties and converts it to the menu item object.
516
+	 *
517
+	 * @param $menu_item_values
518
+	 * @return stdClass
519
+	 * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
520
+	 */
521
+	private function _setup_extra_nav_menu_pages_items($menu_item_values)
522
+	{
523
+		$menu_item = new stdClass();
524
+		$keys      = [
525
+			'ID'               => 0,
526
+			'db_id'            => 0,
527
+			'menu_item_parent' => 0,
528
+			'object_id'        => -1,
529
+			'post_parent'      => 0,
530
+			'type'             => 'custom',
531
+			'object'           => '',
532
+			'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
533
+			'title'            => '',
534
+			'url'              => '',
535
+			'target'           => '',
536
+			'attr_title'       => '',
537
+			'description'      => '',
538
+			'classes'          => [],
539
+			'xfn'              => '',
540
+		];
541
+		foreach ($keys as $key => $value) {
542
+			$menu_item->{$key} = $menu_item_values[ $key ] ?? $value;
543
+		}
544
+		return $menu_item;
545
+	}
546
+
547
+
548
+	/**
549
+	 * admin_init
550
+	 *
551
+	 * @return void
552
+	 * @throws InvalidArgumentException
553
+	 * @throws InvalidDataTypeException
554
+	 * @throws InvalidInterfaceException
555
+	 */
556
+	public function admin_init()
557
+	{
558
+		/**
559
+		 * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
560
+		 * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
561
+		 * - check if doing post processing.
562
+		 * - check if doing post processing of one of EE CPTs
563
+		 * - instantiate the corresponding EE CPT model for the post_type being processed.
564
+		 */
565
+		$action    = $this->request->getRequestParam('action');
566
+		$post_type = $this->request->getRequestParam('post_type');
567
+		if ($post_type && $action === 'editpost') {
568
+			/** @var CustomPostTypeDefinitions $custom_post_types */
569
+			$custom_post_types = $this->loader->getShared(CustomPostTypeDefinitions::class);
570
+			$custom_post_types->getCustomPostTypeModels($post_type);
571
+		}
572
+
573
+
574
+		if (! $this->request->isAjax()) {
575
+			/**
576
+			 * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
577
+			 * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
578
+			 * Pages" tab in the EE General Settings Admin page.
579
+			 * This is for user-proofing.
580
+			 */
581
+			add_filter('wp_dropdown_pages', [$this, 'modify_dropdown_pages']);
582
+			if (DbStatus::isOnline()) {
583
+				$this->adminInitModelsReady();
584
+			}
585
+		}
586
+	}
587
+
588
+
589
+	/**
590
+	 * Runs on admin_init but only if models are usable (ie, we're not in maintenance mode)
591
+	 */
592
+	protected function adminInitModelsReady()
593
+	{
594
+		if (function_exists('wp_add_privacy_policy_content')) {
595
+			$this->loader->getShared('EventEspresso\core\services\privacy\policy\PrivacyPolicyManager');
596
+		}
597
+	}
598
+
599
+
600
+	/**
601
+	 * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
602
+	 *
603
+	 * @param string $output Current output.
604
+	 * @return string
605
+	 * @throws InvalidArgumentException
606
+	 * @throws InvalidDataTypeException
607
+	 * @throws InvalidInterfaceException
608
+	 */
609
+	public function modify_dropdown_pages($output)
610
+	{
611
+		// get critical pages
612
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
613
+
614
+		// split current output by line break for easier parsing.
615
+		$split_output = explode("\n", $output);
616
+
617
+		// loop through to remove any critical pages from the array.
618
+		foreach ($critical_pages as $page_id) {
619
+			$needle = 'value="' . $page_id . '"';
620
+			foreach ($split_output as $key => $haystack) {
621
+				if (strpos($haystack, $needle) !== false) {
622
+					unset($split_output[ $key ]);
623
+				}
624
+			}
625
+		}
626
+		// replace output with the new contents
627
+		return implode("\n", $split_output);
628
+	}
629
+
630
+
631
+	/**
632
+	 * display_admin_notices
633
+	 *
634
+	 * @return void
635
+	 */
636
+	public function display_admin_notices()
637
+	{
638
+		echo EE_Error::get_notices(); // already escaped
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param array $elements
644
+	 * @return array
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function dashboard_glance_items($elements)
652
+	{
653
+		$elements                        = is_array($elements) ? $elements : [$elements];
654
+		$events                          = EEM_Event::instance()->count();
655
+		$items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
656
+			['page' => 'espresso_events'],
657
+			admin_url('admin.php')
658
+		);
659
+		$items['events']['text']         = sprintf(
660
+			esc_html(
661
+				_n('%s Event', '%s Events', $events, 'event_espresso')
662
+			),
663
+			number_format_i18n($events)
664
+		);
665
+		$items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
666
+		$registrations                   = EEM_Registration::instance()->count(
667
+			[
668
+				[
669
+					'STS_ID' => ['!=', RegStatus::INCOMPLETE],
670
+				],
671
+			]
672
+		);
673
+		$items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
674
+			['page' => 'espresso_registrations'],
675
+			admin_url('admin.php')
676
+		);
677
+		$items['registrations']['text']  = sprintf(
678
+			esc_html(
679
+				_n('%s Registration', '%s Registrations', $registrations, 'event_espresso')
680
+			),
681
+			number_format_i18n($registrations)
682
+		);
683
+		$items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
684
+
685
+		$items = (array) apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
686
+
687
+		foreach ($items as $type => $item_properties) {
688
+			$elements[] = sprintf(
689
+				'<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
690
+				$item_properties['url'],
691
+				$item_properties['title'],
692
+				$item_properties['text']
693
+			);
694
+		}
695
+		return $elements;
696
+	}
697
+
698
+
699
+	/**
700
+	 * check_for_invalid_datetime_formats
701
+	 * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
702
+	 * their selected format can be parsed by PHP
703
+	 *
704
+	 * @param    $value
705
+	 * @param    $option
706
+	 * @return    string
707
+	 */
708
+	public function check_for_invalid_datetime_formats($value, $option)
709
+	{
710
+		// check for date_format or time_format
711
+		switch ($option) {
712
+			case 'date_format':
713
+				$date_time_format = $value . ' ' . get_option('time_format');
714
+				break;
715
+			case 'time_format':
716
+				$date_time_format = get_option('date_format') . ' ' . $value;
717
+				break;
718
+			default:
719
+				$date_time_format = false;
720
+		}
721
+		// do we have a date_time format to check ?
722
+		if ($date_time_format) {
723
+			$error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
724
+
725
+			if (is_array($error_msg)) {
726
+				$msg = '<p>'
727
+					   . sprintf(
728
+						   esc_html__(
729
+							   'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
730
+							   'event_espresso'
731
+						   ),
732
+						   date($date_time_format),
733
+						   $date_time_format
734
+					   )
735
+					   . '</p><p><ul>';
736
+
737
+
738
+				foreach ($error_msg as $error) {
739
+					$msg .= '<li>' . $error . '</li>';
740
+				}
741
+
742
+				$msg .= '</ul></p><p>'
743
+						. sprintf(
744
+							esc_html__(
745
+								'%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
746
+								'event_espresso'
747
+							),
748
+							'<span style="color:#D54E21;">',
749
+							'</span>'
750
+						)
751
+						. '</p>';
752
+
753
+				// trigger WP settings error
754
+				add_settings_error(
755
+					'date_format',
756
+					'date_format',
757
+					$msg
758
+				);
759
+
760
+				// set format to something valid
761
+				switch ($option) {
762
+					case 'date_format':
763
+						$value = 'F j, Y';
764
+						break;
765
+					case 'time_format':
766
+						$value = 'g:i a';
767
+						break;
768
+				}
769
+			}
770
+		}
771
+		return $value;
772
+	}
773
+
774
+
775
+	/**
776
+	 * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
777
+	 *
778
+	 * @param $content
779
+	 * @return    string
780
+	 */
781
+	public function its_eSpresso($content)
782
+	{
783
+		return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
784
+	}
785
+
786
+
787
+	/**
788
+	 * espresso_admin_footer
789
+	 *
790
+	 * @param string|null $text
791
+	 * @return string
792
+	 */
793
+	public function espresso_admin_footer(?string $text = ''): string
794
+	{
795
+		return "$text &nbsp " . EEH_Template::powered_by_event_espresso('', '', ['utm_content' => 'admin_footer']);
796
+	}
797
+
798
+	public function beforeAdminFooterText(?string $text = ''): string
799
+	{
800
+		return "<span class='ee-layout-row ee-layout-row--inline'>$text";
801
+	}
802
+
803
+	public function afterAdminFooterText(?string $text = ''): string
804
+	{
805
+		return "$text</span>";
806
+	}
807
+
808
+
809
+	/**
810
+	 * Hooks into the "post states" filter in a wp post type list table.
811
+	 *
812
+	 * @param array   $post_states
813
+	 * @param WP_Post $post
814
+	 * @return array
815
+	 * @throws InvalidArgumentException
816
+	 * @throws InvalidDataTypeException
817
+	 * @throws InvalidInterfaceException
818
+	 */
819
+	public function displayStateForCriticalPages($post_states, $post)
820
+	{
821
+		$post_states = (array) $post_states;
822
+		if (! $post instanceof WP_Post || $post->post_type !== 'page') {
823
+			return $post_states;
824
+		}
825
+		/** @var EE_Core_Config $config */
826
+		$config = $this->loader->getShared('EE_Config')->core;
827
+		if (in_array($post->ID, $config->get_critical_pages_array(), true)) {
828
+			$post_states[] = sprintf(
829
+			/* Translators: Using company name - Event Espresso Critical Page */
830
+				esc_html__('%s Critical Page', 'event_espresso'),
831
+				'Event Espresso'
832
+			);
833
+		}
834
+		return $post_states;
835
+	}
836
+
837
+
838
+	/**
839
+	 * Show documentation links on the plugins page
840
+	 *
841
+	 * @param mixed $meta Plugin Row Meta
842
+	 * @param mixed $file Plugin Base file
843
+	 * @return array
844
+	 */
845
+	public function addLinksToPluginRowMeta($meta, $file)
846
+	{
847
+		if (EE_PLUGIN_BASENAME === $file) {
848
+			$row_meta = [
849
+				'docs' => '<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4"'
850
+						  . ' aria-label="'
851
+						  . esc_attr__('View Event Espresso documentation', 'event_espresso')
852
+						  . '">'
853
+						  . esc_html__('Docs', 'event_espresso')
854
+						  . '</a>',
855
+				'api'  => '<a href="https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API"'
856
+						  . ' aria-label="'
857
+						  . esc_attr__('View Event Espresso API docs', 'event_espresso')
858
+						  . '">'
859
+						  . esc_html__('API docs', 'event_espresso')
860
+						  . '</a>',
861
+			];
862
+			return array_merge($meta, $row_meta);
863
+		}
864
+		return (array) $meta;
865
+	}
866
+
867
+	 /**************************************************************************************/
868
+	 /************************************* DEPRECATED *************************************/
869
+	 /**************************************************************************************/
870
+
871
+
872
+	/**
873
+	 * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
874
+	 * EE_Admin_Page route is called.
875
+	 *
876
+	 * @return void
877
+	 */
878
+	public function route_admin_request()
879
+	{
880
+	}
881
+
882
+
883
+	/**
884
+	 * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
885
+	 *
886
+	 * @return void
887
+	 */
888
+	public function wp_loaded()
889
+	{
890
+	}
891
+
892
+
893
+	/**
894
+	 * static method for registering ee admin page.
895
+	 * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
896
+	 *
897
+	 * @param       $page_basename
898
+	 * @param       $page_path
899
+	 * @param array $config
900
+	 * @return void
901
+	 * @throws EE_Error
902
+	 * @see        EE_Register_Admin_Page::register()
903
+	 * @since      4.3.0
904
+	 * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
905
+	 */
906
+	public static function register_ee_admin_page($page_basename, $page_path, $config = [])
907
+	{
908
+		EE_Error::doing_it_wrong(
909
+			__METHOD__,
910
+			sprintf(
911
+				esc_html__(
912
+					'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
913
+					'event_espresso'
914
+				),
915
+				$page_basename
916
+			),
917
+			'4.3'
918
+		);
919
+		if (class_exists('EE_Register_Admin_Page')) {
920
+			$config['page_path'] = $page_path;
921
+		}
922
+		EE_Register_Admin_Page::register($page_basename, $config);
923
+	}
924
+
925
+
926
+	/**
927
+	 * @param int     $post_ID
928
+	 * @param WP_Post $post
929
+	 * @return void
930
+	 * @deprecated 4.8.41
931
+	 */
932
+	public static function parse_post_content_on_save($post_ID, $post)
933
+	{
934
+		EE_Error::doing_it_wrong(
935
+			__METHOD__,
936
+			esc_html__('Usage is deprecated', 'event_espresso'),
937
+			'4.8.41'
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * @param  $option
944
+	 * @param  $old_value
945
+	 * @param  $value
946
+	 * @return void
947
+	 * @deprecated 4.8.41
948
+	 */
949
+	public function reset_page_for_posts_on_change($option, $old_value, $value)
950
+	{
951
+		EE_Error::doing_it_wrong(
952
+			__METHOD__,
953
+			esc_html__('Usage is deprecated', 'event_espresso'),
954
+			'4.8.41'
955
+		);
956
+	}
957
+
958
+
959
+	/**
960
+	 * @return void
961
+	 * @deprecated 4.9.27
962
+	 */
963
+	public function get_persistent_admin_notices()
964
+	{
965
+		EE_Error::doing_it_wrong(
966
+			__METHOD__,
967
+			sprintf(
968
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
969
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
970
+			),
971
+			'4.9.27'
972
+		);
973
+	}
974
+
975
+
976
+	/**
977
+	 * @throws InvalidInterfaceException
978
+	 * @throws InvalidDataTypeException
979
+	 * @throws DomainException
980
+	 * @deprecated 4.9.27
981
+	 */
982
+	public function dismiss_ee_nag_notice_callback()
983
+	{
984
+		EE_Error::doing_it_wrong(
985
+			__METHOD__,
986
+			sprintf(
987
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
988
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
989
+			),
990
+			'4.9.27'
991
+		);
992
+		$this->persistent_admin_notice_manager->dismissNotice();
993
+	}
994
+
995
+
996
+	/**
997
+	 * @return void
998
+	 * @deprecated 5.0.0.p
999
+	 */
1000
+	public function enqueue_admin_scripts()
1001
+	{
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * @return RequestInterface
1008
+	 * @deprecated 5.0.0.p
1009
+	 */
1010
+	public function get_request()
1011
+	{
1012
+		EE_Error::doing_it_wrong(
1013
+			__METHOD__,
1014
+			sprintf(
1015
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1016
+				'EventEspresso\core\services\request\Request'
1017
+			),
1018
+			'5.0.0.p'
1019
+		);
1020
+		return $this->request;
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * @deprecated 5.0.0.p
1026
+	 */
1027
+	public function hookIntoWpPluginsPage()
1028
+	{
1029
+	}
1030 1030
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
     public static function instance(?LoaderInterface $loader = null, ?RequestInterface $request = null): ?EE_Admin
44 44
     {
45 45
         // check if class object is instantiated
46
-        if (! EE_Admin::$_instance instanceof EE_Admin) {
46
+        if ( ! EE_Admin::$_instance instanceof EE_Admin) {
47 47
             EE_Admin::$_instance = new EE_Admin($loader, $request);
48 48
         }
49 49
         return EE_Admin::$_instance;
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
         // load EE_Request_Handler early
85 85
         add_action('AHEE__EE_System__initialize_last', [$this, 'init']);
86 86
         add_action('admin_init', [$this, 'admin_init'], 100);
87
-        if (! $this->request->isActivation() && ! $this->request->isAjax()) {
87
+        if ( ! $this->request->isActivation() && ! $this->request->isAjax()) {
88 88
             // admin hooks
89 89
             add_action('admin_notices', [$this, 'display_admin_notices']);
90 90
             add_action('network_admin_notices', [$this, 'display_admin_notices']);
@@ -108,11 +108,11 @@  discard block
 block discarded – undo
108 108
      */
109 109
     private function _define_all_constants()
110 110
     {
111
-        if (! defined('EE_ADMIN_URL')) {
112
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
113
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
114
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates/');
115
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
111
+        if ( ! defined('EE_ADMIN_URL')) {
112
+            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL.'core/admin/');
113
+            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL.'admin_pages/');
114
+            define('EE_ADMIN_TEMPLATE', EE_ADMIN.'templates/');
115
+            define('WP_ADMIN_PATH', ABSPATH.'wp-admin/');
116 116
             define('WP_AJAX_URL', admin_url('admin-ajax.php'));
117 117
         }
118 118
     }
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
         // set $main_file in stone
131 131
         static $main_file;
132 132
         // if $main_file is not set yet
133
-        if (! $main_file) {
133
+        if ( ! $main_file) {
134 134
             $main_file = EE_PLUGIN_BASENAME;
135 135
         }
136 136
         if ($plugin === $main_file) {
@@ -165,9 +165,9 @@  discard block
 block discarded – undo
165 165
     public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = [])
166 166
     {
167 167
         return [
168
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance/',
169
-            'about'       => EE_ADMIN_PAGES . 'about/',
170
-            'support'     => EE_ADMIN_PAGES . 'support/',
168
+            'maintenance' => EE_ADMIN_PAGES.'maintenance/',
169
+            'about'       => EE_ADMIN_PAGES.'about/',
170
+            'support'     => EE_ADMIN_PAGES.'support/',
171 171
         ];
172 172
     }
173 173
 
@@ -296,13 +296,13 @@  discard block
 block discarded – undo
296 296
                     '</strong>',
297 297
                     '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
298 298
                     '</a>',
299
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
299
+                    '<a href="'.EE_Admin_Page::add_query_args_and_nonce(
300 300
                         [
301 301
                             'page'   => 'espresso_maintenance_settings',
302 302
                             'action' => 'datetime_tools',
303 303
                         ],
304 304
                         admin_url('admin.php')
305
-                    ) . '">'
305
+                    ).'">'
306 306
                 ),
307 307
                 false,
308 308
                 'manage_options',
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
     public function enable_hidden_ee_nav_menu_metaboxes()
349 349
     {
350 350
         global $wp_meta_boxes, $pagenow;
351
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
351
+        if ( ! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
352 352
             return;
353 353
         }
354 354
         $user = wp_get_current_user();
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
         if (is_array($hidden_meta_boxes)) {
378 378
             foreach ($hidden_meta_boxes as $key => $meta_box_id) {
379 379
                 if (in_array($meta_box_id, $initial_meta_boxes, true)) {
380
-                    unset($hidden_meta_boxes[ $key ]);
380
+                    unset($hidden_meta_boxes[$key]);
381 381
                 }
382 382
             }
383 383
         }
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
         );
407 407
         add_filter(
408 408
             "postbox_classes_nav-menus_add-extra-nav-menu-pages",
409
-            function ($classes) {
409
+            function($classes) {
410 410
                 $classes[] = 'ee-admin-container';
411 411
                 return $classes;
412 412
             }
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
      */
425 425
     public function modify_edit_post_link($link, $id)
426 426
     {
427
-        if (! $post = get_post($id)) {
427
+        if ( ! $post = get_post($id)) {
428 428
             return $link;
429 429
         }
430 430
         if ($post->post_type === EspressoPostType::ATTENDEES) {
@@ -481,7 +481,7 @@  discard block
 block discarded – undo
481 481
             (object) $args
482 482
         );
483 483
         EEH_Template::display_template(
484
-            EE_ADMIN_TEMPLATE . 'cpt_archive_page.template.php',
484
+            EE_ADMIN_TEMPLATE.'cpt_archive_page.template.php',
485 485
             [
486 486
                 'nav_menu_selected_id' => $nav_menu_selected_id,
487 487
                 'nav_menu_pages_items' => $nav_menu_pages_items,
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
             'xfn'              => '',
540 540
         ];
541 541
         foreach ($keys as $key => $value) {
542
-            $menu_item->{$key} = $menu_item_values[ $key ] ?? $value;
542
+            $menu_item->{$key} = $menu_item_values[$key] ?? $value;
543 543
         }
544 544
         return $menu_item;
545 545
     }
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
         }
572 572
 
573 573
 
574
-        if (! $this->request->isAjax()) {
574
+        if ( ! $this->request->isAjax()) {
575 575
             /**
576 576
              * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
577 577
              * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
@@ -616,10 +616,10 @@  discard block
 block discarded – undo
616 616
 
617 617
         // loop through to remove any critical pages from the array.
618 618
         foreach ($critical_pages as $page_id) {
619
-            $needle = 'value="' . $page_id . '"';
619
+            $needle = 'value="'.$page_id.'"';
620 620
             foreach ($split_output as $key => $haystack) {
621 621
                 if (strpos($haystack, $needle) !== false) {
622
-                    unset($split_output[ $key ]);
622
+                    unset($split_output[$key]);
623 623
                 }
624 624
             }
625 625
         }
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
             ['page' => 'espresso_events'],
657 657
             admin_url('admin.php')
658 658
         );
659
-        $items['events']['text']         = sprintf(
659
+        $items['events']['text'] = sprintf(
660 660
             esc_html(
661 661
                 _n('%s Event', '%s Events', $events, 'event_espresso')
662 662
             ),
@@ -670,11 +670,11 @@  discard block
 block discarded – undo
670 670
                 ],
671 671
             ]
672 672
         );
673
-        $items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
673
+        $items['registrations']['url'] = EE_Admin_Page::add_query_args_and_nonce(
674 674
             ['page' => 'espresso_registrations'],
675 675
             admin_url('admin.php')
676 676
         );
677
-        $items['registrations']['text']  = sprintf(
677
+        $items['registrations']['text'] = sprintf(
678 678
             esc_html(
679 679
                 _n('%s Registration', '%s Registrations', $registrations, 'event_espresso')
680 680
             ),
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 
687 687
         foreach ($items as $type => $item_properties) {
688 688
             $elements[] = sprintf(
689
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
689
+                '<a class="ee-dashboard-link-'.$type.'" href="%s" title="%s">%s</a>',
690 690
                 $item_properties['url'],
691 691
                 $item_properties['title'],
692 692
                 $item_properties['text']
@@ -710,10 +710,10 @@  discard block
 block discarded – undo
710 710
         // check for date_format or time_format
711 711
         switch ($option) {
712 712
             case 'date_format':
713
-                $date_time_format = $value . ' ' . get_option('time_format');
713
+                $date_time_format = $value.' '.get_option('time_format');
714 714
                 break;
715 715
             case 'time_format':
716
-                $date_time_format = get_option('date_format') . ' ' . $value;
716
+                $date_time_format = get_option('date_format').' '.$value;
717 717
                 break;
718 718
             default:
719 719
                 $date_time_format = false;
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
 
737 737
 
738 738
                 foreach ($error_msg as $error) {
739
-                    $msg .= '<li>' . $error . '</li>';
739
+                    $msg .= '<li>'.$error.'</li>';
740 740
                 }
741 741
 
742 742
                 $msg .= '</ul></p><p>'
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
      */
793 793
     public function espresso_admin_footer(?string $text = ''): string
794 794
     {
795
-        return "$text &nbsp " . EEH_Template::powered_by_event_espresso('', '', ['utm_content' => 'admin_footer']);
795
+        return "$text &nbsp ".EEH_Template::powered_by_event_espresso('', '', ['utm_content' => 'admin_footer']);
796 796
     }
797 797
 
798 798
     public function beforeAdminFooterText(?string $text = ''): string
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
     public function displayStateForCriticalPages($post_states, $post)
820 820
     {
821 821
         $post_states = (array) $post_states;
822
-        if (! $post instanceof WP_Post || $post->post_type !== 'page') {
822
+        if ( ! $post instanceof WP_Post || $post->post_type !== 'page') {
823 823
             return $post_states;
824 824
         }
825 825
         /** @var EE_Core_Config $config */
Please login to merge, or discard this patch.
core/exceptions/InvalidDataTypeException.php 2 patches
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -15,52 +15,52 @@
 block discarded – undo
15 15
  */
16 16
 class InvalidDataTypeException extends InvalidArgumentException
17 17
 {
18
-    /**
19
-     * InvalidDataTypeException constructor
20
-     *
21
-     * @param string         $var_name name of the variable that was of the wrong type ie: "$my_var"
22
-     * @param mixed          $variable the actual variable that was of the wrong data type, ie: $my_var
23
-     * @param string         $expected data type we wanted ie: "integer", "string", "array", etc.
24
-     *                                 or an entire rewrite of: "{something something} was expected."
25
-     * @param string         $message
26
-     * @param int            $code
27
-     * @param Exception|null $previous
28
-     */
29
-    public function __construct(
30
-        string $var_name,
31
-        $variable,
32
-        string $expected,
33
-        string $message = '',
34
-        int $code = 0,
35
-        ?Exception $previous = null
36
-    ) {
37
-        if (empty($message)) {
38
-            $expected = strpos(' was expected.', $expected) === false
39
-                ? $this->addIndefiniteArticle($expected) . ' was expected.'
40
-                : $expected;
41
-            $message  = sprintf(
42
-                esc_html__(
43
-                    'The supplied data for "%1$s" was %2$s, but %3$s',
44
-                    'event_espresso'
45
-                ),
46
-                $var_name,
47
-                $this->addIndefiniteArticle(gettype($variable)),
48
-                $expected
49
-            );
50
-        }
51
-        parent::__construct($message, $code, $previous);
52
-    }
18
+	/**
19
+	 * InvalidDataTypeException constructor
20
+	 *
21
+	 * @param string         $var_name name of the variable that was of the wrong type ie: "$my_var"
22
+	 * @param mixed          $variable the actual variable that was of the wrong data type, ie: $my_var
23
+	 * @param string         $expected data type we wanted ie: "integer", "string", "array", etc.
24
+	 *                                 or an entire rewrite of: "{something something} was expected."
25
+	 * @param string         $message
26
+	 * @param int            $code
27
+	 * @param Exception|null $previous
28
+	 */
29
+	public function __construct(
30
+		string $var_name,
31
+		$variable,
32
+		string $expected,
33
+		string $message = '',
34
+		int $code = 0,
35
+		?Exception $previous = null
36
+	) {
37
+		if (empty($message)) {
38
+			$expected = strpos(' was expected.', $expected) === false
39
+				? $this->addIndefiniteArticle($expected) . ' was expected.'
40
+				: $expected;
41
+			$message  = sprintf(
42
+				esc_html__(
43
+					'The supplied data for "%1$s" was %2$s, but %3$s',
44
+					'event_espresso'
45
+				),
46
+				$var_name,
47
+				$this->addIndefiniteArticle(gettype($variable)),
48
+				$expected
49
+			);
50
+		}
51
+		parent::__construct($message, $code, $previous);
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * @param string $string
57
-     * @return string
58
-     */
59
-    protected function addIndefiniteArticle(string $string): string
60
-    {
61
-        if (strtolower($string) === 'null') {
62
-            return $string;
63
-        }
64
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
65
-    }
55
+	/**
56
+	 * @param string $string
57
+	 * @return string
58
+	 */
59
+	protected function addIndefiniteArticle(string $string): string
60
+	{
61
+		if (strtolower($string) === 'null') {
62
+			return $string;
63
+		}
64
+		return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
65
+	}
66 66
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
     ) {
37 37
         if (empty($message)) {
38 38
             $expected = strpos(' was expected.', $expected) === false
39
-                ? $this->addIndefiniteArticle($expected) . ' was expected.'
39
+                ? $this->addIndefiniteArticle($expected).' was expected.'
40 40
                 : $expected;
41 41
             $message  = sprintf(
42 42
                 esc_html__(
@@ -61,6 +61,6 @@  discard block
 block discarded – undo
61 61
         if (strtolower($string) === 'null') {
62 62
             return $string;
63 63
         }
64
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
64
+        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ').$string;
65 65
     }
66 66
 }
Please login to merge, or discard this patch.
core/exceptions/InvalidFormSubmissionException.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -13,25 +13,25 @@
 block discarded – undo
13 13
  */
14 14
 class InvalidFormSubmissionException extends OutOfBoundsException
15 15
 {
16
-    /**
17
-     * InvalidFormSubmissionException constructor
18
-     *
19
-     * @param string     $form_name
20
-     * @param string     $message
21
-     * @param int        $code
22
-     * @param \Exception $previous
23
-     */
24
-    public function __construct($form_name, $message = '', $code = 0, \Exception $previous = null)
25
-    {
26
-        if (empty($message)) {
27
-            $message = sprintf(
28
-                esc_html__(
29
-                    'The data for the "%1$s" form, is either missing or was not submitted properly.',
30
-                    'event_espresso'
31
-                ),
32
-                $form_name
33
-            );
34
-        }
35
-        parent::__construct($message, $code, $previous);
36
-    }
16
+	/**
17
+	 * InvalidFormSubmissionException constructor
18
+	 *
19
+	 * @param string     $form_name
20
+	 * @param string     $message
21
+	 * @param int        $code
22
+	 * @param \Exception $previous
23
+	 */
24
+	public function __construct($form_name, $message = '', $code = 0, \Exception $previous = null)
25
+	{
26
+		if (empty($message)) {
27
+			$message = sprintf(
28
+				esc_html__(
29
+					'The data for the "%1$s" form, is either missing or was not submitted properly.',
30
+					'event_espresso'
31
+				),
32
+				$form_name
33
+			);
34
+		}
35
+		parent::__construct($message, $code, $previous);
36
+	}
37 37
 }
Please login to merge, or discard this patch.