Completed
Branch BUG/11419/ical-line-endings (79c085)
by
unknown
25:29 queued 12:47
created
caffeinated/admin/new/pricing/espresso_events_Pricing_Hooks.class.php 1 patch
Indentation   +2130 added lines, -2130 removed lines patch added patch discarded remove patch
@@ -19,2190 +19,2190 @@
 block discarded – undo
19 19
 class espresso_events_Pricing_Hooks extends EE_Admin_Hooks
20 20
 {
21 21
 
22
-    /**
23
-     * This property is just used to hold the status of whether an event is currently being
24
-     * created (true) or edited (false)
25
-     *
26
-     * @access protected
27
-     * @var bool
28
-     */
29
-    protected $_is_creating_event;
22
+	/**
23
+	 * This property is just used to hold the status of whether an event is currently being
24
+	 * created (true) or edited (false)
25
+	 *
26
+	 * @access protected
27
+	 * @var bool
28
+	 */
29
+	protected $_is_creating_event;
30 30
 
31
-    /**
32
-     * Used to contain the format strings for date and time that will be used for php date and
33
-     * time.
34
-     * Is set in the _set_hooks_properties() method.
35
-     *
36
-     * @var array
37
-     */
38
-    protected $_date_format_strings;
31
+	/**
32
+	 * Used to contain the format strings for date and time that will be used for php date and
33
+	 * time.
34
+	 * Is set in the _set_hooks_properties() method.
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected $_date_format_strings;
39 39
 
40
-    /**
41
-     * @var string $_date_time_format
42
-     */
43
-    protected $_date_time_format;
40
+	/**
41
+	 * @var string $_date_time_format
42
+	 */
43
+	protected $_date_time_format;
44 44
 
45 45
 
46
-    /**
47
-     * @throws InvalidArgumentException
48
-     * @throws InvalidInterfaceException
49
-     * @throws InvalidDataTypeException
50
-     */
51
-    protected function _set_hooks_properties()
52
-    {
53
-        $this->_name = 'pricing';
54
-        //capability check
55
-        if (! EE_Registry::instance()->CAP->current_user_can(
56
-            'ee_read_default_prices',
57
-            'advanced_ticket_datetime_metabox'
58
-        )) {
59
-            return;
60
-        }
61
-        $this->_setup_metaboxes();
62
-        $this->_set_date_time_formats();
63
-        $this->_validate_format_strings();
64
-        $this->_set_scripts_styles();
65
-        // commented out temporarily until logic is implemented in callback
66
-        // add_action(
67
-        //     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
68
-        //     array($this, 'autosave_handling')
69
-        // );
70
-        add_filter(
71
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
72
-            array($this, 'caf_updates')
73
-        );
74
-    }
46
+	/**
47
+	 * @throws InvalidArgumentException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws InvalidDataTypeException
50
+	 */
51
+	protected function _set_hooks_properties()
52
+	{
53
+		$this->_name = 'pricing';
54
+		//capability check
55
+		if (! EE_Registry::instance()->CAP->current_user_can(
56
+			'ee_read_default_prices',
57
+			'advanced_ticket_datetime_metabox'
58
+		)) {
59
+			return;
60
+		}
61
+		$this->_setup_metaboxes();
62
+		$this->_set_date_time_formats();
63
+		$this->_validate_format_strings();
64
+		$this->_set_scripts_styles();
65
+		// commented out temporarily until logic is implemented in callback
66
+		// add_action(
67
+		//     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
68
+		//     array($this, 'autosave_handling')
69
+		// );
70
+		add_filter(
71
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
72
+			array($this, 'caf_updates')
73
+		);
74
+	}
75 75
 
76 76
 
77
-    /**
78
-     * @return void
79
-     */
80
-    protected function _setup_metaboxes()
81
-    {
82
-        //if we were going to add our own metaboxes we'd use the below.
83
-        $this->_metaboxes        = array(
84
-            0 => array(
85
-                'page_route' => array('edit', 'create_new'),
86
-                'func'       => 'pricing_metabox',
87
-                'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
88
-                'priority'   => 'high',
89
-                'context'    => 'normal',
90
-            ),
91
-        );
92
-        $this->_remove_metaboxes = array(
93
-            0 => array(
94
-                'page_route' => array('edit', 'create_new'),
95
-                'id'         => 'espresso_event_editor_tickets',
96
-                'context'    => 'normal',
97
-            ),
98
-        );
99
-    }
77
+	/**
78
+	 * @return void
79
+	 */
80
+	protected function _setup_metaboxes()
81
+	{
82
+		//if we were going to add our own metaboxes we'd use the below.
83
+		$this->_metaboxes        = array(
84
+			0 => array(
85
+				'page_route' => array('edit', 'create_new'),
86
+				'func'       => 'pricing_metabox',
87
+				'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
88
+				'priority'   => 'high',
89
+				'context'    => 'normal',
90
+			),
91
+		);
92
+		$this->_remove_metaboxes = array(
93
+			0 => array(
94
+				'page_route' => array('edit', 'create_new'),
95
+				'id'         => 'espresso_event_editor_tickets',
96
+				'context'    => 'normal',
97
+			),
98
+		);
99
+	}
100 100
 
101 101
 
102
-    /**
103
-     * @return void
104
-     */
105
-    protected function _set_date_time_formats()
106
-    {
107
-        /**
108
-         * Format strings for date and time.  Defaults are existing behaviour from 4.1.
109
-         * Note, that if you return null as the value for 'date', and 'time' in the array, then
110
-         * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
111
-         *
112
-         * @since 4.6.7
113
-         * @var array  Expected an array returned with 'date' and 'time' keys.
114
-         */
115
-        $this->_date_format_strings = apply_filters(
116
-            'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
117
-            array(
118
-                'date' => 'Y-m-d',
119
-                'time' => 'h:i a',
120
-            )
121
-        );
122
-        //validate
123
-        $this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
124
-            ? $this->_date_format_strings['date']
125
-            : null;
126
-        $this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
127
-            ? $this->_date_format_strings['time']
128
-            : null;
129
-        $this->_date_time_format            = $this->_date_format_strings['date']
130
-                                              . ' '
131
-                                              . $this->_date_format_strings['time'];
132
-    }
102
+	/**
103
+	 * @return void
104
+	 */
105
+	protected function _set_date_time_formats()
106
+	{
107
+		/**
108
+		 * Format strings for date and time.  Defaults are existing behaviour from 4.1.
109
+		 * Note, that if you return null as the value for 'date', and 'time' in the array, then
110
+		 * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
111
+		 *
112
+		 * @since 4.6.7
113
+		 * @var array  Expected an array returned with 'date' and 'time' keys.
114
+		 */
115
+		$this->_date_format_strings = apply_filters(
116
+			'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
117
+			array(
118
+				'date' => 'Y-m-d',
119
+				'time' => 'h:i a',
120
+			)
121
+		);
122
+		//validate
123
+		$this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
124
+			? $this->_date_format_strings['date']
125
+			: null;
126
+		$this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
127
+			? $this->_date_format_strings['time']
128
+			: null;
129
+		$this->_date_time_format            = $this->_date_format_strings['date']
130
+											  . ' '
131
+											  . $this->_date_format_strings['time'];
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * @return void
137
-     */
138
-    protected function _validate_format_strings()
139
-    {
140
-        //validate format strings
141
-        $format_validation = EEH_DTT_Helper::validate_format_string(
142
-            $this->_date_time_format
143
-        );
144
-        if (is_array($format_validation)) {
145
-            $msg = '<p>';
146
-            $msg .= sprintf(
147
-                esc_html__(
148
-                    'The format "%s" was likely added via a filter and is invalid for the following reasons:',
149
-                    'event_espresso'
150
-                ),
151
-                $this->_date_time_format
152
-            );
153
-            $msg .= '</p><ul>';
154
-            foreach ($format_validation as $error) {
155
-                $msg .= '<li>' . $error . '</li>';
156
-            }
157
-            $msg .= '</ul><p>';
158
-            $msg .= sprintf(
159
-                esc_html__(
160
-                    '%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
161
-                    'event_espresso'
162
-                ),
163
-                '<span style="color:#D54E21;">',
164
-                '</span>'
165
-            );
166
-            $msg .= '</p>';
167
-            EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
168
-            $this->_date_format_strings = array(
169
-                'date' => 'Y-m-d',
170
-                'time' => 'h:i a',
171
-            );
172
-        }
173
-    }
135
+	/**
136
+	 * @return void
137
+	 */
138
+	protected function _validate_format_strings()
139
+	{
140
+		//validate format strings
141
+		$format_validation = EEH_DTT_Helper::validate_format_string(
142
+			$this->_date_time_format
143
+		);
144
+		if (is_array($format_validation)) {
145
+			$msg = '<p>';
146
+			$msg .= sprintf(
147
+				esc_html__(
148
+					'The format "%s" was likely added via a filter and is invalid for the following reasons:',
149
+					'event_espresso'
150
+				),
151
+				$this->_date_time_format
152
+			);
153
+			$msg .= '</p><ul>';
154
+			foreach ($format_validation as $error) {
155
+				$msg .= '<li>' . $error . '</li>';
156
+			}
157
+			$msg .= '</ul><p>';
158
+			$msg .= sprintf(
159
+				esc_html__(
160
+					'%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
161
+					'event_espresso'
162
+				),
163
+				'<span style="color:#D54E21;">',
164
+				'</span>'
165
+			);
166
+			$msg .= '</p>';
167
+			EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
168
+			$this->_date_format_strings = array(
169
+				'date' => 'Y-m-d',
170
+				'time' => 'h:i a',
171
+			);
172
+		}
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * @return void
178
-     */
179
-    protected function _set_scripts_styles()
180
-    {
181
-        $this->_scripts_styles = array(
182
-            'registers'   => array(
183
-                'ee-tickets-datetimes-css' => array(
184
-                    'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
185
-                    'type' => 'css',
186
-                ),
187
-                'ee-dtt-ticket-metabox'    => array(
188
-                    'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
189
-                    'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
190
-                ),
191
-            ),
192
-            'deregisters' => array(
193
-                'event-editor-css'       => array('type' => 'css'),
194
-                'event-datetime-metabox' => array('type' => 'js'),
195
-            ),
196
-            'enqueues'    => array(
197
-                'ee-tickets-datetimes-css' => array('edit', 'create_new'),
198
-                'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
199
-            ),
200
-            'localize'    => array(
201
-                'ee-dtt-ticket-metabox' => array(
202
-                    'DTT_TRASH_BLOCK'       => array(
203
-                        'main_warning'            => esc_html__(
204
-                            'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
205
-                            'event_espresso'
206
-                        ),
207
-                        'after_warning'           => esc_html__(
208
-                            'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
209
-                            'event_espresso'
210
-                        ),
211
-                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
212
-                                                     . esc_html__('Cancel', 'event_espresso') . '</button>',
213
-                        'close_button'            => '<button class="button-secondary ee-modal-cancel">'
214
-                                                     . esc_html__('Close', 'event_espresso') . '</button>',
215
-                        'single_warning_from_tkt' => esc_html__(
216
-                            'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
217
-                            'event_espresso'
218
-                        ),
219
-                        'single_warning_from_dtt' => esc_html__(
220
-                            'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
221
-                            'event_espresso'
222
-                        ),
223
-                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
224
-                                                     . esc_html__('Dismiss', 'event_espresso') . '</button>',
225
-                    ),
226
-                    'DTT_ERROR_MSG'         => array(
227
-                        'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
228
-                        'dismiss_button' => '<div class="save-cancel-button-container">'
229
-                                            . '<button class="button-secondary ee-modal-cancel">'
230
-                                            . esc_html__('Dismiss', 'event_espresso')
231
-                                            . '</button></div>',
232
-                    ),
233
-                    'DTT_OVERSELL_WARNING'  => array(
234
-                        'datetime_ticket' => esc_html__(
235
-                            'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
236
-                            'event_espresso'
237
-                        ),
238
-                        'ticket_datetime' => esc_html__(
239
-                            'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
240
-                            'event_espresso'
241
-                        ),
242
-                    ),
243
-                    'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
244
-                        $this->_date_format_strings['date'],
245
-                        $this->_date_format_strings['time']
246
-                    ),
247
-                    'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
248
-                ),
249
-            ),
250
-        );
251
-    }
176
+	/**
177
+	 * @return void
178
+	 */
179
+	protected function _set_scripts_styles()
180
+	{
181
+		$this->_scripts_styles = array(
182
+			'registers'   => array(
183
+				'ee-tickets-datetimes-css' => array(
184
+					'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
185
+					'type' => 'css',
186
+				),
187
+				'ee-dtt-ticket-metabox'    => array(
188
+					'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
189
+					'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
190
+				),
191
+			),
192
+			'deregisters' => array(
193
+				'event-editor-css'       => array('type' => 'css'),
194
+				'event-datetime-metabox' => array('type' => 'js'),
195
+			),
196
+			'enqueues'    => array(
197
+				'ee-tickets-datetimes-css' => array('edit', 'create_new'),
198
+				'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
199
+			),
200
+			'localize'    => array(
201
+				'ee-dtt-ticket-metabox' => array(
202
+					'DTT_TRASH_BLOCK'       => array(
203
+						'main_warning'            => esc_html__(
204
+							'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
205
+							'event_espresso'
206
+						),
207
+						'after_warning'           => esc_html__(
208
+							'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
209
+							'event_espresso'
210
+						),
211
+						'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
212
+													 . esc_html__('Cancel', 'event_espresso') . '</button>',
213
+						'close_button'            => '<button class="button-secondary ee-modal-cancel">'
214
+													 . esc_html__('Close', 'event_espresso') . '</button>',
215
+						'single_warning_from_tkt' => esc_html__(
216
+							'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
217
+							'event_espresso'
218
+						),
219
+						'single_warning_from_dtt' => esc_html__(
220
+							'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
221
+							'event_espresso'
222
+						),
223
+						'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
224
+													 . esc_html__('Dismiss', 'event_espresso') . '</button>',
225
+					),
226
+					'DTT_ERROR_MSG'         => array(
227
+						'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
228
+						'dismiss_button' => '<div class="save-cancel-button-container">'
229
+											. '<button class="button-secondary ee-modal-cancel">'
230
+											. esc_html__('Dismiss', 'event_espresso')
231
+											. '</button></div>',
232
+					),
233
+					'DTT_OVERSELL_WARNING'  => array(
234
+						'datetime_ticket' => esc_html__(
235
+							'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
236
+							'event_espresso'
237
+						),
238
+						'ticket_datetime' => esc_html__(
239
+							'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
240
+							'event_espresso'
241
+						),
242
+					),
243
+					'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
244
+						$this->_date_format_strings['date'],
245
+						$this->_date_format_strings['time']
246
+					),
247
+					'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
248
+				),
249
+			),
250
+		);
251
+	}
252 252
 
253 253
 
254
-    /**
255
-     * @param array $update_callbacks
256
-     * @return array
257
-     */
258
-    public function caf_updates(array $update_callbacks)
259
-    {
260
-        foreach ($update_callbacks as $key => $callback) {
261
-            if ($callback[1] === '_default_tickets_update') {
262
-                unset($update_callbacks[ $key ]);
263
-            }
264
-        }
265
-        $update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
266
-        return $update_callbacks;
267
-    }
254
+	/**
255
+	 * @param array $update_callbacks
256
+	 * @return array
257
+	 */
258
+	public function caf_updates(array $update_callbacks)
259
+	{
260
+		foreach ($update_callbacks as $key => $callback) {
261
+			if ($callback[1] === '_default_tickets_update') {
262
+				unset($update_callbacks[ $key ]);
263
+			}
264
+		}
265
+		$update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
266
+		return $update_callbacks;
267
+	}
268 268
 
269 269
 
270
-    /**
271
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
272
-     *
273
-     * @param  EE_Event $event The Event object we're attaching data to
274
-     * @param  array    $data  The request data from the form
275
-     * @throws ReflectionException
276
-     * @throws Exception
277
-     * @throws InvalidInterfaceException
278
-     * @throws InvalidDataTypeException
279
-     * @throws EE_Error
280
-     * @throws InvalidArgumentException
281
-     */
282
-    public function datetime_and_tickets_caf_update($event, $data)
283
-    {
284
-        //first we need to start with datetimes cause they are the "root" items attached to events.
285
-        $saved_datetimes = $this->_update_datetimes($event, $data);
286
-        //next tackle the tickets (and prices?)
287
-        $this->_update_tickets($event, $saved_datetimes, $data);
288
-    }
270
+	/**
271
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
272
+	 *
273
+	 * @param  EE_Event $event The Event object we're attaching data to
274
+	 * @param  array    $data  The request data from the form
275
+	 * @throws ReflectionException
276
+	 * @throws Exception
277
+	 * @throws InvalidInterfaceException
278
+	 * @throws InvalidDataTypeException
279
+	 * @throws EE_Error
280
+	 * @throws InvalidArgumentException
281
+	 */
282
+	public function datetime_and_tickets_caf_update($event, $data)
283
+	{
284
+		//first we need to start with datetimes cause they are the "root" items attached to events.
285
+		$saved_datetimes = $this->_update_datetimes($event, $data);
286
+		//next tackle the tickets (and prices?)
287
+		$this->_update_tickets($event, $saved_datetimes, $data);
288
+	}
289 289
 
290 290
 
291
-    /**
292
-     * update event_datetimes
293
-     *
294
-     * @param  EE_Event $event Event being updated
295
-     * @param  array    $data  the request data from the form
296
-     * @return EE_Datetime[]
297
-     * @throws Exception
298
-     * @throws ReflectionException
299
-     * @throws InvalidInterfaceException
300
-     * @throws InvalidDataTypeException
301
-     * @throws InvalidArgumentException
302
-     * @throws EE_Error
303
-     */
304
-    protected function _update_datetimes($event, $data)
305
-    {
306
-        $timezone       = isset($data['timezone_string']) ? $data['timezone_string'] : null;
307
-        $saved_dtt_ids  = array();
308
-        $saved_dtt_objs = array();
309
-        if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
310
-            throw new InvalidArgumentException(
311
-                esc_html__(
312
-                    'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
313
-                    'event_espresso'
314
-                )
315
-            );
316
-        }
317
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
318
-            //trim all values to ensure any excess whitespace is removed.
319
-            $datetime_data                = array_map(
320
-                function ($datetime_data)
321
-                {
322
-                    return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
323
-                },
324
-                $datetime_data
325
-            );
326
-            $datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
327
-                                            && ! empty($datetime_data['DTT_EVT_end'])
328
-                ? $datetime_data['DTT_EVT_end']
329
-                : $datetime_data['DTT_EVT_start'];
330
-            $datetime_values              = array(
331
-                'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
332
-                    ? $datetime_data['DTT_ID']
333
-                    : null,
334
-                'DTT_name'        => ! empty($datetime_data['DTT_name'])
335
-                    ? $datetime_data['DTT_name']
336
-                    : '',
337
-                'DTT_description' => ! empty($datetime_data['DTT_description'])
338
-                    ? $datetime_data['DTT_description']
339
-                    : '',
340
-                'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
341
-                'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
342
-                'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
343
-                    ? EE_INF
344
-                    : $datetime_data['DTT_reg_limit'],
345
-                'DTT_order'       => ! isset($datetime_data['DTT_order'])
346
-                    ? $row
347
-                    : $datetime_data['DTT_order'],
348
-            );
349
-            // if we have an id then let's get existing object first and then set the new values.
350
-            // Otherwise we instantiate a new object for save.
351
-            if (! empty($datetime_data['DTT_ID'])) {
352
-                $datetime = EE_Registry::instance()
353
-                                       ->load_model('Datetime', array($timezone))
354
-                                       ->get_one_by_ID($datetime_data['DTT_ID']);
355
-                //set date and time format according to what is set in this class.
356
-                $datetime->set_date_format($this->_date_format_strings['date']);
357
-                $datetime->set_time_format($this->_date_format_strings['time']);
358
-                foreach ($datetime_values as $field => $value) {
359
-                    $datetime->set($field, $value);
360
-                }
361
-                // make sure the $dtt_id here is saved just in case
362
-                // after the add_relation_to() the autosave replaces it.
363
-                // We need to do this so we dont' TRASH the parent DTT.
364
-                // (save the ID for both key and value to avoid duplications)
365
-                $saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
366
-            } else {
367
-                $datetime = EE_Registry::instance()->load_class(
368
-                    'Datetime',
369
-                    array(
370
-                        $datetime_values,
371
-                        $timezone,
372
-                        array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
373
-                    ),
374
-                    false,
375
-                    false
376
-                );
377
-                foreach ($datetime_values as $field => $value) {
378
-                    $datetime->set($field, $value);
379
-                }
380
-            }
381
-            $datetime->save();
382
-            $datetime = $event->_add_relation_to($datetime, 'Datetime');
383
-            // before going any further make sure our dates are setup correctly
384
-            // so that the end date is always equal or greater than the start date.
385
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
386
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
387
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
388
-                $datetime->save();
389
-            }
390
-            //	now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
391
-            // because it is possible there was a new one created for the autosave.
392
-            // (save the ID for both key and value to avoid duplications)
393
-            $DTT_ID                   = $datetime->ID();
394
-            $saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
395
-            $saved_dtt_objs[ $row ]   = $datetime;
396
-            //todo if ANY of these updates fail then we want the appropriate global error message.
397
-        }
398
-        $event->save();
399
-        // now we need to REMOVE any datetimes that got deleted.
400
-        // Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
401
-        // So its safe to permanently delete at this point.
402
-        $old_datetimes = explode(',', $data['datetime_IDs']);
403
-        $old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
404
-        if (is_array($old_datetimes)) {
405
-            $datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
406
-            foreach ($datetimes_to_delete as $id) {
407
-                $id = absint($id);
408
-                if (empty($id)) {
409
-                    continue;
410
-                }
411
-                $dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
412
-                //remove tkt relationships.
413
-                $related_tickets = $dtt_to_remove->get_many_related('Ticket');
414
-                foreach ($related_tickets as $tkt) {
415
-                    $dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
416
-                }
417
-                $event->_remove_relation_to($id, 'Datetime');
418
-                $dtt_to_remove->refresh_cache_of_related_objects();
419
-            }
420
-        }
421
-        return $saved_dtt_objs;
422
-    }
291
+	/**
292
+	 * update event_datetimes
293
+	 *
294
+	 * @param  EE_Event $event Event being updated
295
+	 * @param  array    $data  the request data from the form
296
+	 * @return EE_Datetime[]
297
+	 * @throws Exception
298
+	 * @throws ReflectionException
299
+	 * @throws InvalidInterfaceException
300
+	 * @throws InvalidDataTypeException
301
+	 * @throws InvalidArgumentException
302
+	 * @throws EE_Error
303
+	 */
304
+	protected function _update_datetimes($event, $data)
305
+	{
306
+		$timezone       = isset($data['timezone_string']) ? $data['timezone_string'] : null;
307
+		$saved_dtt_ids  = array();
308
+		$saved_dtt_objs = array();
309
+		if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
310
+			throw new InvalidArgumentException(
311
+				esc_html__(
312
+					'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
313
+					'event_espresso'
314
+				)
315
+			);
316
+		}
317
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
318
+			//trim all values to ensure any excess whitespace is removed.
319
+			$datetime_data                = array_map(
320
+				function ($datetime_data)
321
+				{
322
+					return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
323
+				},
324
+				$datetime_data
325
+			);
326
+			$datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
327
+											&& ! empty($datetime_data['DTT_EVT_end'])
328
+				? $datetime_data['DTT_EVT_end']
329
+				: $datetime_data['DTT_EVT_start'];
330
+			$datetime_values              = array(
331
+				'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
332
+					? $datetime_data['DTT_ID']
333
+					: null,
334
+				'DTT_name'        => ! empty($datetime_data['DTT_name'])
335
+					? $datetime_data['DTT_name']
336
+					: '',
337
+				'DTT_description' => ! empty($datetime_data['DTT_description'])
338
+					? $datetime_data['DTT_description']
339
+					: '',
340
+				'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
341
+				'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
342
+				'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
343
+					? EE_INF
344
+					: $datetime_data['DTT_reg_limit'],
345
+				'DTT_order'       => ! isset($datetime_data['DTT_order'])
346
+					? $row
347
+					: $datetime_data['DTT_order'],
348
+			);
349
+			// if we have an id then let's get existing object first and then set the new values.
350
+			// Otherwise we instantiate a new object for save.
351
+			if (! empty($datetime_data['DTT_ID'])) {
352
+				$datetime = EE_Registry::instance()
353
+									   ->load_model('Datetime', array($timezone))
354
+									   ->get_one_by_ID($datetime_data['DTT_ID']);
355
+				//set date and time format according to what is set in this class.
356
+				$datetime->set_date_format($this->_date_format_strings['date']);
357
+				$datetime->set_time_format($this->_date_format_strings['time']);
358
+				foreach ($datetime_values as $field => $value) {
359
+					$datetime->set($field, $value);
360
+				}
361
+				// make sure the $dtt_id here is saved just in case
362
+				// after the add_relation_to() the autosave replaces it.
363
+				// We need to do this so we dont' TRASH the parent DTT.
364
+				// (save the ID for both key and value to avoid duplications)
365
+				$saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
366
+			} else {
367
+				$datetime = EE_Registry::instance()->load_class(
368
+					'Datetime',
369
+					array(
370
+						$datetime_values,
371
+						$timezone,
372
+						array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
373
+					),
374
+					false,
375
+					false
376
+				);
377
+				foreach ($datetime_values as $field => $value) {
378
+					$datetime->set($field, $value);
379
+				}
380
+			}
381
+			$datetime->save();
382
+			$datetime = $event->_add_relation_to($datetime, 'Datetime');
383
+			// before going any further make sure our dates are setup correctly
384
+			// so that the end date is always equal or greater than the start date.
385
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
386
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
387
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
388
+				$datetime->save();
389
+			}
390
+			//	now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
391
+			// because it is possible there was a new one created for the autosave.
392
+			// (save the ID for both key and value to avoid duplications)
393
+			$DTT_ID                   = $datetime->ID();
394
+			$saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
395
+			$saved_dtt_objs[ $row ]   = $datetime;
396
+			//todo if ANY of these updates fail then we want the appropriate global error message.
397
+		}
398
+		$event->save();
399
+		// now we need to REMOVE any datetimes that got deleted.
400
+		// Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
401
+		// So its safe to permanently delete at this point.
402
+		$old_datetimes = explode(',', $data['datetime_IDs']);
403
+		$old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
404
+		if (is_array($old_datetimes)) {
405
+			$datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
406
+			foreach ($datetimes_to_delete as $id) {
407
+				$id = absint($id);
408
+				if (empty($id)) {
409
+					continue;
410
+				}
411
+				$dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
412
+				//remove tkt relationships.
413
+				$related_tickets = $dtt_to_remove->get_many_related('Ticket');
414
+				foreach ($related_tickets as $tkt) {
415
+					$dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
416
+				}
417
+				$event->_remove_relation_to($id, 'Datetime');
418
+				$dtt_to_remove->refresh_cache_of_related_objects();
419
+			}
420
+		}
421
+		return $saved_dtt_objs;
422
+	}
423 423
 
424 424
 
425
-    /**
426
-     * update tickets
427
-     *
428
-     * @param  EE_Event      $event           Event object being updated
429
-     * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
430
-     * @param  array         $data            incoming request data
431
-     * @return EE_Ticket[]
432
-     * @throws Exception
433
-     * @throws ReflectionException
434
-     * @throws InvalidInterfaceException
435
-     * @throws InvalidDataTypeException
436
-     * @throws InvalidArgumentException
437
-     * @throws EE_Error
438
-     */
439
-    protected function _update_tickets($event, $saved_datetimes, $data)
440
-    {
441
-        $new_tkt     = null;
442
-        $new_default = null;
443
-        //stripslashes because WP filtered the $_POST ($data) array to add slashes
444
-        $data          = stripslashes_deep($data);
445
-        $timezone      = isset($data['timezone_string']) ? $data['timezone_string'] : null;
446
-        $saved_tickets = $datetimes_on_existing = array();
447
-        $old_tickets   = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
448
-        if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
449
-            throw new InvalidArgumentException(
450
-                esc_html__(
451
-                    'The "edit_tickets" array is invalid therefore the event can not be updated.',
452
-                    'event_espresso'
453
-                )
454
-            );
455
-        }
456
-        foreach ($data['edit_tickets'] as $row => $tkt) {
457
-            $update_prices = $create_new_TKT = false;
458
-            // figure out what datetimes were added to the ticket
459
-            // and what datetimes were removed from the ticket in the session.
460
-            $starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
461
-            $tkt_dtt_rows          = explode(',', $data['ticket_datetime_rows'][ $row ]);
462
-            $datetimes_added       = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
463
-            $datetimes_removed     = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
464
-            // trim inputs to ensure any excess whitespace is removed.
465
-            $tkt = array_map(
466
-                function ($ticket_data)
467
-                {
468
-                    return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
469
-                },
470
-                $tkt
471
-            );
472
-            // note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
473
-            // because we're doing calculations prior to using the models.
474
-            // note incoming ['TKT_price'] value is already in standard notation (via js).
475
-            $ticket_price = isset($tkt['TKT_price'])
476
-                ? round((float) $tkt['TKT_price'], 3)
477
-                : 0;
478
-            //note incoming base price needs converted from localized value.
479
-            $base_price = isset($tkt['TKT_base_price'])
480
-                ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
481
-                : 0;
482
-            //if ticket price == 0 and $base_price != 0 then ticket price == base_price
483
-            $ticket_price  = $ticket_price === 0 && $base_price !== 0
484
-                ? $base_price
485
-                : $ticket_price;
486
-            $base_price_id = isset($tkt['TKT_base_price_ID'])
487
-                ? $tkt['TKT_base_price_ID']
488
-                : 0;
489
-            $price_rows    = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
490
-                ? $data['edit_prices'][ $row ]
491
-                : array();
492
-            $now           = null;
493
-            if (empty($tkt['TKT_start_date'])) {
494
-                //lets' use now in the set timezone.
495
-                $now                   = new DateTime('now', new DateTimeZone($event->get_timezone()));
496
-                $tkt['TKT_start_date'] = $now->format($this->_date_time_format);
497
-            }
498
-            if (empty($tkt['TKT_end_date'])) {
499
-                /**
500
-                 * set the TKT_end_date to the first datetime attached to the ticket.
501
-                 */
502
-                $first_dtt           = $saved_datetimes[ reset($tkt_dtt_rows) ];
503
-                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
504
-            }
505
-            $TKT_values = array(
506
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
507
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
508
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
509
-                'TKT_description' => ! empty($tkt['TKT_description'])
510
-                                     && $tkt['TKT_description'] !== esc_html__(
511
-                    'You can modify this description',
512
-                    'event_espresso'
513
-                )
514
-                    ? $tkt['TKT_description']
515
-                    : '',
516
-                'TKT_start_date'  => $tkt['TKT_start_date'],
517
-                'TKT_end_date'    => $tkt['TKT_end_date'],
518
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
519
-                    ? EE_INF
520
-                    : $tkt['TKT_qty'],
521
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
522
-                    ? EE_INF
523
-                    : $tkt['TKT_uses'],
524
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
525
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
526
-                'TKT_row'         => $row,
527
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
528
-                'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
529
-                'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
530
-                'TKT_price'       => $ticket_price,
531
-            );
532
-            // if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
533
-            // which means in turn that the prices will become new prices as well.
534
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
535
-                $TKT_values['TKT_ID']         = 0;
536
-                $TKT_values['TKT_is_default'] = 0;
537
-                $update_prices                = true;
538
-            }
539
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
540
-            // we actually do our saves ahead of doing any add_relations to
541
-            // because its entirely possible that this ticket wasn't removed or added to any datetime in the session
542
-            // but DID have it's items modified.
543
-            // keep in mind that if the TKT has been sold (and we have changed pricing information),
544
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
545
-            if (absint($TKT_values['TKT_ID'])) {
546
-                $ticket = EE_Registry::instance()
547
-                                     ->load_model('Ticket', array($timezone))
548
-                                     ->get_one_by_ID($tkt['TKT_ID']);
549
-                if ($ticket instanceof EE_Ticket) {
550
-                    $ticket = $this->_update_ticket_datetimes(
551
-                        $ticket,
552
-                        $saved_datetimes,
553
-                        $datetimes_added,
554
-                        $datetimes_removed
555
-                    );
556
-                    // are there any registrations using this ticket ?
557
-                    $tickets_sold = $ticket->count_related(
558
-                        'Registration',
559
-                        array(
560
-                            array(
561
-                                'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
562
-                            ),
563
-                        )
564
-                    );
565
-                    //set ticket formats
566
-                    $ticket->set_date_format($this->_date_format_strings['date']);
567
-                    $ticket->set_time_format($this->_date_format_strings['time']);
568
-                    // let's just check the total price for the existing ticket
569
-                    // and determine if it matches the new total price.
570
-                    // if they are different then we create a new ticket (if tickets sold)
571
-                    // if they aren't different then we go ahead and modify existing ticket.
572
-                    $create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
573
-                    //set new values
574
-                    foreach ($TKT_values as $field => $value) {
575
-                        if ($field === 'TKT_qty') {
576
-                            $ticket->set_qty($value);
577
-                        } else {
578
-                            $ticket->set($field, $value);
579
-                        }
580
-                    }
581
-                    // if $create_new_TKT is false then we can safely update the existing ticket.
582
-                    // Otherwise we have to create a new ticket.
583
-                    if ($create_new_TKT) {
584
-                        $new_tkt = $this->_duplicate_ticket(
585
-                            $ticket,
586
-                            $price_rows,
587
-                            $ticket_price,
588
-                            $base_price,
589
-                            $base_price_id
590
-                        );
591
-                    }
592
-                }
593
-            } else {
594
-                // no TKT_id so a new TKT
595
-                $ticket = EE_Ticket::new_instance(
596
-                    $TKT_values,
597
-                    $timezone,
598
-                    array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
599
-                );
600
-                if ($ticket instanceof EE_Ticket) {
601
-                    // make sure ticket has an ID of setting relations won't work
602
-                    $ticket->save();
603
-                    $ticket        = $this->_update_ticket_datetimes(
604
-                        $ticket,
605
-                        $saved_datetimes,
606
-                        $datetimes_added,
607
-                        $datetimes_removed
608
-                    );
609
-                    $update_prices = true;
610
-                }
611
-            }
612
-            //make sure any current values have been saved.
613
-            //$ticket->save();
614
-            // before going any further make sure our dates are setup correctly
615
-            // so that the end date is always equal or greater than the start date.
616
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
617
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
618
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
619
-            }
620
-            //let's make sure the base price is handled
621
-            $ticket = ! $create_new_TKT
622
-                ? $this->_add_prices_to_ticket(
623
-                    array(),
624
-                    $ticket,
625
-                    $update_prices,
626
-                    $base_price,
627
-                    $base_price_id
628
-                )
629
-                : $ticket;
630
-            //add/update price_modifiers
631
-            $ticket = ! $create_new_TKT
632
-                ? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
633
-                : $ticket;
634
-            //need to make sue that the TKT_price is accurate after saving the prices.
635
-            $ticket->ensure_TKT_Price_correct();
636
-            //handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
637
-            if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
638
-                $update_prices = true;
639
-                $new_default   = clone $ticket;
640
-                $new_default->set('TKT_ID', 0);
641
-                $new_default->set('TKT_is_default', 1);
642
-                $new_default->set('TKT_row', 1);
643
-                $new_default->set('TKT_price', $ticket_price);
644
-                // remove any dtt relations cause we DON'T want dtt relations attached
645
-                // (note this is just removing the cached relations in the object)
646
-                $new_default->_remove_relations('Datetime');
647
-                //todo we need to add the current attached prices as new prices to the new default ticket.
648
-                $new_default = $this->_add_prices_to_ticket(
649
-                    $price_rows,
650
-                    $new_default,
651
-                    $update_prices
652
-                );
653
-                //don't forget the base price!
654
-                $new_default = $this->_add_prices_to_ticket(
655
-                    array(),
656
-                    $new_default,
657
-                    $update_prices,
658
-                    $base_price,
659
-                    $base_price_id
660
-                );
661
-                $new_default->save();
662
-                do_action(
663
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
664
-                    $new_default,
665
-                    $row,
666
-                    $ticket,
667
-                    $data
668
-                );
669
-            }
670
-            // DO ALL dtt relationships for both current tickets and any archived tickets
671
-            // for the given dtt that are related to the current ticket.
672
-            // TODO... not sure exactly how we're going to do this considering we don't know
673
-            // what current ticket the archived tickets are related to
674
-            // (and TKT_parent is used for autosaves so that's not a field we can reliably use).
675
-            //let's assign any tickets that have been setup to the saved_tickets tracker
676
-            //save existing TKT
677
-            $ticket->save();
678
-            if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
679
-                //save new TKT
680
-                $new_tkt->save();
681
-                //add new ticket to array
682
-                $saved_tickets[ $new_tkt->ID() ] = $new_tkt;
683
-                do_action(
684
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
685
-                    $new_tkt,
686
-                    $row,
687
-                    $tkt,
688
-                    $data
689
-                );
690
-            } else {
691
-                //add tkt to saved tkts
692
-                $saved_tickets[ $ticket->ID() ] = $ticket;
693
-                do_action(
694
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
695
-                    $ticket,
696
-                    $row,
697
-                    $tkt,
698
-                    $data
699
-                );
700
-            }
701
-        }
702
-        // now we need to handle tickets actually "deleted permanently".
703
-        // There are cases where we'd want this to happen
704
-        // (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
705
-        // Or a draft event was saved and in the process of editing a ticket is trashed.
706
-        // No sense in keeping all the related data in the db!
707
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
708
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
709
-        foreach ($tickets_removed as $id) {
710
-            $id = absint($id);
711
-            //get the ticket for this id
712
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
713
-            //if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
714
-            if ($tkt_to_remove->get('TKT_is_default')) {
715
-                continue;
716
-            }
717
-            // if this tkt has any registrations attached so then we just ARCHIVE
718
-            // because we don't actually permanently delete these tickets.
719
-            if ($tkt_to_remove->count_related('Registration') > 0) {
720
-                $tkt_to_remove->delete();
721
-                continue;
722
-            }
723
-            // need to get all the related datetimes on this ticket and remove from every single one of them
724
-            // (remember this process can ONLY kick off if there are NO tkts_sold)
725
-            $datetimes = $tkt_to_remove->get_many_related('Datetime');
726
-            foreach ($datetimes as $datetime) {
727
-                $tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
728
-            }
729
-            // need to do the same for prices (except these prices can also be deleted because again,
730
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
731
-            $tkt_to_remove->delete_related_permanently('Price');
732
-            do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
733
-            // finally let's delete this ticket
734
-            // (which should not be blocked at this point b/c we've removed all our relationships)
735
-            $tkt_to_remove->delete_permanently();
736
-        }
737
-        return $saved_tickets;
738
-    }
425
+	/**
426
+	 * update tickets
427
+	 *
428
+	 * @param  EE_Event      $event           Event object being updated
429
+	 * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
430
+	 * @param  array         $data            incoming request data
431
+	 * @return EE_Ticket[]
432
+	 * @throws Exception
433
+	 * @throws ReflectionException
434
+	 * @throws InvalidInterfaceException
435
+	 * @throws InvalidDataTypeException
436
+	 * @throws InvalidArgumentException
437
+	 * @throws EE_Error
438
+	 */
439
+	protected function _update_tickets($event, $saved_datetimes, $data)
440
+	{
441
+		$new_tkt     = null;
442
+		$new_default = null;
443
+		//stripslashes because WP filtered the $_POST ($data) array to add slashes
444
+		$data          = stripslashes_deep($data);
445
+		$timezone      = isset($data['timezone_string']) ? $data['timezone_string'] : null;
446
+		$saved_tickets = $datetimes_on_existing = array();
447
+		$old_tickets   = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
448
+		if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
449
+			throw new InvalidArgumentException(
450
+				esc_html__(
451
+					'The "edit_tickets" array is invalid therefore the event can not be updated.',
452
+					'event_espresso'
453
+				)
454
+			);
455
+		}
456
+		foreach ($data['edit_tickets'] as $row => $tkt) {
457
+			$update_prices = $create_new_TKT = false;
458
+			// figure out what datetimes were added to the ticket
459
+			// and what datetimes were removed from the ticket in the session.
460
+			$starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
461
+			$tkt_dtt_rows          = explode(',', $data['ticket_datetime_rows'][ $row ]);
462
+			$datetimes_added       = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
463
+			$datetimes_removed     = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
464
+			// trim inputs to ensure any excess whitespace is removed.
465
+			$tkt = array_map(
466
+				function ($ticket_data)
467
+				{
468
+					return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
469
+				},
470
+				$tkt
471
+			);
472
+			// note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
473
+			// because we're doing calculations prior to using the models.
474
+			// note incoming ['TKT_price'] value is already in standard notation (via js).
475
+			$ticket_price = isset($tkt['TKT_price'])
476
+				? round((float) $tkt['TKT_price'], 3)
477
+				: 0;
478
+			//note incoming base price needs converted from localized value.
479
+			$base_price = isset($tkt['TKT_base_price'])
480
+				? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
481
+				: 0;
482
+			//if ticket price == 0 and $base_price != 0 then ticket price == base_price
483
+			$ticket_price  = $ticket_price === 0 && $base_price !== 0
484
+				? $base_price
485
+				: $ticket_price;
486
+			$base_price_id = isset($tkt['TKT_base_price_ID'])
487
+				? $tkt['TKT_base_price_ID']
488
+				: 0;
489
+			$price_rows    = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
490
+				? $data['edit_prices'][ $row ]
491
+				: array();
492
+			$now           = null;
493
+			if (empty($tkt['TKT_start_date'])) {
494
+				//lets' use now in the set timezone.
495
+				$now                   = new DateTime('now', new DateTimeZone($event->get_timezone()));
496
+				$tkt['TKT_start_date'] = $now->format($this->_date_time_format);
497
+			}
498
+			if (empty($tkt['TKT_end_date'])) {
499
+				/**
500
+				 * set the TKT_end_date to the first datetime attached to the ticket.
501
+				 */
502
+				$first_dtt           = $saved_datetimes[ reset($tkt_dtt_rows) ];
503
+				$tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
504
+			}
505
+			$TKT_values = array(
506
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
507
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
508
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
509
+				'TKT_description' => ! empty($tkt['TKT_description'])
510
+									 && $tkt['TKT_description'] !== esc_html__(
511
+					'You can modify this description',
512
+					'event_espresso'
513
+				)
514
+					? $tkt['TKT_description']
515
+					: '',
516
+				'TKT_start_date'  => $tkt['TKT_start_date'],
517
+				'TKT_end_date'    => $tkt['TKT_end_date'],
518
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
519
+					? EE_INF
520
+					: $tkt['TKT_qty'],
521
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
522
+					? EE_INF
523
+					: $tkt['TKT_uses'],
524
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
525
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
526
+				'TKT_row'         => $row,
527
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
528
+				'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
529
+				'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
530
+				'TKT_price'       => $ticket_price,
531
+			);
532
+			// if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
533
+			// which means in turn that the prices will become new prices as well.
534
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
535
+				$TKT_values['TKT_ID']         = 0;
536
+				$TKT_values['TKT_is_default'] = 0;
537
+				$update_prices                = true;
538
+			}
539
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
540
+			// we actually do our saves ahead of doing any add_relations to
541
+			// because its entirely possible that this ticket wasn't removed or added to any datetime in the session
542
+			// but DID have it's items modified.
543
+			// keep in mind that if the TKT has been sold (and we have changed pricing information),
544
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
545
+			if (absint($TKT_values['TKT_ID'])) {
546
+				$ticket = EE_Registry::instance()
547
+									 ->load_model('Ticket', array($timezone))
548
+									 ->get_one_by_ID($tkt['TKT_ID']);
549
+				if ($ticket instanceof EE_Ticket) {
550
+					$ticket = $this->_update_ticket_datetimes(
551
+						$ticket,
552
+						$saved_datetimes,
553
+						$datetimes_added,
554
+						$datetimes_removed
555
+					);
556
+					// are there any registrations using this ticket ?
557
+					$tickets_sold = $ticket->count_related(
558
+						'Registration',
559
+						array(
560
+							array(
561
+								'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
562
+							),
563
+						)
564
+					);
565
+					//set ticket formats
566
+					$ticket->set_date_format($this->_date_format_strings['date']);
567
+					$ticket->set_time_format($this->_date_format_strings['time']);
568
+					// let's just check the total price for the existing ticket
569
+					// and determine if it matches the new total price.
570
+					// if they are different then we create a new ticket (if tickets sold)
571
+					// if they aren't different then we go ahead and modify existing ticket.
572
+					$create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
573
+					//set new values
574
+					foreach ($TKT_values as $field => $value) {
575
+						if ($field === 'TKT_qty') {
576
+							$ticket->set_qty($value);
577
+						} else {
578
+							$ticket->set($field, $value);
579
+						}
580
+					}
581
+					// if $create_new_TKT is false then we can safely update the existing ticket.
582
+					// Otherwise we have to create a new ticket.
583
+					if ($create_new_TKT) {
584
+						$new_tkt = $this->_duplicate_ticket(
585
+							$ticket,
586
+							$price_rows,
587
+							$ticket_price,
588
+							$base_price,
589
+							$base_price_id
590
+						);
591
+					}
592
+				}
593
+			} else {
594
+				// no TKT_id so a new TKT
595
+				$ticket = EE_Ticket::new_instance(
596
+					$TKT_values,
597
+					$timezone,
598
+					array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
599
+				);
600
+				if ($ticket instanceof EE_Ticket) {
601
+					// make sure ticket has an ID of setting relations won't work
602
+					$ticket->save();
603
+					$ticket        = $this->_update_ticket_datetimes(
604
+						$ticket,
605
+						$saved_datetimes,
606
+						$datetimes_added,
607
+						$datetimes_removed
608
+					);
609
+					$update_prices = true;
610
+				}
611
+			}
612
+			//make sure any current values have been saved.
613
+			//$ticket->save();
614
+			// before going any further make sure our dates are setup correctly
615
+			// so that the end date is always equal or greater than the start date.
616
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
617
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
618
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
619
+			}
620
+			//let's make sure the base price is handled
621
+			$ticket = ! $create_new_TKT
622
+				? $this->_add_prices_to_ticket(
623
+					array(),
624
+					$ticket,
625
+					$update_prices,
626
+					$base_price,
627
+					$base_price_id
628
+				)
629
+				: $ticket;
630
+			//add/update price_modifiers
631
+			$ticket = ! $create_new_TKT
632
+				? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
633
+				: $ticket;
634
+			//need to make sue that the TKT_price is accurate after saving the prices.
635
+			$ticket->ensure_TKT_Price_correct();
636
+			//handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
637
+			if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
638
+				$update_prices = true;
639
+				$new_default   = clone $ticket;
640
+				$new_default->set('TKT_ID', 0);
641
+				$new_default->set('TKT_is_default', 1);
642
+				$new_default->set('TKT_row', 1);
643
+				$new_default->set('TKT_price', $ticket_price);
644
+				// remove any dtt relations cause we DON'T want dtt relations attached
645
+				// (note this is just removing the cached relations in the object)
646
+				$new_default->_remove_relations('Datetime');
647
+				//todo we need to add the current attached prices as new prices to the new default ticket.
648
+				$new_default = $this->_add_prices_to_ticket(
649
+					$price_rows,
650
+					$new_default,
651
+					$update_prices
652
+				);
653
+				//don't forget the base price!
654
+				$new_default = $this->_add_prices_to_ticket(
655
+					array(),
656
+					$new_default,
657
+					$update_prices,
658
+					$base_price,
659
+					$base_price_id
660
+				);
661
+				$new_default->save();
662
+				do_action(
663
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
664
+					$new_default,
665
+					$row,
666
+					$ticket,
667
+					$data
668
+				);
669
+			}
670
+			// DO ALL dtt relationships for both current tickets and any archived tickets
671
+			// for the given dtt that are related to the current ticket.
672
+			// TODO... not sure exactly how we're going to do this considering we don't know
673
+			// what current ticket the archived tickets are related to
674
+			// (and TKT_parent is used for autosaves so that's not a field we can reliably use).
675
+			//let's assign any tickets that have been setup to the saved_tickets tracker
676
+			//save existing TKT
677
+			$ticket->save();
678
+			if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
679
+				//save new TKT
680
+				$new_tkt->save();
681
+				//add new ticket to array
682
+				$saved_tickets[ $new_tkt->ID() ] = $new_tkt;
683
+				do_action(
684
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
685
+					$new_tkt,
686
+					$row,
687
+					$tkt,
688
+					$data
689
+				);
690
+			} else {
691
+				//add tkt to saved tkts
692
+				$saved_tickets[ $ticket->ID() ] = $ticket;
693
+				do_action(
694
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
695
+					$ticket,
696
+					$row,
697
+					$tkt,
698
+					$data
699
+				);
700
+			}
701
+		}
702
+		// now we need to handle tickets actually "deleted permanently".
703
+		// There are cases where we'd want this to happen
704
+		// (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
705
+		// Or a draft event was saved and in the process of editing a ticket is trashed.
706
+		// No sense in keeping all the related data in the db!
707
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
708
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
709
+		foreach ($tickets_removed as $id) {
710
+			$id = absint($id);
711
+			//get the ticket for this id
712
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
713
+			//if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
714
+			if ($tkt_to_remove->get('TKT_is_default')) {
715
+				continue;
716
+			}
717
+			// if this tkt has any registrations attached so then we just ARCHIVE
718
+			// because we don't actually permanently delete these tickets.
719
+			if ($tkt_to_remove->count_related('Registration') > 0) {
720
+				$tkt_to_remove->delete();
721
+				continue;
722
+			}
723
+			// need to get all the related datetimes on this ticket and remove from every single one of them
724
+			// (remember this process can ONLY kick off if there are NO tkts_sold)
725
+			$datetimes = $tkt_to_remove->get_many_related('Datetime');
726
+			foreach ($datetimes as $datetime) {
727
+				$tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
728
+			}
729
+			// need to do the same for prices (except these prices can also be deleted because again,
730
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
731
+			$tkt_to_remove->delete_related_permanently('Price');
732
+			do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
733
+			// finally let's delete this ticket
734
+			// (which should not be blocked at this point b/c we've removed all our relationships)
735
+			$tkt_to_remove->delete_permanently();
736
+		}
737
+		return $saved_tickets;
738
+	}
739 739
 
740 740
 
741
-    /**
742
-     * @access  protected
743
-     * @param EE_Ticket      $ticket
744
-     * @param \EE_Datetime[] $saved_datetimes
745
-     * @param \EE_Datetime[] $added_datetimes
746
-     * @param \EE_Datetime[] $removed_datetimes
747
-     * @return EE_Ticket
748
-     * @throws EE_Error
749
-     */
750
-    protected function _update_ticket_datetimes(
751
-        EE_Ticket $ticket,
752
-        $saved_datetimes = array(),
753
-        $added_datetimes = array(),
754
-        $removed_datetimes = array()
755
-    ) {
756
-        // to start we have to add the ticket to all the datetimes its supposed to be with,
757
-        // and removing the ticket from datetimes it got removed from.
758
-        // first let's add datetimes
759
-        if (! empty($added_datetimes) && is_array($added_datetimes)) {
760
-            foreach ($added_datetimes as $row_id) {
761
-                $row_id = (int) $row_id;
762
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
763
-                    $ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
764
-                    // Is this an existing ticket (has an ID) and does it have any sold?
765
-                    // If so, then we need to add that to the DTT sold because this DTT is getting added.
766
-                    if ($ticket->ID() && $ticket->sold() > 0) {
767
-                        $saved_datetimes[ $row_id ]->increase_sold($ticket->sold());
768
-                        $saved_datetimes[ $row_id ]->save();
769
-                    }
770
-                }
771
-            }
772
-        }
773
-        // then remove datetimes
774
-        if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
775
-            foreach ($removed_datetimes as $row_id) {
776
-                $row_id = (int) $row_id;
777
-                // its entirely possible that a datetime got deleted (instead of just removed from relationship.
778
-                // So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
779
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
780
-                    $ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
781
-                    // Is this an existing ticket (has an ID) and does it have any sold?
782
-                    // If so, then we need to remove it's sold from the DTT_sold.
783
-                    if ($ticket->ID() && $ticket->sold() > 0) {
784
-                        $saved_datetimes[ $row_id ]->decrease_sold($ticket->sold());
785
-                        $saved_datetimes[ $row_id ]->save();
786
-                    }
787
-                }
788
-            }
789
-        }
790
-        // cap ticket qty by datetime reg limits
791
-        $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
792
-        return $ticket;
793
-    }
741
+	/**
742
+	 * @access  protected
743
+	 * @param EE_Ticket      $ticket
744
+	 * @param \EE_Datetime[] $saved_datetimes
745
+	 * @param \EE_Datetime[] $added_datetimes
746
+	 * @param \EE_Datetime[] $removed_datetimes
747
+	 * @return EE_Ticket
748
+	 * @throws EE_Error
749
+	 */
750
+	protected function _update_ticket_datetimes(
751
+		EE_Ticket $ticket,
752
+		$saved_datetimes = array(),
753
+		$added_datetimes = array(),
754
+		$removed_datetimes = array()
755
+	) {
756
+		// to start we have to add the ticket to all the datetimes its supposed to be with,
757
+		// and removing the ticket from datetimes it got removed from.
758
+		// first let's add datetimes
759
+		if (! empty($added_datetimes) && is_array($added_datetimes)) {
760
+			foreach ($added_datetimes as $row_id) {
761
+				$row_id = (int) $row_id;
762
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
763
+					$ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
764
+					// Is this an existing ticket (has an ID) and does it have any sold?
765
+					// If so, then we need to add that to the DTT sold because this DTT is getting added.
766
+					if ($ticket->ID() && $ticket->sold() > 0) {
767
+						$saved_datetimes[ $row_id ]->increase_sold($ticket->sold());
768
+						$saved_datetimes[ $row_id ]->save();
769
+					}
770
+				}
771
+			}
772
+		}
773
+		// then remove datetimes
774
+		if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
775
+			foreach ($removed_datetimes as $row_id) {
776
+				$row_id = (int) $row_id;
777
+				// its entirely possible that a datetime got deleted (instead of just removed from relationship.
778
+				// So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
779
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
780
+					$ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
781
+					// Is this an existing ticket (has an ID) and does it have any sold?
782
+					// If so, then we need to remove it's sold from the DTT_sold.
783
+					if ($ticket->ID() && $ticket->sold() > 0) {
784
+						$saved_datetimes[ $row_id ]->decrease_sold($ticket->sold());
785
+						$saved_datetimes[ $row_id ]->save();
786
+					}
787
+				}
788
+			}
789
+		}
790
+		// cap ticket qty by datetime reg limits
791
+		$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
792
+		return $ticket;
793
+	}
794 794
 
795 795
 
796
-    /**
797
-     * @access  protected
798
-     * @param EE_Ticket $ticket
799
-     * @param array     $price_rows
800
-     * @param int       $ticket_price
801
-     * @param int       $base_price
802
-     * @param int       $base_price_id
803
-     * @return EE_Ticket
804
-     * @throws ReflectionException
805
-     * @throws InvalidArgumentException
806
-     * @throws InvalidInterfaceException
807
-     * @throws InvalidDataTypeException
808
-     * @throws EE_Error
809
-     */
810
-    protected function _duplicate_ticket(
811
-        EE_Ticket $ticket,
812
-        $price_rows = array(),
813
-        $ticket_price = 0,
814
-        $base_price = 0,
815
-        $base_price_id = 0
816
-    ) {
817
-        // create new ticket that's a copy of the existing
818
-        // except a new id of course (and not archived)
819
-        // AND has the new TKT_price associated with it.
820
-        $new_ticket = clone $ticket;
821
-        $new_ticket->set('TKT_ID', 0);
822
-        $new_ticket->set_deleted(0);
823
-        $new_ticket->set_price($ticket_price);
824
-        $new_ticket->set_sold(0);
825
-        // let's get a new ID for this ticket
826
-        $new_ticket->save();
827
-        // we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
828
-        $datetimes_on_existing = $ticket->datetimes();
829
-        $new_ticket            = $this->_update_ticket_datetimes(
830
-            $new_ticket,
831
-            $datetimes_on_existing,
832
-            array_keys($datetimes_on_existing)
833
-        );
834
-        // $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
835
-        // if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
836
-        // available.
837
-        if ($ticket->sold() > 0) {
838
-            $new_qty = $ticket->qty() - $ticket->sold();
839
-            $new_ticket->set_qty($new_qty);
840
-        }
841
-        //now we update the prices just for this ticket
842
-        $new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
843
-        //and we update the base price
844
-        $new_ticket = $this->_add_prices_to_ticket(
845
-            array(),
846
-            $new_ticket,
847
-            true,
848
-            $base_price,
849
-            $base_price_id
850
-        );
851
-        return $new_ticket;
852
-    }
796
+	/**
797
+	 * @access  protected
798
+	 * @param EE_Ticket $ticket
799
+	 * @param array     $price_rows
800
+	 * @param int       $ticket_price
801
+	 * @param int       $base_price
802
+	 * @param int       $base_price_id
803
+	 * @return EE_Ticket
804
+	 * @throws ReflectionException
805
+	 * @throws InvalidArgumentException
806
+	 * @throws InvalidInterfaceException
807
+	 * @throws InvalidDataTypeException
808
+	 * @throws EE_Error
809
+	 */
810
+	protected function _duplicate_ticket(
811
+		EE_Ticket $ticket,
812
+		$price_rows = array(),
813
+		$ticket_price = 0,
814
+		$base_price = 0,
815
+		$base_price_id = 0
816
+	) {
817
+		// create new ticket that's a copy of the existing
818
+		// except a new id of course (and not archived)
819
+		// AND has the new TKT_price associated with it.
820
+		$new_ticket = clone $ticket;
821
+		$new_ticket->set('TKT_ID', 0);
822
+		$new_ticket->set_deleted(0);
823
+		$new_ticket->set_price($ticket_price);
824
+		$new_ticket->set_sold(0);
825
+		// let's get a new ID for this ticket
826
+		$new_ticket->save();
827
+		// we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
828
+		$datetimes_on_existing = $ticket->datetimes();
829
+		$new_ticket            = $this->_update_ticket_datetimes(
830
+			$new_ticket,
831
+			$datetimes_on_existing,
832
+			array_keys($datetimes_on_existing)
833
+		);
834
+		// $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
835
+		// if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
836
+		// available.
837
+		if ($ticket->sold() > 0) {
838
+			$new_qty = $ticket->qty() - $ticket->sold();
839
+			$new_ticket->set_qty($new_qty);
840
+		}
841
+		//now we update the prices just for this ticket
842
+		$new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
843
+		//and we update the base price
844
+		$new_ticket = $this->_add_prices_to_ticket(
845
+			array(),
846
+			$new_ticket,
847
+			true,
848
+			$base_price,
849
+			$base_price_id
850
+		);
851
+		return $new_ticket;
852
+	}
853 853
 
854 854
 
855
-    /**
856
-     * This attaches a list of given prices to a ticket.
857
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
858
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
859
-     * price info and prices are automatically "archived" via the ticket.
860
-     *
861
-     * @access  private
862
-     * @param array     $prices        Array of prices from the form.
863
-     * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
864
-     * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
865
-     * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
866
-     * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
867
-     * @return EE_Ticket
868
-     * @throws ReflectionException
869
-     * @throws InvalidArgumentException
870
-     * @throws InvalidInterfaceException
871
-     * @throws InvalidDataTypeException
872
-     * @throws EE_Error
873
-     */
874
-    protected function _add_prices_to_ticket(
875
-        $prices = array(),
876
-        EE_Ticket $ticket,
877
-        $new_prices = false,
878
-        $base_price = false,
879
-        $base_price_id = false
880
-    ) {
881
-        // let's just get any current prices that may exist on the given ticket
882
-        // so we can remove any prices that got trashed in this session.
883
-        $current_prices_on_ticket = $base_price !== false
884
-            ? $ticket->base_price(true)
885
-            : $ticket->price_modifiers();
886
-        $updated_prices           = array();
887
-        // if $base_price ! FALSE then updating a base price.
888
-        if ($base_price !== false) {
889
-            $prices[1] = array(
890
-                'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
891
-                'PRT_ID'     => 1,
892
-                'PRC_amount' => $base_price,
893
-                'PRC_name'   => $ticket->get('TKT_name'),
894
-                'PRC_desc'   => $ticket->get('TKT_description'),
895
-            );
896
-        }
897
-        //possibly need to save tkt
898
-        if (! $ticket->ID()) {
899
-            $ticket->save();
900
-        }
901
-        foreach ($prices as $row => $prc) {
902
-            $prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
903
-            if (empty($prt_id)) {
904
-                continue;
905
-            } //prices MUST have a price type id.
906
-            $PRC_values = array(
907
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
908
-                'PRT_ID'         => $prt_id,
909
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
910
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
911
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
912
-                'PRC_is_default' => false,
913
-                //make sure we set PRC_is_default to false for all ticket saves from event_editor
914
-                'PRC_order'      => $row,
915
-            );
916
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
917
-                $PRC_values['PRC_ID'] = 0;
918
-                $price                = EE_Registry::instance()->load_class(
919
-                    'Price',
920
-                    array($PRC_values),
921
-                    false,
922
-                    false
923
-                );
924
-            } else {
925
-                $price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
926
-                //update this price with new values
927
-                foreach ($PRC_values as $field => $value) {
928
-                    $price->set($field, $value);
929
-                }
930
-            }
931
-            $price->save();
932
-            $updated_prices[ $price->ID() ] = $price;
933
-            $ticket->_add_relation_to($price, 'Price');
934
-        }
935
-        //now let's remove any prices that got removed from the ticket
936
-        if (! empty ($current_prices_on_ticket)) {
937
-            $current          = array_keys($current_prices_on_ticket);
938
-            $updated          = array_keys($updated_prices);
939
-            $prices_to_remove = array_diff($current, $updated);
940
-            if (! empty($prices_to_remove)) {
941
-                foreach ($prices_to_remove as $prc_id) {
942
-                    $p = $current_prices_on_ticket[ $prc_id ];
943
-                    $ticket->_remove_relation_to($p, 'Price');
944
-                    //delete permanently the price
945
-                    $p->delete_permanently();
946
-                }
947
-            }
948
-        }
949
-        return $ticket;
950
-    }
855
+	/**
856
+	 * This attaches a list of given prices to a ticket.
857
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
858
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
859
+	 * price info and prices are automatically "archived" via the ticket.
860
+	 *
861
+	 * @access  private
862
+	 * @param array     $prices        Array of prices from the form.
863
+	 * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
864
+	 * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
865
+	 * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
866
+	 * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
867
+	 * @return EE_Ticket
868
+	 * @throws ReflectionException
869
+	 * @throws InvalidArgumentException
870
+	 * @throws InvalidInterfaceException
871
+	 * @throws InvalidDataTypeException
872
+	 * @throws EE_Error
873
+	 */
874
+	protected function _add_prices_to_ticket(
875
+		$prices = array(),
876
+		EE_Ticket $ticket,
877
+		$new_prices = false,
878
+		$base_price = false,
879
+		$base_price_id = false
880
+	) {
881
+		// let's just get any current prices that may exist on the given ticket
882
+		// so we can remove any prices that got trashed in this session.
883
+		$current_prices_on_ticket = $base_price !== false
884
+			? $ticket->base_price(true)
885
+			: $ticket->price_modifiers();
886
+		$updated_prices           = array();
887
+		// if $base_price ! FALSE then updating a base price.
888
+		if ($base_price !== false) {
889
+			$prices[1] = array(
890
+				'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
891
+				'PRT_ID'     => 1,
892
+				'PRC_amount' => $base_price,
893
+				'PRC_name'   => $ticket->get('TKT_name'),
894
+				'PRC_desc'   => $ticket->get('TKT_description'),
895
+			);
896
+		}
897
+		//possibly need to save tkt
898
+		if (! $ticket->ID()) {
899
+			$ticket->save();
900
+		}
901
+		foreach ($prices as $row => $prc) {
902
+			$prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
903
+			if (empty($prt_id)) {
904
+				continue;
905
+			} //prices MUST have a price type id.
906
+			$PRC_values = array(
907
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
908
+				'PRT_ID'         => $prt_id,
909
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
910
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
911
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
912
+				'PRC_is_default' => false,
913
+				//make sure we set PRC_is_default to false for all ticket saves from event_editor
914
+				'PRC_order'      => $row,
915
+			);
916
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
917
+				$PRC_values['PRC_ID'] = 0;
918
+				$price                = EE_Registry::instance()->load_class(
919
+					'Price',
920
+					array($PRC_values),
921
+					false,
922
+					false
923
+				);
924
+			} else {
925
+				$price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
926
+				//update this price with new values
927
+				foreach ($PRC_values as $field => $value) {
928
+					$price->set($field, $value);
929
+				}
930
+			}
931
+			$price->save();
932
+			$updated_prices[ $price->ID() ] = $price;
933
+			$ticket->_add_relation_to($price, 'Price');
934
+		}
935
+		//now let's remove any prices that got removed from the ticket
936
+		if (! empty ($current_prices_on_ticket)) {
937
+			$current          = array_keys($current_prices_on_ticket);
938
+			$updated          = array_keys($updated_prices);
939
+			$prices_to_remove = array_diff($current, $updated);
940
+			if (! empty($prices_to_remove)) {
941
+				foreach ($prices_to_remove as $prc_id) {
942
+					$p = $current_prices_on_ticket[ $prc_id ];
943
+					$ticket->_remove_relation_to($p, 'Price');
944
+					//delete permanently the price
945
+					$p->delete_permanently();
946
+				}
947
+			}
948
+		}
949
+		return $ticket;
950
+	}
951 951
 
952 952
 
953
-    /**
954
-     * @param Events_Admin_Page $event_admin_obj
955
-     * @return Events_Admin_Page
956
-     */
957
-    public function autosave_handling(Events_Admin_Page $event_admin_obj)
958
-    {
959
-        return $event_admin_obj;
960
-        //doing nothing for the moment.
961
-        // todo when I get to this remember that I need to set the template args on the $event_admin_obj
962
-        // (use the set_template_args() method)
963
-        /**
964
-         * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
965
-         * 1. TKT_is_default_selector (visible)
966
-         * 2. TKT_is_default (hidden)
967
-         * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
968
-         * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
969
-         * this ticket to be saved as a default.
970
-         * The tricky part is, on an initial display on create or edit (or after manually updating),
971
-         * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
972
-         * if this is a create.  However, after an autosave, users will want some sort of indicator that
973
-         * the TKT HAS been saved as a default..
974
-         * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
975
-         * On Autosave:
976
-         * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
977
-         * then set the TKT_is_default to false.
978
-         * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
979
-         *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
980
-         * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
981
-         */
982
-    }
953
+	/**
954
+	 * @param Events_Admin_Page $event_admin_obj
955
+	 * @return Events_Admin_Page
956
+	 */
957
+	public function autosave_handling(Events_Admin_Page $event_admin_obj)
958
+	{
959
+		return $event_admin_obj;
960
+		//doing nothing for the moment.
961
+		// todo when I get to this remember that I need to set the template args on the $event_admin_obj
962
+		// (use the set_template_args() method)
963
+		/**
964
+		 * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
965
+		 * 1. TKT_is_default_selector (visible)
966
+		 * 2. TKT_is_default (hidden)
967
+		 * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
968
+		 * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
969
+		 * this ticket to be saved as a default.
970
+		 * The tricky part is, on an initial display on create or edit (or after manually updating),
971
+		 * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
972
+		 * if this is a create.  However, after an autosave, users will want some sort of indicator that
973
+		 * the TKT HAS been saved as a default..
974
+		 * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
975
+		 * On Autosave:
976
+		 * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
977
+		 * then set the TKT_is_default to false.
978
+		 * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
979
+		 *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
980
+		 * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
981
+		 */
982
+	}
983 983
 
984 984
 
985
-    /**
986
-     * @throws ReflectionException
987
-     * @throws InvalidArgumentException
988
-     * @throws InvalidInterfaceException
989
-     * @throws InvalidDataTypeException
990
-     * @throws DomainException
991
-     * @throws EE_Error
992
-     */
993
-    public function pricing_metabox()
994
-    {
995
-        $existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
996
-        $event                 = $this->_adminpage_obj->get_cpt_model_obj();
997
-        //set is_creating_event property.
998
-        $EVT_ID                   = $event->ID();
999
-        $this->_is_creating_event = empty($this->_req_data['post']);
1000
-        //default main template args
1001
-        $main_template_args = array(
1002
-            'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1003
-                'event_editor_event_datetimes_help_tab',
1004
-                $this->_adminpage_obj->page_slug,
1005
-                $this->_adminpage_obj->get_req_action(),
1006
-                false,
1007
-                false
1008
-            ),
1009
-            // todo need to add a filter to the template for the help text
1010
-            // in the Events_Admin_Page core file so we can add further help
1011
-            'existing_datetime_ids'    => '',
1012
-            'total_dtt_rows'           => 1,
1013
-            'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1014
-                'add_new_dtt_info',
1015
-                $this->_adminpage_obj->page_slug,
1016
-                $this->_adminpage_obj->get_req_action(),
1017
-                false,
1018
-                false
1019
-            ),
1020
-            //todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1021
-            'datetime_rows'            => '',
1022
-            'show_tickets_container'   => '',
1023
-            //$this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1024
-            'ticket_rows'              => '',
1025
-            'existing_ticket_ids'      => '',
1026
-            'total_ticket_rows'        => 1,
1027
-            'ticket_js_structure'      => '',
1028
-            'ee_collapsible_status'    => ' ee-collapsible-open'
1029
-            //$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1030
-        );
1031
-        $timezone           = $event instanceof EE_Event ? $event->timezone_string() : null;
1032
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1033
-        /**
1034
-         * 1. Start with retrieving Datetimes
1035
-         * 2. For each datetime get related tickets
1036
-         * 3. For each ticket get related prices
1037
-         */
1038
-        /** @var EEM_Datetime $datetime_model */
1039
-        $datetime_model                       = EE_Registry::instance()->load_model('Datetime', array($timezone));
1040
-        $datetimes                            = $datetime_model->get_all_event_dates($EVT_ID);
1041
-        $main_template_args['total_dtt_rows'] = count($datetimes);
1042
-        /**
1043
-         * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1044
-         * for why we are counting $datetime_row and then setting that on the Datetime object
1045
-         */
1046
-        $datetime_row = 1;
1047
-        foreach ($datetimes as $datetime) {
1048
-            $DTT_ID = $datetime->get('DTT_ID');
1049
-            $datetime->set('DTT_order', $datetime_row);
1050
-            $existing_datetime_ids[] = $DTT_ID;
1051
-            //tickets attached
1052
-            $related_tickets = $datetime->ID() > 0
1053
-                ? $datetime->get_many_related(
1054
-                    'Ticket',
1055
-                    array(
1056
-                        array(
1057
-                            'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1058
-                        ),
1059
-                        'default_where_conditions' => 'none',
1060
-                        'order_by'                 => array('TKT_order' => 'ASC'),
1061
-                    )
1062
-                )
1063
-                : array();
1064
-            //if there are no related tickets this is likely a new event OR autodraft
1065
-            // event so we need to generate the default tickets because datetimes
1066
-            // ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1067
-            // datetime on the event.
1068
-            if (empty ($related_tickets) && count($datetimes) < 2) {
1069
-                /** @var EEM_Ticket $ticket_model */
1070
-                $ticket_model    = EE_Registry::instance()->load_model('Ticket');
1071
-                $related_tickets = $ticket_model->get_all_default_tickets();
1072
-                // this should be ordered by TKT_ID, so let's grab the first default ticket
1073
-                // (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1074
-                $default_prices      = EEM_Price::instance()->get_all_default_prices();
1075
-                $main_default_ticket = reset($related_tickets);
1076
-                if ($main_default_ticket instanceof EE_Ticket) {
1077
-                    foreach ($default_prices as $default_price) {
1078
-                        if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1079
-                            continue;
1080
-                        }
1081
-                        $main_default_ticket->cache('Price', $default_price);
1082
-                    }
1083
-                }
1084
-            }
1085
-            // we can't actually setup rows in this loop yet cause we don't know all
1086
-            // the unique tickets for this event yet (tickets are linked through all datetimes).
1087
-            // So we're going to temporarily cache some of that information.
1088
-            //loop through and setup the ticket rows and make sure the order is set.
1089
-            foreach ($related_tickets as $ticket) {
1090
-                $TKT_ID     = $ticket->get('TKT_ID');
1091
-                $ticket_row = $ticket->get('TKT_row');
1092
-                //we only want unique tickets in our final display!!
1093
-                if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1094
-                    $existing_ticket_ids[] = $TKT_ID;
1095
-                    $all_tickets[]         = $ticket;
1096
-                }
1097
-                //temporary cache of this ticket info for this datetime for later processing of datetime rows.
1098
-                $datetime_tickets[ $DTT_ID ][] = $ticket_row;
1099
-                //temporary cache of this datetime info for this ticket for later processing of ticket rows.
1100
-                if (
1101
-                    ! isset($ticket_datetimes[ $TKT_ID ])
1102
-                    || ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1103
-                ) {
1104
-                    $ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1105
-                }
1106
-            }
1107
-            $datetime_row++;
1108
-        }
1109
-        $main_template_args['total_ticket_rows']     = count($existing_ticket_ids);
1110
-        $main_template_args['existing_ticket_ids']   = implode(',', $existing_ticket_ids);
1111
-        $main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1112
-        //sort $all_tickets by order
1113
-        usort(
1114
-            $all_tickets,
1115
-            function (EE_Ticket $a, EE_Ticket $b)
1116
-            {
1117
-                $a_order = (int) $a->get('TKT_order');
1118
-                $b_order = (int) $b->get('TKT_order');
1119
-                if ($a_order === $b_order) {
1120
-                    return 0;
1121
-                }
1122
-                return ($a_order < $b_order) ? -1 : 1;
1123
-            }
1124
-        );
1125
-        // k NOW we have all the data we need for setting up the dtt rows
1126
-        // and ticket rows so we start our dtt loop again.
1127
-        $datetime_row = 1;
1128
-        foreach ($datetimes as $datetime) {
1129
-            $main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1130
-                $datetime_row,
1131
-                $datetime,
1132
-                $datetime_tickets,
1133
-                $all_tickets,
1134
-                false,
1135
-                $datetimes
1136
-            );
1137
-            $datetime_row++;
1138
-        }
1139
-        //then loop through all tickets for the ticket rows.
1140
-        $ticket_row = 1;
1141
-        foreach ($all_tickets as $ticket) {
1142
-            $main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1143
-                $ticket_row,
1144
-                $ticket,
1145
-                $ticket_datetimes,
1146
-                $datetimes,
1147
-                false,
1148
-                $all_tickets
1149
-            );
1150
-            $ticket_row++;
1151
-        }
1152
-        $main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
1153
-        EEH_Template::display_template(
1154
-            PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1155
-            $main_template_args
1156
-        );
1157
-    }
985
+	/**
986
+	 * @throws ReflectionException
987
+	 * @throws InvalidArgumentException
988
+	 * @throws InvalidInterfaceException
989
+	 * @throws InvalidDataTypeException
990
+	 * @throws DomainException
991
+	 * @throws EE_Error
992
+	 */
993
+	public function pricing_metabox()
994
+	{
995
+		$existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
996
+		$event                 = $this->_adminpage_obj->get_cpt_model_obj();
997
+		//set is_creating_event property.
998
+		$EVT_ID                   = $event->ID();
999
+		$this->_is_creating_event = empty($this->_req_data['post']);
1000
+		//default main template args
1001
+		$main_template_args = array(
1002
+			'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1003
+				'event_editor_event_datetimes_help_tab',
1004
+				$this->_adminpage_obj->page_slug,
1005
+				$this->_adminpage_obj->get_req_action(),
1006
+				false,
1007
+				false
1008
+			),
1009
+			// todo need to add a filter to the template for the help text
1010
+			// in the Events_Admin_Page core file so we can add further help
1011
+			'existing_datetime_ids'    => '',
1012
+			'total_dtt_rows'           => 1,
1013
+			'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1014
+				'add_new_dtt_info',
1015
+				$this->_adminpage_obj->page_slug,
1016
+				$this->_adminpage_obj->get_req_action(),
1017
+				false,
1018
+				false
1019
+			),
1020
+			//todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1021
+			'datetime_rows'            => '',
1022
+			'show_tickets_container'   => '',
1023
+			//$this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1024
+			'ticket_rows'              => '',
1025
+			'existing_ticket_ids'      => '',
1026
+			'total_ticket_rows'        => 1,
1027
+			'ticket_js_structure'      => '',
1028
+			'ee_collapsible_status'    => ' ee-collapsible-open'
1029
+			//$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1030
+		);
1031
+		$timezone           = $event instanceof EE_Event ? $event->timezone_string() : null;
1032
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1033
+		/**
1034
+		 * 1. Start with retrieving Datetimes
1035
+		 * 2. For each datetime get related tickets
1036
+		 * 3. For each ticket get related prices
1037
+		 */
1038
+		/** @var EEM_Datetime $datetime_model */
1039
+		$datetime_model                       = EE_Registry::instance()->load_model('Datetime', array($timezone));
1040
+		$datetimes                            = $datetime_model->get_all_event_dates($EVT_ID);
1041
+		$main_template_args['total_dtt_rows'] = count($datetimes);
1042
+		/**
1043
+		 * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1044
+		 * for why we are counting $datetime_row and then setting that on the Datetime object
1045
+		 */
1046
+		$datetime_row = 1;
1047
+		foreach ($datetimes as $datetime) {
1048
+			$DTT_ID = $datetime->get('DTT_ID');
1049
+			$datetime->set('DTT_order', $datetime_row);
1050
+			$existing_datetime_ids[] = $DTT_ID;
1051
+			//tickets attached
1052
+			$related_tickets = $datetime->ID() > 0
1053
+				? $datetime->get_many_related(
1054
+					'Ticket',
1055
+					array(
1056
+						array(
1057
+							'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1058
+						),
1059
+						'default_where_conditions' => 'none',
1060
+						'order_by'                 => array('TKT_order' => 'ASC'),
1061
+					)
1062
+				)
1063
+				: array();
1064
+			//if there are no related tickets this is likely a new event OR autodraft
1065
+			// event so we need to generate the default tickets because datetimes
1066
+			// ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1067
+			// datetime on the event.
1068
+			if (empty ($related_tickets) && count($datetimes) < 2) {
1069
+				/** @var EEM_Ticket $ticket_model */
1070
+				$ticket_model    = EE_Registry::instance()->load_model('Ticket');
1071
+				$related_tickets = $ticket_model->get_all_default_tickets();
1072
+				// this should be ordered by TKT_ID, so let's grab the first default ticket
1073
+				// (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1074
+				$default_prices      = EEM_Price::instance()->get_all_default_prices();
1075
+				$main_default_ticket = reset($related_tickets);
1076
+				if ($main_default_ticket instanceof EE_Ticket) {
1077
+					foreach ($default_prices as $default_price) {
1078
+						if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1079
+							continue;
1080
+						}
1081
+						$main_default_ticket->cache('Price', $default_price);
1082
+					}
1083
+				}
1084
+			}
1085
+			// we can't actually setup rows in this loop yet cause we don't know all
1086
+			// the unique tickets for this event yet (tickets are linked through all datetimes).
1087
+			// So we're going to temporarily cache some of that information.
1088
+			//loop through and setup the ticket rows and make sure the order is set.
1089
+			foreach ($related_tickets as $ticket) {
1090
+				$TKT_ID     = $ticket->get('TKT_ID');
1091
+				$ticket_row = $ticket->get('TKT_row');
1092
+				//we only want unique tickets in our final display!!
1093
+				if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1094
+					$existing_ticket_ids[] = $TKT_ID;
1095
+					$all_tickets[]         = $ticket;
1096
+				}
1097
+				//temporary cache of this ticket info for this datetime for later processing of datetime rows.
1098
+				$datetime_tickets[ $DTT_ID ][] = $ticket_row;
1099
+				//temporary cache of this datetime info for this ticket for later processing of ticket rows.
1100
+				if (
1101
+					! isset($ticket_datetimes[ $TKT_ID ])
1102
+					|| ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1103
+				) {
1104
+					$ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1105
+				}
1106
+			}
1107
+			$datetime_row++;
1108
+		}
1109
+		$main_template_args['total_ticket_rows']     = count($existing_ticket_ids);
1110
+		$main_template_args['existing_ticket_ids']   = implode(',', $existing_ticket_ids);
1111
+		$main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1112
+		//sort $all_tickets by order
1113
+		usort(
1114
+			$all_tickets,
1115
+			function (EE_Ticket $a, EE_Ticket $b)
1116
+			{
1117
+				$a_order = (int) $a->get('TKT_order');
1118
+				$b_order = (int) $b->get('TKT_order');
1119
+				if ($a_order === $b_order) {
1120
+					return 0;
1121
+				}
1122
+				return ($a_order < $b_order) ? -1 : 1;
1123
+			}
1124
+		);
1125
+		// k NOW we have all the data we need for setting up the dtt rows
1126
+		// and ticket rows so we start our dtt loop again.
1127
+		$datetime_row = 1;
1128
+		foreach ($datetimes as $datetime) {
1129
+			$main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1130
+				$datetime_row,
1131
+				$datetime,
1132
+				$datetime_tickets,
1133
+				$all_tickets,
1134
+				false,
1135
+				$datetimes
1136
+			);
1137
+			$datetime_row++;
1138
+		}
1139
+		//then loop through all tickets for the ticket rows.
1140
+		$ticket_row = 1;
1141
+		foreach ($all_tickets as $ticket) {
1142
+			$main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1143
+				$ticket_row,
1144
+				$ticket,
1145
+				$ticket_datetimes,
1146
+				$datetimes,
1147
+				false,
1148
+				$all_tickets
1149
+			);
1150
+			$ticket_row++;
1151
+		}
1152
+		$main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
1153
+		EEH_Template::display_template(
1154
+			PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1155
+			$main_template_args
1156
+		);
1157
+	}
1158 1158
 
1159 1159
 
1160
-    /**
1161
-     * @param int         $datetime_row
1162
-     * @param EE_Datetime $datetime
1163
-     * @param array       $datetime_tickets
1164
-     * @param array       $all_tickets
1165
-     * @param bool        $default
1166
-     * @param array       $all_datetimes
1167
-     * @return mixed
1168
-     * @throws DomainException
1169
-     * @throws EE_Error
1170
-     */
1171
-    protected function _get_datetime_row(
1172
-        $datetime_row,
1173
-        EE_Datetime $datetime,
1174
-        $datetime_tickets = array(),
1175
-        $all_tickets = array(),
1176
-        $default = false,
1177
-        $all_datetimes = array()
1178
-    ) {
1179
-        $dtt_display_template_args = array(
1180
-            'dtt_edit_row'             => $this->_get_dtt_edit_row(
1181
-                $datetime_row,
1182
-                $datetime,
1183
-                $default,
1184
-                $all_datetimes
1185
-            ),
1186
-            'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1187
-                $datetime_row,
1188
-                $datetime,
1189
-                $datetime_tickets,
1190
-                $all_tickets,
1191
-                $default
1192
-            ),
1193
-            'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1194
-        );
1195
-        return EEH_Template::display_template(
1196
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1197
-            $dtt_display_template_args,
1198
-            true
1199
-        );
1200
-    }
1160
+	/**
1161
+	 * @param int         $datetime_row
1162
+	 * @param EE_Datetime $datetime
1163
+	 * @param array       $datetime_tickets
1164
+	 * @param array       $all_tickets
1165
+	 * @param bool        $default
1166
+	 * @param array       $all_datetimes
1167
+	 * @return mixed
1168
+	 * @throws DomainException
1169
+	 * @throws EE_Error
1170
+	 */
1171
+	protected function _get_datetime_row(
1172
+		$datetime_row,
1173
+		EE_Datetime $datetime,
1174
+		$datetime_tickets = array(),
1175
+		$all_tickets = array(),
1176
+		$default = false,
1177
+		$all_datetimes = array()
1178
+	) {
1179
+		$dtt_display_template_args = array(
1180
+			'dtt_edit_row'             => $this->_get_dtt_edit_row(
1181
+				$datetime_row,
1182
+				$datetime,
1183
+				$default,
1184
+				$all_datetimes
1185
+			),
1186
+			'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1187
+				$datetime_row,
1188
+				$datetime,
1189
+				$datetime_tickets,
1190
+				$all_tickets,
1191
+				$default
1192
+			),
1193
+			'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1194
+		);
1195
+		return EEH_Template::display_template(
1196
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1197
+			$dtt_display_template_args,
1198
+			true
1199
+		);
1200
+	}
1201 1201
 
1202 1202
 
1203
-    /**
1204
-     * This method is used to generate a dtt fields  edit row.
1205
-     * The same row is used to generate a row with valid DTT objects
1206
-     * and the default row that is used as the skeleton by the js.
1207
-     *
1208
-     * @param int           $datetime_row  The row number for the row being generated.
1209
-     * @param EE_Datetime   $datetime
1210
-     * @param bool          $default       Whether a default row is being generated or not.
1211
-     * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1212
-     * @return string
1213
-     * @throws DomainException
1214
-     * @throws EE_Error
1215
-     */
1216
-    protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1217
-    {
1218
-        // if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1219
-        $default                     = ! $datetime instanceof EE_Datetime ? true : $default;
1220
-        $template_args               = array(
1221
-            'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1222
-            'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1223
-            'edit_dtt_expanded'    => '',
1224
-            'DTT_ID'               => $default ? '' : $datetime->ID(),
1225
-            'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1226
-            'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1227
-            'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1228
-            'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1229
-            'DTT_reg_limit'        => $default
1230
-                ? ''
1231
-                : $datetime->get_pretty(
1232
-                    'DTT_reg_limit',
1233
-                    'input'
1234
-                ),
1235
-            'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1236
-            'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1237
-            'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1238
-            'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1239
-                ? ''
1240
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1241
-            'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1242
-                ? 'ee-lock-icon'
1243
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1244
-            'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1245
-                ? ''
1246
-                : EE_Admin_Page::add_query_args_and_nonce(
1247
-                    array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1248
-                    REG_ADMIN_URL
1249
-                ),
1250
-        );
1251
-        $template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1252
-            ? ' style="display:none"'
1253
-            : '';
1254
-        //allow filtering of template args at this point.
1255
-        $template_args = apply_filters(
1256
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1257
-            $template_args,
1258
-            $datetime_row,
1259
-            $datetime,
1260
-            $default,
1261
-            $all_datetimes,
1262
-            $this->_is_creating_event
1263
-        );
1264
-        return EEH_Template::display_template(
1265
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1266
-            $template_args,
1267
-            true
1268
-        );
1269
-    }
1203
+	/**
1204
+	 * This method is used to generate a dtt fields  edit row.
1205
+	 * The same row is used to generate a row with valid DTT objects
1206
+	 * and the default row that is used as the skeleton by the js.
1207
+	 *
1208
+	 * @param int           $datetime_row  The row number for the row being generated.
1209
+	 * @param EE_Datetime   $datetime
1210
+	 * @param bool          $default       Whether a default row is being generated or not.
1211
+	 * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1212
+	 * @return string
1213
+	 * @throws DomainException
1214
+	 * @throws EE_Error
1215
+	 */
1216
+	protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1217
+	{
1218
+		// if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1219
+		$default                     = ! $datetime instanceof EE_Datetime ? true : $default;
1220
+		$template_args               = array(
1221
+			'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1222
+			'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1223
+			'edit_dtt_expanded'    => '',
1224
+			'DTT_ID'               => $default ? '' : $datetime->ID(),
1225
+			'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1226
+			'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1227
+			'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1228
+			'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1229
+			'DTT_reg_limit'        => $default
1230
+				? ''
1231
+				: $datetime->get_pretty(
1232
+					'DTT_reg_limit',
1233
+					'input'
1234
+				),
1235
+			'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1236
+			'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1237
+			'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1238
+			'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1239
+				? ''
1240
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1241
+			'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1242
+				? 'ee-lock-icon'
1243
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1244
+			'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1245
+				? ''
1246
+				: EE_Admin_Page::add_query_args_and_nonce(
1247
+					array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1248
+					REG_ADMIN_URL
1249
+				),
1250
+		);
1251
+		$template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1252
+			? ' style="display:none"'
1253
+			: '';
1254
+		//allow filtering of template args at this point.
1255
+		$template_args = apply_filters(
1256
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1257
+			$template_args,
1258
+			$datetime_row,
1259
+			$datetime,
1260
+			$default,
1261
+			$all_datetimes,
1262
+			$this->_is_creating_event
1263
+		);
1264
+		return EEH_Template::display_template(
1265
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1266
+			$template_args,
1267
+			true
1268
+		);
1269
+	}
1270 1270
 
1271 1271
 
1272
-    /**
1273
-     * @param int         $datetime_row
1274
-     * @param EE_Datetime $datetime
1275
-     * @param array       $datetime_tickets
1276
-     * @param array       $all_tickets
1277
-     * @param bool        $default
1278
-     * @return mixed
1279
-     * @throws DomainException
1280
-     * @throws EE_Error
1281
-     */
1282
-    protected function _get_dtt_attached_tickets_row(
1283
-        $datetime_row,
1284
-        $datetime,
1285
-        $datetime_tickets = array(),
1286
-        $all_tickets = array(),
1287
-        $default
1288
-    ) {
1289
-        $template_args = array(
1290
-            'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1291
-            'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1292
-            'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1293
-            'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1294
-            'show_tickets_row'                  => ' style="display:none;"',
1295
-            'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1296
-                'add_new_ticket_via_datetime',
1297
-                $this->_adminpage_obj->page_slug,
1298
-                $this->_adminpage_obj->get_req_action(),
1299
-                false,
1300
-                false
1301
-            ),
1302
-            //todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1303
-            'DTT_ID'                            => $default ? '' : $datetime->ID(),
1304
-        );
1305
-        //need to setup the list items (but only if this isn't a default skeleton setup)
1306
-        if (! $default) {
1307
-            $ticket_row = 1;
1308
-            foreach ($all_tickets as $ticket) {
1309
-                $template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1310
-                    $datetime_row,
1311
-                    $ticket_row,
1312
-                    $datetime,
1313
-                    $ticket,
1314
-                    $datetime_tickets,
1315
-                    $default
1316
-                );
1317
-                $ticket_row++;
1318
-            }
1319
-        }
1320
-        //filter template args at this point
1321
-        $template_args = apply_filters(
1322
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1323
-            $template_args,
1324
-            $datetime_row,
1325
-            $datetime,
1326
-            $datetime_tickets,
1327
-            $all_tickets,
1328
-            $default,
1329
-            $this->_is_creating_event
1330
-        );
1331
-        return EEH_Template::display_template(
1332
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1333
-            $template_args,
1334
-            true
1335
-        );
1336
-    }
1272
+	/**
1273
+	 * @param int         $datetime_row
1274
+	 * @param EE_Datetime $datetime
1275
+	 * @param array       $datetime_tickets
1276
+	 * @param array       $all_tickets
1277
+	 * @param bool        $default
1278
+	 * @return mixed
1279
+	 * @throws DomainException
1280
+	 * @throws EE_Error
1281
+	 */
1282
+	protected function _get_dtt_attached_tickets_row(
1283
+		$datetime_row,
1284
+		$datetime,
1285
+		$datetime_tickets = array(),
1286
+		$all_tickets = array(),
1287
+		$default
1288
+	) {
1289
+		$template_args = array(
1290
+			'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1291
+			'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1292
+			'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1293
+			'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1294
+			'show_tickets_row'                  => ' style="display:none;"',
1295
+			'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1296
+				'add_new_ticket_via_datetime',
1297
+				$this->_adminpage_obj->page_slug,
1298
+				$this->_adminpage_obj->get_req_action(),
1299
+				false,
1300
+				false
1301
+			),
1302
+			//todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1303
+			'DTT_ID'                            => $default ? '' : $datetime->ID(),
1304
+		);
1305
+		//need to setup the list items (but only if this isn't a default skeleton setup)
1306
+		if (! $default) {
1307
+			$ticket_row = 1;
1308
+			foreach ($all_tickets as $ticket) {
1309
+				$template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1310
+					$datetime_row,
1311
+					$ticket_row,
1312
+					$datetime,
1313
+					$ticket,
1314
+					$datetime_tickets,
1315
+					$default
1316
+				);
1317
+				$ticket_row++;
1318
+			}
1319
+		}
1320
+		//filter template args at this point
1321
+		$template_args = apply_filters(
1322
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1323
+			$template_args,
1324
+			$datetime_row,
1325
+			$datetime,
1326
+			$datetime_tickets,
1327
+			$all_tickets,
1328
+			$default,
1329
+			$this->_is_creating_event
1330
+		);
1331
+		return EEH_Template::display_template(
1332
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1333
+			$template_args,
1334
+			true
1335
+		);
1336
+	}
1337 1337
 
1338 1338
 
1339
-    /**
1340
-     * @param int         $datetime_row
1341
-     * @param int         $ticket_row
1342
-     * @param EE_Datetime $datetime
1343
-     * @param EE_Ticket   $ticket
1344
-     * @param array       $datetime_tickets
1345
-     * @param bool        $default
1346
-     * @return mixed
1347
-     * @throws DomainException
1348
-     * @throws EE_Error
1349
-     */
1350
-    protected function _get_datetime_tickets_list_item(
1351
-        $datetime_row,
1352
-        $ticket_row,
1353
-        $datetime,
1354
-        $ticket,
1355
-        $datetime_tickets = array(),
1356
-        $default
1357
-    ) {
1358
-        $dtt_tkts      = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1359
-            ? $datetime_tickets[ $datetime->ID() ]
1360
-            : array();
1361
-        $display_row   = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1362
-        $no_ticket     = $default && empty($ticket);
1363
-        $template_args = array(
1364
-            'dtt_row'                 => $default
1365
-                ? 'DTTNUM'
1366
-                : $datetime_row,
1367
-            'tkt_row'                 => $no_ticket
1368
-                ? 'TICKETNUM'
1369
-                : $ticket_row,
1370
-            'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1371
-                ? ' checked="checked"'
1372
-                : '',
1373
-            'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1374
-                ? ' ticket-selected'
1375
-                : '',
1376
-            'TKT_name'                => $no_ticket
1377
-                ? 'TKTNAME'
1378
-                : $ticket->get('TKT_name'),
1379
-            'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1380
-                ? ' tkt-status-' . EE_Ticket::onsale
1381
-                : ' tkt-status-' . $ticket->ticket_status(),
1382
-        );
1383
-        //filter template args
1384
-        $template_args = apply_filters(
1385
-            'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1386
-            $template_args,
1387
-            $datetime_row,
1388
-            $ticket_row,
1389
-            $datetime,
1390
-            $ticket,
1391
-            $datetime_tickets,
1392
-            $default,
1393
-            $this->_is_creating_event
1394
-        );
1395
-        return EEH_Template::display_template(
1396
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1397
-            $template_args,
1398
-            true
1399
-        );
1400
-    }
1339
+	/**
1340
+	 * @param int         $datetime_row
1341
+	 * @param int         $ticket_row
1342
+	 * @param EE_Datetime $datetime
1343
+	 * @param EE_Ticket   $ticket
1344
+	 * @param array       $datetime_tickets
1345
+	 * @param bool        $default
1346
+	 * @return mixed
1347
+	 * @throws DomainException
1348
+	 * @throws EE_Error
1349
+	 */
1350
+	protected function _get_datetime_tickets_list_item(
1351
+		$datetime_row,
1352
+		$ticket_row,
1353
+		$datetime,
1354
+		$ticket,
1355
+		$datetime_tickets = array(),
1356
+		$default
1357
+	) {
1358
+		$dtt_tkts      = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1359
+			? $datetime_tickets[ $datetime->ID() ]
1360
+			: array();
1361
+		$display_row   = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1362
+		$no_ticket     = $default && empty($ticket);
1363
+		$template_args = array(
1364
+			'dtt_row'                 => $default
1365
+				? 'DTTNUM'
1366
+				: $datetime_row,
1367
+			'tkt_row'                 => $no_ticket
1368
+				? 'TICKETNUM'
1369
+				: $ticket_row,
1370
+			'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1371
+				? ' checked="checked"'
1372
+				: '',
1373
+			'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1374
+				? ' ticket-selected'
1375
+				: '',
1376
+			'TKT_name'                => $no_ticket
1377
+				? 'TKTNAME'
1378
+				: $ticket->get('TKT_name'),
1379
+			'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1380
+				? ' tkt-status-' . EE_Ticket::onsale
1381
+				: ' tkt-status-' . $ticket->ticket_status(),
1382
+		);
1383
+		//filter template args
1384
+		$template_args = apply_filters(
1385
+			'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1386
+			$template_args,
1387
+			$datetime_row,
1388
+			$ticket_row,
1389
+			$datetime,
1390
+			$ticket,
1391
+			$datetime_tickets,
1392
+			$default,
1393
+			$this->_is_creating_event
1394
+		);
1395
+		return EEH_Template::display_template(
1396
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1397
+			$template_args,
1398
+			true
1399
+		);
1400
+	}
1401 1401
 
1402 1402
 
1403
-    /**
1404
-     * This generates the ticket row for tickets.
1405
-     * This same method is used to generate both the actual rows and the js skeleton row
1406
-     * (when default === true)
1407
-     *
1408
-     * @param int           $ticket_row       Represents the row number being generated.
1409
-     * @param               $ticket
1410
-     * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1411
-     *                                        or empty for default
1412
-     * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1413
-     * @param bool          $default          Whether default row being generated or not.
1414
-     * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1415
-     *                                        (or empty in the case of defaults)
1416
-     * @return mixed
1417
-     * @throws InvalidArgumentException
1418
-     * @throws InvalidInterfaceException
1419
-     * @throws InvalidDataTypeException
1420
-     * @throws DomainException
1421
-     * @throws EE_Error
1422
-     * @throws ReflectionException
1423
-     */
1424
-    protected function _get_ticket_row(
1425
-        $ticket_row,
1426
-        $ticket,
1427
-        $ticket_datetimes,
1428
-        $all_datetimes,
1429
-        $default = false,
1430
-        $all_tickets = array()
1431
-    ) {
1432
-        // if $ticket is not an instance of EE_Ticket then force default to true.
1433
-        $default = ! $ticket instanceof EE_Ticket ? true : $default;
1434
-        $prices  = ! empty($ticket) && ! $default ? $ticket->get_many_related('Price',
1435
-            array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))) : array();
1436
-        // if there is only one price (which would be the base price)
1437
-        // or NO prices and this ticket is a default ticket,
1438
-        // let's just make sure there are no cached default prices on the object.
1439
-        // This is done by not including any query_params.
1440
-        if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1441
-            $prices = $ticket->prices();
1442
-        }
1443
-        // check if we're dealing with a default ticket in which case
1444
-        // we don't want any starting_ticket_datetime_row values set
1445
-        // (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1446
-        // This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1447
-        $default_dtt      = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1448
-        $tkt_datetimes    = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1449
-            ? $ticket_datetimes[ $ticket->ID() ]
1450
-            : array();
1451
-        $ticket_subtotal  = $default ? 0 : $ticket->get_ticket_subtotal();
1452
-        $base_price       = $default ? null : $ticket->base_price();
1453
-        $count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1454
-        //breaking out complicated condition for ticket_status
1455
-        if ($default) {
1456
-            $ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1457
-        } else {
1458
-            $ticket_status_class = $ticket->is_default()
1459
-                ? ' tkt-status-' . EE_Ticket::onsale
1460
-                : ' tkt-status-' . $ticket->ticket_status();
1461
-        }
1462
-        //breaking out complicated condition for TKT_taxable
1463
-        if ($default) {
1464
-            $TKT_taxable = '';
1465
-        } else {
1466
-            $TKT_taxable = $ticket->taxable()
1467
-                ? ' checked="checked"'
1468
-                : '';
1469
-        }
1470
-        if ($default) {
1471
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1472
-        } elseif ($ticket->is_default()) {
1473
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1474
-        } else {
1475
-            $TKT_status = $ticket->ticket_status(true);
1476
-        }
1477
-        if ($default) {
1478
-            $TKT_min = '';
1479
-        } else {
1480
-            $TKT_min = $ticket->min();
1481
-            if ($TKT_min === -1 || $TKT_min === 0) {
1482
-                $TKT_min = '';
1483
-            }
1484
-        }
1485
-        $template_args                 = array(
1486
-            'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1487
-            'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1488
-            //on initial page load this will always be the correct order.
1489
-            'tkt_status_class'              => $ticket_status_class,
1490
-            'display_edit_tkt_row'          => ' style="display:none;"',
1491
-            'edit_tkt_expanded'             => '',
1492
-            'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1493
-            'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1494
-            'TKT_start_date'                => $default
1495
-                ? ''
1496
-                : $ticket->get_date('TKT_start_date', $this->_date_time_format),
1497
-            'TKT_end_date'                  => $default
1498
-                ? ''
1499
-                : $ticket->get_date('TKT_end_date', $this->_date_time_format),
1500
-            'TKT_status'                    => $TKT_status,
1501
-            'TKT_price'                     => $default
1502
-                ? ''
1503
-                : EEH_Template::format_currency(
1504
-                    $ticket->get_ticket_total_with_taxes(),
1505
-                    false,
1506
-                    false
1507
-                ),
1508
-            'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1509
-            'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1510
-            'TKT_qty'                       => $default
1511
-                ? ''
1512
-                : $ticket->get_pretty('TKT_qty', 'symbol'),
1513
-            'TKT_qty_for_input'             => $default
1514
-                ? ''
1515
-                : $ticket->get_pretty('TKT_qty', 'input'),
1516
-            'TKT_uses'                      => $default
1517
-                ? ''
1518
-                : $ticket->get_pretty('TKT_uses', 'input'),
1519
-            'TKT_min'                       => $TKT_min,
1520
-            'TKT_max'                       => $default
1521
-                ? ''
1522
-                : $ticket->get_pretty('TKT_max', 'input'),
1523
-            'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1524
-            'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1525
-            'TKT_registrations'             => $default
1526
-                ? 0
1527
-                : $ticket->count_registrations(
1528
-                    array(
1529
-                        array(
1530
-                            'STS_ID' => array(
1531
-                                '!=',
1532
-                                EEM_Registration::status_id_incomplete,
1533
-                            ),
1534
-                        ),
1535
-                    )
1536
-                ),
1537
-            'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1538
-            'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1539
-            'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1540
-            'TKT_required'                  => $default ? 0 : $ticket->required(),
1541
-            'TKT_is_default_selector'       => '',
1542
-            'ticket_price_rows'             => '',
1543
-            'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1544
-                ? ''
1545
-                : $base_price->get_pretty('PRC_amount', 'localized_float'),
1546
-            'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1547
-            'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1548
-                ? ''
1549
-                : ' style="display:none;"',
1550
-            'show_price_mod_button'         => count($prices) > 1
1551
-                                               || ($default && $count_price_mods > 0)
1552
-                                               || (! $default && $ticket->deleted())
1553
-                ? ' style="display:none;"'
1554
-                : '',
1555
-            'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1556
-            'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1557
-            'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1558
-            'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1559
-            'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1560
-            'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1561
-            'TKT_taxable'                   => $TKT_taxable,
1562
-            'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1563
-                ? ''
1564
-                : ' style="display:none"',
1565
-            'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1566
-            'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1567
-                $ticket_subtotal,
1568
-                false,
1569
-                false
1570
-            ),
1571
-            'TKT_subtotal_amount'           => $ticket_subtotal,
1572
-            'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1573
-            'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1574
-            'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1575
-                ? ' ticket-archived'
1576
-                : '',
1577
-            'trash_icon'                    => $ticket instanceof EE_Ticket
1578
-                                               && $ticket->deleted()
1579
-                                               && ! $ticket->is_permanently_deleteable()
1580
-                ? 'ee-lock-icon '
1581
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1582
-            'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1583
-                ? ''
1584
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1585
-        );
1586
-        $template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1587
-            ? ' style="display:none"'
1588
-            : '';
1589
-        //handle rows that should NOT be empty
1590
-        if (empty($template_args['TKT_start_date'])) {
1591
-            //if empty then the start date will be now.
1592
-            $template_args['TKT_start_date']   = date($this->_date_time_format,
1593
-                current_time('timestamp'));
1594
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1595
-        }
1596
-        if (empty($template_args['TKT_end_date'])) {
1597
-            //get the earliest datetime (if present);
1598
-            $earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1599
-                ? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1600
-                    'Datetime',
1601
-                    array('order_by' => array('DTT_EVT_start' => 'ASC'))
1602
-                )
1603
-                : null;
1604
-            if (! empty($earliest_dtt)) {
1605
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1606
-                    'DTT_EVT_start',
1607
-                    $this->_date_time_format
1608
-                );
1609
-            } else {
1610
-                //default so let's just use what's been set for the default date-time which is 30 days from now.
1611
-                $template_args['TKT_end_date'] = date(
1612
-                    $this->_date_time_format,
1613
-                    mktime(
1614
-                        24, 0, 0, date('m'), date('d') + 29, date('Y')
1615
-                    )
1616
-                );
1617
-            }
1618
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1619
-        }
1620
-        //generate ticket_datetime items
1621
-        if (! $default) {
1622
-            $datetime_row = 1;
1623
-            foreach ($all_datetimes as $datetime) {
1624
-                $template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1625
-                    $datetime_row,
1626
-                    $ticket_row,
1627
-                    $datetime,
1628
-                    $ticket,
1629
-                    $ticket_datetimes,
1630
-                    $default
1631
-                );
1632
-                $datetime_row++;
1633
-            }
1634
-        }
1635
-        $price_row = 1;
1636
-        foreach ($prices as $price) {
1637
-            if (! $price instanceof EE_Price) {
1638
-                continue;
1639
-            }
1640
-            if ($price->is_base_price()) {
1641
-                $price_row++;
1642
-                continue;
1643
-            }
1644
-            $show_trash                         = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1645
-            $show_create                        = ! (count($prices) > 1 && count($prices) !== $price_row);
1646
-            $template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1647
-                $ticket_row,
1648
-                $price_row,
1649
-                $price,
1650
-                $default,
1651
-                $ticket,
1652
-                $show_trash,
1653
-                $show_create
1654
-            );
1655
-            $price_row++;
1656
-        }
1657
-        //filter $template_args
1658
-        $template_args = apply_filters(
1659
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1660
-            $template_args,
1661
-            $ticket_row,
1662
-            $ticket,
1663
-            $ticket_datetimes,
1664
-            $all_datetimes,
1665
-            $default,
1666
-            $all_tickets,
1667
-            $this->_is_creating_event
1668
-        );
1669
-        return EEH_Template::display_template(
1670
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1671
-            $template_args,
1672
-            true
1673
-        );
1674
-    }
1403
+	/**
1404
+	 * This generates the ticket row for tickets.
1405
+	 * This same method is used to generate both the actual rows and the js skeleton row
1406
+	 * (when default === true)
1407
+	 *
1408
+	 * @param int           $ticket_row       Represents the row number being generated.
1409
+	 * @param               $ticket
1410
+	 * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1411
+	 *                                        or empty for default
1412
+	 * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1413
+	 * @param bool          $default          Whether default row being generated or not.
1414
+	 * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1415
+	 *                                        (or empty in the case of defaults)
1416
+	 * @return mixed
1417
+	 * @throws InvalidArgumentException
1418
+	 * @throws InvalidInterfaceException
1419
+	 * @throws InvalidDataTypeException
1420
+	 * @throws DomainException
1421
+	 * @throws EE_Error
1422
+	 * @throws ReflectionException
1423
+	 */
1424
+	protected function _get_ticket_row(
1425
+		$ticket_row,
1426
+		$ticket,
1427
+		$ticket_datetimes,
1428
+		$all_datetimes,
1429
+		$default = false,
1430
+		$all_tickets = array()
1431
+	) {
1432
+		// if $ticket is not an instance of EE_Ticket then force default to true.
1433
+		$default = ! $ticket instanceof EE_Ticket ? true : $default;
1434
+		$prices  = ! empty($ticket) && ! $default ? $ticket->get_many_related('Price',
1435
+			array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))) : array();
1436
+		// if there is only one price (which would be the base price)
1437
+		// or NO prices and this ticket is a default ticket,
1438
+		// let's just make sure there are no cached default prices on the object.
1439
+		// This is done by not including any query_params.
1440
+		if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1441
+			$prices = $ticket->prices();
1442
+		}
1443
+		// check if we're dealing with a default ticket in which case
1444
+		// we don't want any starting_ticket_datetime_row values set
1445
+		// (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1446
+		// This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1447
+		$default_dtt      = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1448
+		$tkt_datetimes    = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1449
+			? $ticket_datetimes[ $ticket->ID() ]
1450
+			: array();
1451
+		$ticket_subtotal  = $default ? 0 : $ticket->get_ticket_subtotal();
1452
+		$base_price       = $default ? null : $ticket->base_price();
1453
+		$count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1454
+		//breaking out complicated condition for ticket_status
1455
+		if ($default) {
1456
+			$ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1457
+		} else {
1458
+			$ticket_status_class = $ticket->is_default()
1459
+				? ' tkt-status-' . EE_Ticket::onsale
1460
+				: ' tkt-status-' . $ticket->ticket_status();
1461
+		}
1462
+		//breaking out complicated condition for TKT_taxable
1463
+		if ($default) {
1464
+			$TKT_taxable = '';
1465
+		} else {
1466
+			$TKT_taxable = $ticket->taxable()
1467
+				? ' checked="checked"'
1468
+				: '';
1469
+		}
1470
+		if ($default) {
1471
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1472
+		} elseif ($ticket->is_default()) {
1473
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1474
+		} else {
1475
+			$TKT_status = $ticket->ticket_status(true);
1476
+		}
1477
+		if ($default) {
1478
+			$TKT_min = '';
1479
+		} else {
1480
+			$TKT_min = $ticket->min();
1481
+			if ($TKT_min === -1 || $TKT_min === 0) {
1482
+				$TKT_min = '';
1483
+			}
1484
+		}
1485
+		$template_args                 = array(
1486
+			'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1487
+			'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1488
+			//on initial page load this will always be the correct order.
1489
+			'tkt_status_class'              => $ticket_status_class,
1490
+			'display_edit_tkt_row'          => ' style="display:none;"',
1491
+			'edit_tkt_expanded'             => '',
1492
+			'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1493
+			'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1494
+			'TKT_start_date'                => $default
1495
+				? ''
1496
+				: $ticket->get_date('TKT_start_date', $this->_date_time_format),
1497
+			'TKT_end_date'                  => $default
1498
+				? ''
1499
+				: $ticket->get_date('TKT_end_date', $this->_date_time_format),
1500
+			'TKT_status'                    => $TKT_status,
1501
+			'TKT_price'                     => $default
1502
+				? ''
1503
+				: EEH_Template::format_currency(
1504
+					$ticket->get_ticket_total_with_taxes(),
1505
+					false,
1506
+					false
1507
+				),
1508
+			'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1509
+			'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1510
+			'TKT_qty'                       => $default
1511
+				? ''
1512
+				: $ticket->get_pretty('TKT_qty', 'symbol'),
1513
+			'TKT_qty_for_input'             => $default
1514
+				? ''
1515
+				: $ticket->get_pretty('TKT_qty', 'input'),
1516
+			'TKT_uses'                      => $default
1517
+				? ''
1518
+				: $ticket->get_pretty('TKT_uses', 'input'),
1519
+			'TKT_min'                       => $TKT_min,
1520
+			'TKT_max'                       => $default
1521
+				? ''
1522
+				: $ticket->get_pretty('TKT_max', 'input'),
1523
+			'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1524
+			'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1525
+			'TKT_registrations'             => $default
1526
+				? 0
1527
+				: $ticket->count_registrations(
1528
+					array(
1529
+						array(
1530
+							'STS_ID' => array(
1531
+								'!=',
1532
+								EEM_Registration::status_id_incomplete,
1533
+							),
1534
+						),
1535
+					)
1536
+				),
1537
+			'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1538
+			'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1539
+			'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1540
+			'TKT_required'                  => $default ? 0 : $ticket->required(),
1541
+			'TKT_is_default_selector'       => '',
1542
+			'ticket_price_rows'             => '',
1543
+			'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1544
+				? ''
1545
+				: $base_price->get_pretty('PRC_amount', 'localized_float'),
1546
+			'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1547
+			'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1548
+				? ''
1549
+				: ' style="display:none;"',
1550
+			'show_price_mod_button'         => count($prices) > 1
1551
+											   || ($default && $count_price_mods > 0)
1552
+											   || (! $default && $ticket->deleted())
1553
+				? ' style="display:none;"'
1554
+				: '',
1555
+			'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1556
+			'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1557
+			'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1558
+			'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1559
+			'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1560
+			'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1561
+			'TKT_taxable'                   => $TKT_taxable,
1562
+			'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1563
+				? ''
1564
+				: ' style="display:none"',
1565
+			'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1566
+			'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1567
+				$ticket_subtotal,
1568
+				false,
1569
+				false
1570
+			),
1571
+			'TKT_subtotal_amount'           => $ticket_subtotal,
1572
+			'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1573
+			'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1574
+			'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1575
+				? ' ticket-archived'
1576
+				: '',
1577
+			'trash_icon'                    => $ticket instanceof EE_Ticket
1578
+											   && $ticket->deleted()
1579
+											   && ! $ticket->is_permanently_deleteable()
1580
+				? 'ee-lock-icon '
1581
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1582
+			'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1583
+				? ''
1584
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1585
+		);
1586
+		$template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1587
+			? ' style="display:none"'
1588
+			: '';
1589
+		//handle rows that should NOT be empty
1590
+		if (empty($template_args['TKT_start_date'])) {
1591
+			//if empty then the start date will be now.
1592
+			$template_args['TKT_start_date']   = date($this->_date_time_format,
1593
+				current_time('timestamp'));
1594
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1595
+		}
1596
+		if (empty($template_args['TKT_end_date'])) {
1597
+			//get the earliest datetime (if present);
1598
+			$earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1599
+				? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1600
+					'Datetime',
1601
+					array('order_by' => array('DTT_EVT_start' => 'ASC'))
1602
+				)
1603
+				: null;
1604
+			if (! empty($earliest_dtt)) {
1605
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1606
+					'DTT_EVT_start',
1607
+					$this->_date_time_format
1608
+				);
1609
+			} else {
1610
+				//default so let's just use what's been set for the default date-time which is 30 days from now.
1611
+				$template_args['TKT_end_date'] = date(
1612
+					$this->_date_time_format,
1613
+					mktime(
1614
+						24, 0, 0, date('m'), date('d') + 29, date('Y')
1615
+					)
1616
+				);
1617
+			}
1618
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1619
+		}
1620
+		//generate ticket_datetime items
1621
+		if (! $default) {
1622
+			$datetime_row = 1;
1623
+			foreach ($all_datetimes as $datetime) {
1624
+				$template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1625
+					$datetime_row,
1626
+					$ticket_row,
1627
+					$datetime,
1628
+					$ticket,
1629
+					$ticket_datetimes,
1630
+					$default
1631
+				);
1632
+				$datetime_row++;
1633
+			}
1634
+		}
1635
+		$price_row = 1;
1636
+		foreach ($prices as $price) {
1637
+			if (! $price instanceof EE_Price) {
1638
+				continue;
1639
+			}
1640
+			if ($price->is_base_price()) {
1641
+				$price_row++;
1642
+				continue;
1643
+			}
1644
+			$show_trash                         = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1645
+			$show_create                        = ! (count($prices) > 1 && count($prices) !== $price_row);
1646
+			$template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1647
+				$ticket_row,
1648
+				$price_row,
1649
+				$price,
1650
+				$default,
1651
+				$ticket,
1652
+				$show_trash,
1653
+				$show_create
1654
+			);
1655
+			$price_row++;
1656
+		}
1657
+		//filter $template_args
1658
+		$template_args = apply_filters(
1659
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1660
+			$template_args,
1661
+			$ticket_row,
1662
+			$ticket,
1663
+			$ticket_datetimes,
1664
+			$all_datetimes,
1665
+			$default,
1666
+			$all_tickets,
1667
+			$this->_is_creating_event
1668
+		);
1669
+		return EEH_Template::display_template(
1670
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1671
+			$template_args,
1672
+			true
1673
+		);
1674
+	}
1675 1675
 
1676 1676
 
1677
-    /**
1678
-     * @param int            $ticket_row
1679
-     * @param EE_Ticket|null $ticket
1680
-     * @return string
1681
-     * @throws DomainException
1682
-     * @throws EE_Error
1683
-     */
1684
-    protected function _get_tax_rows($ticket_row, $ticket)
1685
-    {
1686
-        $tax_rows = '';
1687
-        /** @var EE_Price[] $taxes */
1688
-        $taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1689
-        foreach ($taxes as $tax) {
1690
-            $tax_added     = $this->_get_tax_added($tax, $ticket);
1691
-            $template_args = array(
1692
-                'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1693
-                    ? ''
1694
-                    : ' style="display:none;"',
1695
-                'tax_id'            => $tax->ID(),
1696
-                'tkt_row'           => $ticket_row,
1697
-                'tax_label'         => $tax->get('PRC_name'),
1698
-                'tax_added'         => $tax_added,
1699
-                'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1700
-                'tax_amount'        => $tax->get('PRC_amount'),
1701
-            );
1702
-            $template_args = apply_filters(
1703
-                'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1704
-                $template_args,
1705
-                $ticket_row,
1706
-                $ticket,
1707
-                $this->_is_creating_event
1708
-            );
1709
-            $tax_rows      .= EEH_Template::display_template(
1710
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1711
-                $template_args,
1712
-                true
1713
-            );
1714
-        }
1715
-        return $tax_rows;
1716
-    }
1677
+	/**
1678
+	 * @param int            $ticket_row
1679
+	 * @param EE_Ticket|null $ticket
1680
+	 * @return string
1681
+	 * @throws DomainException
1682
+	 * @throws EE_Error
1683
+	 */
1684
+	protected function _get_tax_rows($ticket_row, $ticket)
1685
+	{
1686
+		$tax_rows = '';
1687
+		/** @var EE_Price[] $taxes */
1688
+		$taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1689
+		foreach ($taxes as $tax) {
1690
+			$tax_added     = $this->_get_tax_added($tax, $ticket);
1691
+			$template_args = array(
1692
+				'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1693
+					? ''
1694
+					: ' style="display:none;"',
1695
+				'tax_id'            => $tax->ID(),
1696
+				'tkt_row'           => $ticket_row,
1697
+				'tax_label'         => $tax->get('PRC_name'),
1698
+				'tax_added'         => $tax_added,
1699
+				'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1700
+				'tax_amount'        => $tax->get('PRC_amount'),
1701
+			);
1702
+			$template_args = apply_filters(
1703
+				'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1704
+				$template_args,
1705
+				$ticket_row,
1706
+				$ticket,
1707
+				$this->_is_creating_event
1708
+			);
1709
+			$tax_rows      .= EEH_Template::display_template(
1710
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1711
+				$template_args,
1712
+				true
1713
+			);
1714
+		}
1715
+		return $tax_rows;
1716
+	}
1717 1717
 
1718 1718
 
1719
-    /**
1720
-     * @param EE_Price       $tax
1721
-     * @param EE_Ticket|null $ticket
1722
-     * @return float|int
1723
-     * @throws EE_Error
1724
-     */
1725
-    protected function _get_tax_added(EE_Price $tax, $ticket)
1726
-    {
1727
-        $subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1728
-        return $subtotal * $tax->get('PRC_amount') / 100;
1729
-    }
1719
+	/**
1720
+	 * @param EE_Price       $tax
1721
+	 * @param EE_Ticket|null $ticket
1722
+	 * @return float|int
1723
+	 * @throws EE_Error
1724
+	 */
1725
+	protected function _get_tax_added(EE_Price $tax, $ticket)
1726
+	{
1727
+		$subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1728
+		return $subtotal * $tax->get('PRC_amount') / 100;
1729
+	}
1730 1730
 
1731 1731
 
1732
-    /**
1733
-     * @param int            $ticket_row
1734
-     * @param int            $price_row
1735
-     * @param EE_Price|null  $price
1736
-     * @param bool           $default
1737
-     * @param EE_Ticket|null $ticket
1738
-     * @param bool           $show_trash
1739
-     * @param bool           $show_create
1740
-     * @return mixed
1741
-     * @throws InvalidArgumentException
1742
-     * @throws InvalidInterfaceException
1743
-     * @throws InvalidDataTypeException
1744
-     * @throws DomainException
1745
-     * @throws EE_Error
1746
-     * @throws ReflectionException
1747
-     */
1748
-    protected function _get_ticket_price_row(
1749
-        $ticket_row,
1750
-        $price_row,
1751
-        $price,
1752
-        $default,
1753
-        $ticket,
1754
-        $show_trash = true,
1755
-        $show_create = true
1756
-    ) {
1757
-        $send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1758
-        $template_args = array(
1759
-            'tkt_row'               => $default && empty($ticket)
1760
-                ? 'TICKETNUM'
1761
-                : $ticket_row,
1762
-            'PRC_order'             => $default && empty($price)
1763
-                ? 'PRICENUM'
1764
-                : $price_row,
1765
-            'edit_prices_name'      => $default && empty($price)
1766
-                ? 'PRICENAMEATTR'
1767
-                : 'edit_prices',
1768
-            'price_type_selector'   => $default && empty($price)
1769
-                ? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1770
-                : $this->_get_price_type_selector(
1771
-                    $ticket_row,
1772
-                    $price_row,
1773
-                    $price,
1774
-                    $default,
1775
-                    $send_disabled
1776
-                ),
1777
-            'PRC_ID'                => $default && empty($price)
1778
-                ? 0
1779
-                : $price->ID(),
1780
-            'PRC_is_default'        => $default && empty($price)
1781
-                ? 0
1782
-                : $price->get('PRC_is_default'),
1783
-            'PRC_name'              => $default && empty($price)
1784
-                ? ''
1785
-                : $price->get('PRC_name'),
1786
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1787
-            'show_plus_or_minus'    => $default && empty($price)
1788
-                ? ''
1789
-                : ' style="display:none;"',
1790
-            'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1791
-                ? ' style="display:none;"'
1792
-                : '',
1793
-            'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1794
-                ? ' style="display:none;"'
1795
-                : '',
1796
-            'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1797
-                ? ' style="display:none"'
1798
-                : '',
1799
-            'PRC_amount'            => $default && empty($price)
1800
-                ? 0
1801
-                : $price->get_pretty('PRC_amount',
1802
-                    'localized_float'),
1803
-            'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1804
-                ? ' style="display:none;"'
1805
-                : '',
1806
-            'show_trash_icon'       => $show_trash
1807
-                ? ''
1808
-                : ' style="display:none;"',
1809
-            'show_create_button'    => $show_create
1810
-                ? ''
1811
-                : ' style="display:none;"',
1812
-            'PRC_desc'              => $default && empty($price)
1813
-                ? ''
1814
-                : $price->get('PRC_desc'),
1815
-            'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1816
-        );
1817
-        $template_args = apply_filters(
1818
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1819
-            $template_args,
1820
-            $ticket_row,
1821
-            $price_row,
1822
-            $price,
1823
-            $default,
1824
-            $ticket,
1825
-            $show_trash,
1826
-            $show_create,
1827
-            $this->_is_creating_event
1828
-        );
1829
-        return EEH_Template::display_template(
1830
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1831
-            $template_args,
1832
-            true
1833
-        );
1834
-    }
1732
+	/**
1733
+	 * @param int            $ticket_row
1734
+	 * @param int            $price_row
1735
+	 * @param EE_Price|null  $price
1736
+	 * @param bool           $default
1737
+	 * @param EE_Ticket|null $ticket
1738
+	 * @param bool           $show_trash
1739
+	 * @param bool           $show_create
1740
+	 * @return mixed
1741
+	 * @throws InvalidArgumentException
1742
+	 * @throws InvalidInterfaceException
1743
+	 * @throws InvalidDataTypeException
1744
+	 * @throws DomainException
1745
+	 * @throws EE_Error
1746
+	 * @throws ReflectionException
1747
+	 */
1748
+	protected function _get_ticket_price_row(
1749
+		$ticket_row,
1750
+		$price_row,
1751
+		$price,
1752
+		$default,
1753
+		$ticket,
1754
+		$show_trash = true,
1755
+		$show_create = true
1756
+	) {
1757
+		$send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1758
+		$template_args = array(
1759
+			'tkt_row'               => $default && empty($ticket)
1760
+				? 'TICKETNUM'
1761
+				: $ticket_row,
1762
+			'PRC_order'             => $default && empty($price)
1763
+				? 'PRICENUM'
1764
+				: $price_row,
1765
+			'edit_prices_name'      => $default && empty($price)
1766
+				? 'PRICENAMEATTR'
1767
+				: 'edit_prices',
1768
+			'price_type_selector'   => $default && empty($price)
1769
+				? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1770
+				: $this->_get_price_type_selector(
1771
+					$ticket_row,
1772
+					$price_row,
1773
+					$price,
1774
+					$default,
1775
+					$send_disabled
1776
+				),
1777
+			'PRC_ID'                => $default && empty($price)
1778
+				? 0
1779
+				: $price->ID(),
1780
+			'PRC_is_default'        => $default && empty($price)
1781
+				? 0
1782
+				: $price->get('PRC_is_default'),
1783
+			'PRC_name'              => $default && empty($price)
1784
+				? ''
1785
+				: $price->get('PRC_name'),
1786
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1787
+			'show_plus_or_minus'    => $default && empty($price)
1788
+				? ''
1789
+				: ' style="display:none;"',
1790
+			'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1791
+				? ' style="display:none;"'
1792
+				: '',
1793
+			'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1794
+				? ' style="display:none;"'
1795
+				: '',
1796
+			'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1797
+				? ' style="display:none"'
1798
+				: '',
1799
+			'PRC_amount'            => $default && empty($price)
1800
+				? 0
1801
+				: $price->get_pretty('PRC_amount',
1802
+					'localized_float'),
1803
+			'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1804
+				? ' style="display:none;"'
1805
+				: '',
1806
+			'show_trash_icon'       => $show_trash
1807
+				? ''
1808
+				: ' style="display:none;"',
1809
+			'show_create_button'    => $show_create
1810
+				? ''
1811
+				: ' style="display:none;"',
1812
+			'PRC_desc'              => $default && empty($price)
1813
+				? ''
1814
+				: $price->get('PRC_desc'),
1815
+			'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1816
+		);
1817
+		$template_args = apply_filters(
1818
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1819
+			$template_args,
1820
+			$ticket_row,
1821
+			$price_row,
1822
+			$price,
1823
+			$default,
1824
+			$ticket,
1825
+			$show_trash,
1826
+			$show_create,
1827
+			$this->_is_creating_event
1828
+		);
1829
+		return EEH_Template::display_template(
1830
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1831
+			$template_args,
1832
+			true
1833
+		);
1834
+	}
1835 1835
 
1836 1836
 
1837
-    /**
1838
-     * @param int      $ticket_row
1839
-     * @param int      $price_row
1840
-     * @param EE_Price $price
1841
-     * @param bool     $default
1842
-     * @param bool     $disabled
1843
-     * @return mixed
1844
-     * @throws ReflectionException
1845
-     * @throws InvalidArgumentException
1846
-     * @throws InvalidInterfaceException
1847
-     * @throws InvalidDataTypeException
1848
-     * @throws DomainException
1849
-     * @throws EE_Error
1850
-     */
1851
-    protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1852
-    {
1853
-        if ($price->is_base_price()) {
1854
-            return $this->_get_base_price_template(
1855
-                $ticket_row,
1856
-                $price_row,
1857
-                $price,
1858
-                $default
1859
-            );
1860
-        }
1861
-        return $this->_get_price_modifier_template(
1862
-            $ticket_row,
1863
-            $price_row,
1864
-            $price,
1865
-            $default,
1866
-            $disabled
1867
-        );
1868
-    }
1837
+	/**
1838
+	 * @param int      $ticket_row
1839
+	 * @param int      $price_row
1840
+	 * @param EE_Price $price
1841
+	 * @param bool     $default
1842
+	 * @param bool     $disabled
1843
+	 * @return mixed
1844
+	 * @throws ReflectionException
1845
+	 * @throws InvalidArgumentException
1846
+	 * @throws InvalidInterfaceException
1847
+	 * @throws InvalidDataTypeException
1848
+	 * @throws DomainException
1849
+	 * @throws EE_Error
1850
+	 */
1851
+	protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1852
+	{
1853
+		if ($price->is_base_price()) {
1854
+			return $this->_get_base_price_template(
1855
+				$ticket_row,
1856
+				$price_row,
1857
+				$price,
1858
+				$default
1859
+			);
1860
+		}
1861
+		return $this->_get_price_modifier_template(
1862
+			$ticket_row,
1863
+			$price_row,
1864
+			$price,
1865
+			$default,
1866
+			$disabled
1867
+		);
1868
+	}
1869 1869
 
1870 1870
 
1871
-    /**
1872
-     * @param int      $ticket_row
1873
-     * @param int      $price_row
1874
-     * @param EE_Price $price
1875
-     * @param bool     $default
1876
-     * @return mixed
1877
-     * @throws DomainException
1878
-     * @throws EE_Error
1879
-     */
1880
-    protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1881
-    {
1882
-        $template_args = array(
1883
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1884
-            'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1885
-            'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1886
-            'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1887
-            'price_selected_operator'   => '+',
1888
-            'price_selected_is_percent' => 0,
1889
-        );
1890
-        $template_args = apply_filters(
1891
-            'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1892
-            $template_args,
1893
-            $ticket_row,
1894
-            $price_row,
1895
-            $price,
1896
-            $default,
1897
-            $this->_is_creating_event
1898
-        );
1899
-        return EEH_Template::display_template(
1900
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1901
-            $template_args,
1902
-            true
1903
-        );
1904
-    }
1871
+	/**
1872
+	 * @param int      $ticket_row
1873
+	 * @param int      $price_row
1874
+	 * @param EE_Price $price
1875
+	 * @param bool     $default
1876
+	 * @return mixed
1877
+	 * @throws DomainException
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1881
+	{
1882
+		$template_args = array(
1883
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1884
+			'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1885
+			'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1886
+			'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1887
+			'price_selected_operator'   => '+',
1888
+			'price_selected_is_percent' => 0,
1889
+		);
1890
+		$template_args = apply_filters(
1891
+			'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1892
+			$template_args,
1893
+			$ticket_row,
1894
+			$price_row,
1895
+			$price,
1896
+			$default,
1897
+			$this->_is_creating_event
1898
+		);
1899
+		return EEH_Template::display_template(
1900
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1901
+			$template_args,
1902
+			true
1903
+		);
1904
+	}
1905 1905
 
1906 1906
 
1907
-    /**
1908
-     * @param int      $ticket_row
1909
-     * @param int      $price_row
1910
-     * @param EE_Price $price
1911
-     * @param bool     $default
1912
-     * @param bool     $disabled
1913
-     * @return mixed
1914
-     * @throws ReflectionException
1915
-     * @throws InvalidArgumentException
1916
-     * @throws InvalidInterfaceException
1917
-     * @throws InvalidDataTypeException
1918
-     * @throws DomainException
1919
-     * @throws EE_Error
1920
-     */
1921
-    protected function _get_price_modifier_template(
1922
-        $ticket_row,
1923
-        $price_row,
1924
-        $price,
1925
-        $default,
1926
-        $disabled = false
1927
-    ) {
1928
-        $select_name = $default && ! $price instanceof EE_Price
1929
-            ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1930
-            : 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1931
-        /** @var EEM_Price_Type $price_type_model */
1932
-        $price_type_model       = EE_Registry::instance()->load_model('Price_Type');
1933
-        $price_types            = $price_type_model->get_all(array(
1934
-            array(
1935
-                'OR' => array(
1936
-                    'PBT_ID'  => '2',
1937
-                    'PBT_ID*' => '3',
1938
-                ),
1939
-            ),
1940
-        ));
1941
-        $all_price_types        = $default && ! $price instanceof EE_Price
1942
-            ? array(esc_html__('Select Modifier', 'event_espresso'))
1943
-            : array();
1944
-        $selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1945
-        $price_option_spans     = '';
1946
-        //setup price types for selector
1947
-        foreach ($price_types as $price_type) {
1948
-            if (! $price_type instanceof EE_Price_Type) {
1949
-                continue;
1950
-            }
1951
-            $all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1952
-            //while we're in the loop let's setup the option spans used by js
1953
-            $span_args          = array(
1954
-                'PRT_ID'         => $price_type->ID(),
1955
-                'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1956
-                'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1957
-            );
1958
-            $price_option_spans .= EEH_Template::display_template(
1959
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1960
-                $span_args,
1961
-                true
1962
-            );
1963
-        }
1964
-        $select_name               = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1965
-            : $select_name;
1966
-        $select_input              = new EE_Select_Input(
1967
-            $all_price_types,
1968
-            array(
1969
-                'default'               => $selected_price_type_id,
1970
-                'html_name'             => $select_name,
1971
-                'html_class'            => 'edit-price-PRT_ID',
1972
-                'html_other_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1973
-            )
1974
-        );
1975
-        $price_selected_operator   = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1976
-        $price_selected_operator   = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
1977
-        $price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
1978
-        $price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
1979
-        $template_args             = array(
1980
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1981
-            'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
1982
-            'price_modifier_selector'   => $select_input->get_html_for_input(),
1983
-            'main_name'                 => $select_name,
1984
-            'selected_price_type_id'    => $selected_price_type_id,
1985
-            'price_option_spans'        => $price_option_spans,
1986
-            'price_selected_operator'   => $price_selected_operator,
1987
-            'price_selected_is_percent' => $price_selected_is_percent,
1988
-            'disabled'                  => $disabled,
1989
-        );
1990
-        $template_args             = apply_filters(
1991
-            'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1992
-            $template_args,
1993
-            $ticket_row,
1994
-            $price_row,
1995
-            $price,
1996
-            $default,
1997
-            $disabled,
1998
-            $this->_is_creating_event
1999
-        );
2000
-        return EEH_Template::display_template(
2001
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2002
-            $template_args,
2003
-            true
2004
-        );
2005
-    }
1907
+	/**
1908
+	 * @param int      $ticket_row
1909
+	 * @param int      $price_row
1910
+	 * @param EE_Price $price
1911
+	 * @param bool     $default
1912
+	 * @param bool     $disabled
1913
+	 * @return mixed
1914
+	 * @throws ReflectionException
1915
+	 * @throws InvalidArgumentException
1916
+	 * @throws InvalidInterfaceException
1917
+	 * @throws InvalidDataTypeException
1918
+	 * @throws DomainException
1919
+	 * @throws EE_Error
1920
+	 */
1921
+	protected function _get_price_modifier_template(
1922
+		$ticket_row,
1923
+		$price_row,
1924
+		$price,
1925
+		$default,
1926
+		$disabled = false
1927
+	) {
1928
+		$select_name = $default && ! $price instanceof EE_Price
1929
+			? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1930
+			: 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1931
+		/** @var EEM_Price_Type $price_type_model */
1932
+		$price_type_model       = EE_Registry::instance()->load_model('Price_Type');
1933
+		$price_types            = $price_type_model->get_all(array(
1934
+			array(
1935
+				'OR' => array(
1936
+					'PBT_ID'  => '2',
1937
+					'PBT_ID*' => '3',
1938
+				),
1939
+			),
1940
+		));
1941
+		$all_price_types        = $default && ! $price instanceof EE_Price
1942
+			? array(esc_html__('Select Modifier', 'event_espresso'))
1943
+			: array();
1944
+		$selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1945
+		$price_option_spans     = '';
1946
+		//setup price types for selector
1947
+		foreach ($price_types as $price_type) {
1948
+			if (! $price_type instanceof EE_Price_Type) {
1949
+				continue;
1950
+			}
1951
+			$all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1952
+			//while we're in the loop let's setup the option spans used by js
1953
+			$span_args          = array(
1954
+				'PRT_ID'         => $price_type->ID(),
1955
+				'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1956
+				'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1957
+			);
1958
+			$price_option_spans .= EEH_Template::display_template(
1959
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1960
+				$span_args,
1961
+				true
1962
+			);
1963
+		}
1964
+		$select_name               = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1965
+			: $select_name;
1966
+		$select_input              = new EE_Select_Input(
1967
+			$all_price_types,
1968
+			array(
1969
+				'default'               => $selected_price_type_id,
1970
+				'html_name'             => $select_name,
1971
+				'html_class'            => 'edit-price-PRT_ID',
1972
+				'html_other_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1973
+			)
1974
+		);
1975
+		$price_selected_operator   = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1976
+		$price_selected_operator   = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
1977
+		$price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
1978
+		$price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
1979
+		$template_args             = array(
1980
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1981
+			'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
1982
+			'price_modifier_selector'   => $select_input->get_html_for_input(),
1983
+			'main_name'                 => $select_name,
1984
+			'selected_price_type_id'    => $selected_price_type_id,
1985
+			'price_option_spans'        => $price_option_spans,
1986
+			'price_selected_operator'   => $price_selected_operator,
1987
+			'price_selected_is_percent' => $price_selected_is_percent,
1988
+			'disabled'                  => $disabled,
1989
+		);
1990
+		$template_args             = apply_filters(
1991
+			'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1992
+			$template_args,
1993
+			$ticket_row,
1994
+			$price_row,
1995
+			$price,
1996
+			$default,
1997
+			$disabled,
1998
+			$this->_is_creating_event
1999
+		);
2000
+		return EEH_Template::display_template(
2001
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2002
+			$template_args,
2003
+			true
2004
+		);
2005
+	}
2006 2006
 
2007 2007
 
2008
-    /**
2009
-     * @param int              $datetime_row
2010
-     * @param int              $ticket_row
2011
-     * @param EE_Datetime|null $datetime
2012
-     * @param EE_Ticket|null   $ticket
2013
-     * @param array            $ticket_datetimes
2014
-     * @param bool             $default
2015
-     * @return mixed
2016
-     * @throws DomainException
2017
-     * @throws EE_Error
2018
-     */
2019
-    protected function _get_ticket_datetime_list_item(
2020
-        $datetime_row,
2021
-        $ticket_row,
2022
-        $datetime,
2023
-        $ticket,
2024
-        $ticket_datetimes = array(),
2025
-        $default
2026
-    ) {
2027
-        $tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2028
-            ? $ticket_datetimes[ $ticket->ID() ]
2029
-            : array();
2030
-        $template_args = array(
2031
-            'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2032
-                ? 'DTTNUM'
2033
-                : $datetime_row,
2034
-            'tkt_row'                  => $default
2035
-                ? 'TICKETNUM'
2036
-                : $ticket_row,
2037
-            'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2038
-                ? ' ticket-selected'
2039
-                : '',
2040
-            'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2041
-                ? ' checked="checked"'
2042
-                : '',
2043
-            'DTT_name'                 => $default && empty($datetime)
2044
-                ? 'DTTNAME'
2045
-                : $datetime->get_dtt_display_name(true),
2046
-            'tkt_status_class'         => '',
2047
-        );
2048
-        $template_args = apply_filters(
2049
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2050
-            $template_args,
2051
-            $datetime_row,
2052
-            $ticket_row,
2053
-            $datetime,
2054
-            $ticket,
2055
-            $ticket_datetimes,
2056
-            $default,
2057
-            $this->_is_creating_event
2058
-        );
2059
-        return EEH_Template::display_template(
2060
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2061
-            $template_args,
2062
-            true
2063
-        );
2064
-    }
2008
+	/**
2009
+	 * @param int              $datetime_row
2010
+	 * @param int              $ticket_row
2011
+	 * @param EE_Datetime|null $datetime
2012
+	 * @param EE_Ticket|null   $ticket
2013
+	 * @param array            $ticket_datetimes
2014
+	 * @param bool             $default
2015
+	 * @return mixed
2016
+	 * @throws DomainException
2017
+	 * @throws EE_Error
2018
+	 */
2019
+	protected function _get_ticket_datetime_list_item(
2020
+		$datetime_row,
2021
+		$ticket_row,
2022
+		$datetime,
2023
+		$ticket,
2024
+		$ticket_datetimes = array(),
2025
+		$default
2026
+	) {
2027
+		$tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2028
+			? $ticket_datetimes[ $ticket->ID() ]
2029
+			: array();
2030
+		$template_args = array(
2031
+			'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2032
+				? 'DTTNUM'
2033
+				: $datetime_row,
2034
+			'tkt_row'                  => $default
2035
+				? 'TICKETNUM'
2036
+				: $ticket_row,
2037
+			'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2038
+				? ' ticket-selected'
2039
+				: '',
2040
+			'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2041
+				? ' checked="checked"'
2042
+				: '',
2043
+			'DTT_name'                 => $default && empty($datetime)
2044
+				? 'DTTNAME'
2045
+				: $datetime->get_dtt_display_name(true),
2046
+			'tkt_status_class'         => '',
2047
+		);
2048
+		$template_args = apply_filters(
2049
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2050
+			$template_args,
2051
+			$datetime_row,
2052
+			$ticket_row,
2053
+			$datetime,
2054
+			$ticket,
2055
+			$ticket_datetimes,
2056
+			$default,
2057
+			$this->_is_creating_event
2058
+		);
2059
+		return EEH_Template::display_template(
2060
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2061
+			$template_args,
2062
+			true
2063
+		);
2064
+	}
2065 2065
 
2066 2066
 
2067
-    /**
2068
-     * @param array $all_datetimes
2069
-     * @param array $all_tickets
2070
-     * @return mixed
2071
-     * @throws ReflectionException
2072
-     * @throws InvalidArgumentException
2073
-     * @throws InvalidInterfaceException
2074
-     * @throws InvalidDataTypeException
2075
-     * @throws DomainException
2076
-     * @throws EE_Error
2077
-     */
2078
-    protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2079
-    {
2080
-        $template_args = array(
2081
-            'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2082
-                'DTTNUM',
2083
-                null,
2084
-                true,
2085
-                $all_datetimes
2086
-            ),
2087
-            'default_ticket_row'                       => $this->_get_ticket_row(
2088
-                'TICKETNUM',
2089
-                null,
2090
-                array(),
2091
-                array(),
2092
-                true
2093
-            ),
2094
-            'default_price_row'                        => $this->_get_ticket_price_row(
2095
-                'TICKETNUM',
2096
-                'PRICENUM',
2097
-                null,
2098
-                true,
2099
-                null
2100
-            ),
2101
-            'default_price_rows'                       => '',
2102
-            'default_base_price_amount'                => 0,
2103
-            'default_base_price_name'                  => '',
2104
-            'default_base_price_description'           => '',
2105
-            'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2106
-                'TICKETNUM',
2107
-                'PRICENUM',
2108
-                null,
2109
-                true
2110
-            ),
2111
-            'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2112
-                'DTTNUM',
2113
-                null,
2114
-                array(),
2115
-                array(),
2116
-                true
2117
-            ),
2118
-            'existing_available_datetime_tickets_list' => '',
2119
-            'existing_available_ticket_datetimes_list' => '',
2120
-            'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2121
-                'DTTNUM',
2122
-                'TICKETNUM',
2123
-                null,
2124
-                null,
2125
-                array(),
2126
-                true
2127
-            ),
2128
-            'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2129
-                'DTTNUM',
2130
-                'TICKETNUM',
2131
-                null,
2132
-                null,
2133
-                array(),
2134
-                true
2135
-            ),
2136
-        );
2137
-        $ticket_row    = 1;
2138
-        foreach ($all_tickets as $ticket) {
2139
-            $template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2140
-                'DTTNUM',
2141
-                $ticket_row,
2142
-                null,
2143
-                $ticket,
2144
-                array(),
2145
-                true
2146
-            );
2147
-            $ticket_row++;
2148
-        }
2149
-        $datetime_row = 1;
2150
-        foreach ($all_datetimes as $datetime) {
2151
-            $template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2152
-                $datetime_row,
2153
-                'TICKETNUM',
2154
-                $datetime,
2155
-                null,
2156
-                array(),
2157
-                true
2158
-            );
2159
-            $datetime_row++;
2160
-        }
2161
-        /** @var EEM_Price $price_model */
2162
-        $price_model    = EE_Registry::instance()->load_model('Price');
2163
-        $default_prices = $price_model->get_all_default_prices();
2164
-        $price_row      = 1;
2165
-        foreach ($default_prices as $price) {
2166
-            if (! $price instanceof EE_Price) {
2167
-                continue;
2168
-            }
2169
-            if ($price->is_base_price()) {
2170
-                $template_args['default_base_price_amount']      = $price->get_pretty(
2171
-                    'PRC_amount',
2172
-                    'localized_float'
2173
-                );
2174
-                $template_args['default_base_price_name']        = $price->get('PRC_name');
2175
-                $template_args['default_base_price_description'] = $price->get('PRC_desc');
2176
-                $price_row++;
2177
-                continue;
2178
-            }
2179
-            $show_trash                          = ! ((count($default_prices) > 1 && $price_row === 1)
2180
-                                                      || count($default_prices) === 1);
2181
-            $show_create                         = ! (count($default_prices) > 1
2182
-                                                      && count($default_prices)
2183
-                                                         !== $price_row);
2184
-            $template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2185
-                'TICKETNUM',
2186
-                $price_row,
2187
-                $price,
2188
-                true,
2189
-                null,
2190
-                $show_trash,
2191
-                $show_create
2192
-            );
2193
-            $price_row++;
2194
-        }
2195
-        $template_args = apply_filters(
2196
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2197
-            $template_args,
2198
-            $all_datetimes,
2199
-            $all_tickets,
2200
-            $this->_is_creating_event
2201
-        );
2202
-        return EEH_Template::display_template(
2203
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2204
-            $template_args,
2205
-            true
2206
-        );
2207
-    }
2067
+	/**
2068
+	 * @param array $all_datetimes
2069
+	 * @param array $all_tickets
2070
+	 * @return mixed
2071
+	 * @throws ReflectionException
2072
+	 * @throws InvalidArgumentException
2073
+	 * @throws InvalidInterfaceException
2074
+	 * @throws InvalidDataTypeException
2075
+	 * @throws DomainException
2076
+	 * @throws EE_Error
2077
+	 */
2078
+	protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2079
+	{
2080
+		$template_args = array(
2081
+			'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2082
+				'DTTNUM',
2083
+				null,
2084
+				true,
2085
+				$all_datetimes
2086
+			),
2087
+			'default_ticket_row'                       => $this->_get_ticket_row(
2088
+				'TICKETNUM',
2089
+				null,
2090
+				array(),
2091
+				array(),
2092
+				true
2093
+			),
2094
+			'default_price_row'                        => $this->_get_ticket_price_row(
2095
+				'TICKETNUM',
2096
+				'PRICENUM',
2097
+				null,
2098
+				true,
2099
+				null
2100
+			),
2101
+			'default_price_rows'                       => '',
2102
+			'default_base_price_amount'                => 0,
2103
+			'default_base_price_name'                  => '',
2104
+			'default_base_price_description'           => '',
2105
+			'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2106
+				'TICKETNUM',
2107
+				'PRICENUM',
2108
+				null,
2109
+				true
2110
+			),
2111
+			'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2112
+				'DTTNUM',
2113
+				null,
2114
+				array(),
2115
+				array(),
2116
+				true
2117
+			),
2118
+			'existing_available_datetime_tickets_list' => '',
2119
+			'existing_available_ticket_datetimes_list' => '',
2120
+			'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2121
+				'DTTNUM',
2122
+				'TICKETNUM',
2123
+				null,
2124
+				null,
2125
+				array(),
2126
+				true
2127
+			),
2128
+			'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2129
+				'DTTNUM',
2130
+				'TICKETNUM',
2131
+				null,
2132
+				null,
2133
+				array(),
2134
+				true
2135
+			),
2136
+		);
2137
+		$ticket_row    = 1;
2138
+		foreach ($all_tickets as $ticket) {
2139
+			$template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2140
+				'DTTNUM',
2141
+				$ticket_row,
2142
+				null,
2143
+				$ticket,
2144
+				array(),
2145
+				true
2146
+			);
2147
+			$ticket_row++;
2148
+		}
2149
+		$datetime_row = 1;
2150
+		foreach ($all_datetimes as $datetime) {
2151
+			$template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2152
+				$datetime_row,
2153
+				'TICKETNUM',
2154
+				$datetime,
2155
+				null,
2156
+				array(),
2157
+				true
2158
+			);
2159
+			$datetime_row++;
2160
+		}
2161
+		/** @var EEM_Price $price_model */
2162
+		$price_model    = EE_Registry::instance()->load_model('Price');
2163
+		$default_prices = $price_model->get_all_default_prices();
2164
+		$price_row      = 1;
2165
+		foreach ($default_prices as $price) {
2166
+			if (! $price instanceof EE_Price) {
2167
+				continue;
2168
+			}
2169
+			if ($price->is_base_price()) {
2170
+				$template_args['default_base_price_amount']      = $price->get_pretty(
2171
+					'PRC_amount',
2172
+					'localized_float'
2173
+				);
2174
+				$template_args['default_base_price_name']        = $price->get('PRC_name');
2175
+				$template_args['default_base_price_description'] = $price->get('PRC_desc');
2176
+				$price_row++;
2177
+				continue;
2178
+			}
2179
+			$show_trash                          = ! ((count($default_prices) > 1 && $price_row === 1)
2180
+													  || count($default_prices) === 1);
2181
+			$show_create                         = ! (count($default_prices) > 1
2182
+													  && count($default_prices)
2183
+														 !== $price_row);
2184
+			$template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2185
+				'TICKETNUM',
2186
+				$price_row,
2187
+				$price,
2188
+				true,
2189
+				null,
2190
+				$show_trash,
2191
+				$show_create
2192
+			);
2193
+			$price_row++;
2194
+		}
2195
+		$template_args = apply_filters(
2196
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2197
+			$template_args,
2198
+			$all_datetimes,
2199
+			$all_tickets,
2200
+			$this->_is_creating_event
2201
+		);
2202
+		return EEH_Template::display_template(
2203
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2204
+			$template_args,
2205
+			true
2206
+		);
2207
+	}
2208 2208
 } //end class espresso_events_Pricing_Hooks
Please login to merge, or discard this patch.
core/domain/services/admin/ExitModal.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -18,68 +18,68 @@
 block discarded – undo
18 18
 class ExitModal
19 19
 {
20 20
 
21
-    /**
22
-     * @var Registry
23
-     */
24
-    private $assets_registry;
21
+	/**
22
+	 * @var Registry
23
+	 */
24
+	private $assets_registry;
25 25
 
26
-    /**
27
-     * ExitModal constructor.
28
-     *
29
-     * @param Registry $assets_registry
30
-     */
31
-    public function __construct(Registry $assets_registry)
32
-    {
33
-        $this->assets_registry = $assets_registry;
34
-        add_action('in_admin_footer', array($this, 'modalContainer'));
35
-        add_action('admin_enqueue_scripts', array($this, 'enqueues'));
36
-    }
26
+	/**
27
+	 * ExitModal constructor.
28
+	 *
29
+	 * @param Registry $assets_registry
30
+	 */
31
+	public function __construct(Registry $assets_registry)
32
+	{
33
+		$this->assets_registry = $assets_registry;
34
+		add_action('in_admin_footer', array($this, 'modalContainer'));
35
+		add_action('admin_enqueue_scripts', array($this, 'enqueues'));
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Callback on in_admin_footer that is used to output the exit modal container.
41
-     */
42
-    public function modalContainer()
43
-    {
44
-        echo '<div id="ee-exit-survey-modal"></div>';
45
-    }
39
+	/**
40
+	 * Callback on in_admin_footer that is used to output the exit modal container.
41
+	 */
42
+	public function modalContainer()
43
+	{
44
+		echo '<div id="ee-exit-survey-modal"></div>';
45
+	}
46 46
 
47 47
 
48
-    /**
49
-     * Callback for `admin_enqueue_scripts` to take care of enqueueing scripts and styles specific to the modal.
50
-     *
51
-     * @throws InvalidArgumentException
52
-     */
53
-    public function enqueues()
54
-    {
55
-        $current_user = new WP_User(get_current_user_id());
56
-        $this->assets_registry->addData(
57
-            'exitModalInfo',
58
-            array(
59
-                'firstname' => htmlspecialchars($current_user->user_firstname),
60
-                'emailaddress' => htmlspecialchars($current_user->user_email),
61
-                'website' => htmlspecialchars(site_url()),
62
-                'isModalActive' => $this->isModalActive()
63
-            )
64
-        );
48
+	/**
49
+	 * Callback for `admin_enqueue_scripts` to take care of enqueueing scripts and styles specific to the modal.
50
+	 *
51
+	 * @throws InvalidArgumentException
52
+	 */
53
+	public function enqueues()
54
+	{
55
+		$current_user = new WP_User(get_current_user_id());
56
+		$this->assets_registry->addData(
57
+			'exitModalInfo',
58
+			array(
59
+				'firstname' => htmlspecialchars($current_user->user_firstname),
60
+				'emailaddress' => htmlspecialchars($current_user->user_email),
61
+				'website' => htmlspecialchars(site_url()),
62
+				'isModalActive' => $this->isModalActive()
63
+			)
64
+		);
65 65
 
66
-        wp_enqueue_script('ee-wp-plugins-page');
67
-        wp_enqueue_style('ee-wp-plugins-page');
68
-    }
66
+		wp_enqueue_script('ee-wp-plugins-page');
67
+		wp_enqueue_style('ee-wp-plugins-page');
68
+	}
69 69
 
70 70
 
71
-    /**
72
-     * Exposes a filter switch for turning off the enqueueing of the modal script.
73
-     * @return bool
74
-     */
75
-    private function isModalActive()
76
-    {
77
-        return filter_var(
78
-            apply_filters(
79
-                'FHEE__EventEspresso_core_domain_services_admin_ExitModal__isModalActive',
80
-                true
81
-            ),
82
-            FILTER_VALIDATE_BOOLEAN
83
-        );
84
-    }
71
+	/**
72
+	 * Exposes a filter switch for turning off the enqueueing of the modal script.
73
+	 * @return bool
74
+	 */
75
+	private function isModalActive()
76
+	{
77
+		return filter_var(
78
+			apply_filters(
79
+				'FHEE__EventEspresso_core_domain_services_admin_ExitModal__isModalActive',
80
+				true
81
+			),
82
+			FILTER_VALIDATE_BOOLEAN
83
+		);
84
+	}
85 85
 }
86 86
\ No newline at end of file
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +890 added lines, -890 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
 use EventEspresso\core\services\request\ResponseInterface;
9 9
 
10 10
 if (! defined('EVENT_ESPRESSO_VERSION')) {
11
-    exit('No direct script access allowed');
11
+	exit('No direct script access allowed');
12 12
 }
13 13
 
14 14
 
@@ -25,896 +25,896 @@  discard block
 block discarded – undo
25 25
 class EE_Dependency_Map
26 26
 {
27 27
 
28
-    /**
29
-     * This means that the requested class dependency is not present in the dependency map
30
-     */
31
-    const not_registered = 0;
32
-
33
-    /**
34
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
35
-     */
36
-    const load_new_object = 1;
37
-
38
-    /**
39
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
40
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
41
-     */
42
-    const load_from_cache = 2;
43
-
44
-    /**
45
-     * When registering a dependency,
46
-     * this indicates to keep any existing dependencies that already exist,
47
-     * and simply discard any new dependencies declared in the incoming data
48
-     */
49
-    const KEEP_EXISTING_DEPENDENCIES = 0;
50
-
51
-    /**
52
-     * When registering a dependency,
53
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
54
-     */
55
-    const OVERWRITE_DEPENDENCIES = 1;
56
-
57
-
58
-
59
-    /**
60
-     * @type EE_Dependency_Map $_instance
61
-     */
62
-    protected static $_instance;
63
-
64
-    /**
65
-     * @type RequestInterface $request
66
-     */
67
-    protected $request;
68
-
69
-    /**
70
-     * @type LegacyRequestInterface $legacy_request
71
-     */
72
-    protected $legacy_request;
73
-
74
-    /**
75
-     * @type ResponseInterface $response
76
-     */
77
-    protected $response;
78
-
79
-    /**
80
-     * @type LoaderInterface $loader
81
-     */
82
-    protected $loader;
83
-
84
-    /**
85
-     * @type array $_dependency_map
86
-     */
87
-    protected $_dependency_map = array();
88
-
89
-    /**
90
-     * @type array $_class_loaders
91
-     */
92
-    protected $_class_loaders = array();
93
-
94
-    /**
95
-     * @type array $_aliases
96
-     */
97
-    protected $_aliases = array();
98
-
99
-
100
-
101
-    /**
102
-     * EE_Dependency_Map constructor.
103
-     */
104
-    protected function __construct()
105
-    {
106
-        // add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
107
-        do_action('EE_Dependency_Map____construct');
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidArgumentException
116
-     */
117
-    public function initialize()
118
-    {
119
-        $this->_register_core_dependencies();
120
-        $this->_register_core_class_loaders();
121
-        $this->_register_core_aliases();
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * @singleton method used to instantiate class object
128
-     * @return EE_Dependency_Map
129
-     */
130
-    public static function instance() {
131
-        // check if class object is instantiated, and instantiated properly
132
-        if (! self::$_instance instanceof EE_Dependency_Map) {
133
-            self::$_instance = new EE_Dependency_Map(/*$request, $response, $legacy_request*/);
134
-        }
135
-        return self::$_instance;
136
-    }
137
-
138
-
139
-    /**
140
-     * @param RequestInterface $request
141
-     */
142
-    public function setRequest(RequestInterface $request)
143
-    {
144
-        $this->request = $request;
145
-    }
146
-
147
-
148
-    /**
149
-     * @param LegacyRequestInterface $legacy_request
150
-     */
151
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
152
-    {
153
-        $this->legacy_request = $legacy_request;
154
-    }
155
-
156
-
157
-    /**
158
-     * @param ResponseInterface $response
159
-     */
160
-    public function setResponse(ResponseInterface $response)
161
-    {
162
-        $this->response = $response;
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @param LoaderInterface $loader
169
-     */
170
-    public function setLoader(LoaderInterface $loader)
171
-    {
172
-        $this->loader = $loader;
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * @param string $class
179
-     * @param array  $dependencies
180
-     * @param int    $overwrite
181
-     * @return bool
182
-     */
183
-    public static function register_dependencies(
184
-        $class,
185
-        array $dependencies,
186
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
187
-    ) {
188
-        return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
189
-    }
190
-
191
-
192
-
193
-    /**
194
-     * Assigns an array of class names and corresponding load sources (new or cached)
195
-     * to the class specified by the first parameter.
196
-     * IMPORTANT !!!
197
-     * The order of elements in the incoming $dependencies array MUST match
198
-     * the order of the constructor parameters for the class in question.
199
-     * This is especially important when overriding any existing dependencies that are registered.
200
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
201
-     *
202
-     * @param string $class
203
-     * @param array  $dependencies
204
-     * @param int    $overwrite
205
-     * @return bool
206
-     */
207
-    public function registerDependencies(
208
-        $class,
209
-        array $dependencies,
210
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
211
-    ) {
212
-        $class = trim($class, '\\');
213
-        $registered = false;
214
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
215
-            self::$_instance->_dependency_map[ $class ] = array();
216
-        }
217
-        // we need to make sure that any aliases used when registering a dependency
218
-        // get resolved to the correct class name
219
-        foreach ($dependencies as $dependency => $load_source) {
220
-            $alias = self::$_instance->get_alias($dependency);
221
-            if (
222
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
223
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
224
-            ) {
225
-                unset($dependencies[$dependency]);
226
-                $dependencies[$alias] = $load_source;
227
-                $registered = true;
228
-            }
229
-        }
230
-        // now add our two lists of dependencies together.
231
-        // using Union (+=) favours the arrays in precedence from left to right,
232
-        // so $dependencies is NOT overwritten because it is listed first
233
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
234
-        // Union is way faster than array_merge() but should be used with caution...
235
-        // especially with numerically indexed arrays
236
-        $dependencies += self::$_instance->_dependency_map[ $class ];
237
-        // now we need to ensure that the resulting dependencies
238
-        // array only has the entries that are required for the class
239
-        // so first count how many dependencies were originally registered for the class
240
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
241
-        // if that count is non-zero (meaning dependencies were already registered)
242
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
243
-            // then truncate the  final array to match that count
244
-            ? array_slice($dependencies, 0, $dependency_count)
245
-            // otherwise just take the incoming array because nothing previously existed
246
-            : $dependencies;
247
-        return $registered;
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * @param string $class_name
254
-     * @param string $loader
255
-     * @return bool
256
-     * @throws DomainException
257
-     */
258
-    public static function register_class_loader($class_name, $loader = 'load_core')
259
-    {
260
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
261
-            throw new DomainException(
262
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
263
-            );
264
-        }
265
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
266
-        if (
267
-            ! is_callable($loader)
268
-            && (
269
-                strpos($loader, 'load_') !== 0
270
-                || ! method_exists('EE_Registry', $loader)
271
-            )
272
-        ) {
273
-            throw new DomainException(
274
-                sprintf(
275
-                    esc_html__(
276
-                        '"%1$s" is not a valid loader method on EE_Registry.',
277
-                        'event_espresso'
278
-                    ),
279
-                    $loader
280
-                )
281
-            );
282
-        }
283
-        $class_name = self::$_instance->get_alias($class_name);
284
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
285
-            self::$_instance->_class_loaders[$class_name] = $loader;
286
-            return true;
287
-        }
288
-        return false;
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * @return array
295
-     */
296
-    public function dependency_map()
297
-    {
298
-        return $this->_dependency_map;
299
-    }
300
-
301
-
302
-
303
-    /**
304
-     * returns TRUE if dependency map contains a listing for the provided class name
305
-     *
306
-     * @param string $class_name
307
-     * @return boolean
308
-     */
309
-    public function has($class_name = '')
310
-    {
311
-        // all legacy models have the same dependencies
312
-        if (strpos($class_name, 'EEM_') === 0) {
313
-            $class_name = 'LEGACY_MODELS';
314
-        }
315
-        return isset($this->_dependency_map[$class_name]) ? true : false;
316
-    }
317
-
318
-
319
-
320
-    /**
321
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
322
-     *
323
-     * @param string $class_name
324
-     * @param string $dependency
325
-     * @return bool
326
-     */
327
-    public function has_dependency_for_class($class_name = '', $dependency = '')
328
-    {
329
-        // all legacy models have the same dependencies
330
-        if (strpos($class_name, 'EEM_') === 0) {
331
-            $class_name = 'LEGACY_MODELS';
332
-        }
333
-        $dependency = $this->get_alias($dependency);
334
-        return isset($this->_dependency_map[$class_name][$dependency])
335
-            ? true
336
-            : false;
337
-    }
338
-
339
-
340
-
341
-    /**
342
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
343
-     *
344
-     * @param string $class_name
345
-     * @param string $dependency
346
-     * @return int
347
-     */
348
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
349
-    {
350
-        // all legacy models have the same dependencies
351
-        if (strpos($class_name, 'EEM_') === 0) {
352
-            $class_name = 'LEGACY_MODELS';
353
-        }
354
-        $dependency = $this->get_alias($dependency);
355
-        return $this->has_dependency_for_class($class_name, $dependency)
356
-            ? $this->_dependency_map[$class_name][$dependency]
357
-            : EE_Dependency_Map::not_registered;
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * @param string $class_name
364
-     * @return string | Closure
365
-     */
366
-    public function class_loader($class_name)
367
-    {
368
-        // all legacy models use load_model()
369
-        if(strpos($class_name, 'EEM_') === 0){
370
-            return 'load_model';
371
-        }
372
-        $class_name = $this->get_alias($class_name);
373
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
374
-    }
375
-
376
-
377
-
378
-    /**
379
-     * @return array
380
-     */
381
-    public function class_loaders()
382
-    {
383
-        return $this->_class_loaders;
384
-    }
385
-
386
-
387
-
388
-    /**
389
-     * adds an alias for a classname
390
-     *
391
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
392
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
393
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
394
-     */
395
-    public function add_alias($class_name, $alias, $for_class = '')
396
-    {
397
-        if ($for_class !== '') {
398
-            if (! isset($this->_aliases[$for_class])) {
399
-                $this->_aliases[$for_class] = array();
400
-            }
401
-            $this->_aliases[$for_class][$class_name] = $alias;
402
-        }
403
-        $this->_aliases[$class_name] = $alias;
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * returns TRUE if the provided class name has an alias
410
-     *
411
-     * @param string $class_name
412
-     * @param string $for_class
413
-     * @return bool
414
-     */
415
-    public function has_alias($class_name = '', $for_class = '')
416
-    {
417
-        return isset($this->_aliases[$for_class][$class_name])
418
-               || (
419
-                   isset($this->_aliases[$class_name])
420
-                   && ! is_array($this->_aliases[$class_name])
421
-               );
422
-    }
423
-
424
-
425
-
426
-    /**
427
-     * returns alias for class name if one exists, otherwise returns the original classname
428
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
429
-     *  for example:
430
-     *      if the following two entries were added to the _aliases array:
431
-     *          array(
432
-     *              'interface_alias'           => 'some\namespace\interface'
433
-     *              'some\namespace\interface'  => 'some\namespace\classname'
434
-     *          )
435
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
436
-     *      to load an instance of 'some\namespace\classname'
437
-     *
438
-     * @param string $class_name
439
-     * @param string $for_class
440
-     * @return string
441
-     */
442
-    public function get_alias($class_name = '', $for_class = '')
443
-    {
444
-        if (! $this->has_alias($class_name, $for_class)) {
445
-            return $class_name;
446
-        }
447
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
448
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
449
-        }
450
-        return $this->get_alias($this->_aliases[$class_name]);
451
-    }
452
-
453
-
454
-
455
-    /**
456
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
457
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
458
-     * This is done by using the following class constants:
459
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
460
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
461
-     */
462
-    protected function _register_core_dependencies()
463
-    {
464
-        $this->_dependency_map = array(
465
-            'EE_Request_Handler'                                                                                          => array(
466
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
467
-            ),
468
-            'EE_System'                                                                                                   => array(
469
-                'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
470
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
471
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
472
-                'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
473
-            ),
474
-            'EE_Session'                                                                                                  => array(
475
-                'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
476
-                'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
477
-                'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
478
-                'EE_Encryption'                                            => EE_Dependency_Map::load_from_cache,
479
-            ),
480
-            'EE_Cart'                                                                                                     => array(
481
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
482
-            ),
483
-            'EE_Front_Controller'                                                                                         => array(
484
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
485
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
486
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
487
-            ),
488
-            'EE_Messenger_Collection_Loader'                                                                              => array(
489
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
490
-            ),
491
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
492
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
493
-            ),
494
-            'EE_Message_Resource_Manager'                                                                                 => array(
495
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
496
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
497
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
498
-            ),
499
-            'EE_Message_Factory'                                                                                          => array(
500
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
501
-            ),
502
-            'EE_messages'                                                                                                 => array(
503
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
-            ),
505
-            'EE_Messages_Generator'                                                                                       => array(
506
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
507
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
508
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
509
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
510
-            ),
511
-            'EE_Messages_Processor'                                                                                       => array(
512
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
513
-            ),
514
-            'EE_Messages_Queue'                                                                                           => array(
515
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
516
-            ),
517
-            'EE_Messages_Template_Defaults'                                                                               => array(
518
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
519
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
520
-            ),
521
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
522
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
523
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
524
-            ),
525
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
526
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
527
-            ),
528
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
529
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
530
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
531
-            ),
532
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
533
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
534
-            ),
535
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
536
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
537
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
538
-            ),
539
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
540
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
541
-            ),
542
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
543
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
544
-            ),
545
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
546
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
547
-            ),
548
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
549
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
550
-            ),
551
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
552
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
553
-            ),
554
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
555
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
556
-            ),
557
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
558
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
559
-            ),
560
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
561
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
-            ),
563
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
564
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
565
-            ),
566
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
567
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
-            ),
569
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
570
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
571
-            ),
572
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
573
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
574
-            ),
575
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
576
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
577
-            ),
578
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
579
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
-            ),
581
-            'EE_Data_Migration_Class_Base'                                                                                => array(
582
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
583
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
584
-            ),
585
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
586
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
587
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
588
-            ),
589
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
590
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
591
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
592
-            ),
593
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
594
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
595
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
596
-            ),
597
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
598
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
599
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
600
-            ),
601
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
602
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
603
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
604
-            ),
605
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
606
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
607
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
608
-            ),
609
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
610
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
611
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
612
-            ),
613
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
614
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
615
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
616
-            ),
617
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
618
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
619
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
620
-            ),
621
-            'EventEspresso\core\services\assets\I18nRegistry' => array(
622
-                array(),
623
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
624
-            ),
625
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
626
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
627
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
628
-                'EventEspresso\core\services\assets\I18nRegistry' => EE_Dependency_Map::load_from_cache,
629
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
630
-            ),
631
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
632
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
633
-            ),
634
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
635
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
636
-            ),
637
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
638
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
639
-            ),
640
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
641
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
642
-            ),
643
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
644
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
-            ),
646
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
647
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
-            ),
649
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
650
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
-            ),
652
-            'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
653
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
654
-            ),
655
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
656
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
657
-            ),
658
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
659
-                'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
660
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
661
-            ),
662
-            'EventEspresso\core\domain\values\EmailAddress'                              => array(
663
-                null,
664
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
665
-            ),
666
-            'EventEspresso\core\services\orm\ModelFieldFactory' => array(
667
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
668
-            ),
669
-            'LEGACY_MODELS'                                                   => array(
670
-                null,
671
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
672
-            ),
673
-            'EE_Module_Request_Router' => array(
674
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
675
-            ),
676
-            'EE_Registration_Processor' => array(
677
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
678
-            ),
679
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager' => array(
680
-                null,
681
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
682
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
683
-            ),
684
-            'EventEspresso\core\services\licensing\LicenseService' => array(
685
-                'EventEspresso\core\domain\services\pue\Stats' => EE_Dependency_Map::load_from_cache,
686
-                'EventEspresso\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache
687
-            ),
28
+	/**
29
+	 * This means that the requested class dependency is not present in the dependency map
30
+	 */
31
+	const not_registered = 0;
32
+
33
+	/**
34
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
35
+	 */
36
+	const load_new_object = 1;
37
+
38
+	/**
39
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
40
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
41
+	 */
42
+	const load_from_cache = 2;
43
+
44
+	/**
45
+	 * When registering a dependency,
46
+	 * this indicates to keep any existing dependencies that already exist,
47
+	 * and simply discard any new dependencies declared in the incoming data
48
+	 */
49
+	const KEEP_EXISTING_DEPENDENCIES = 0;
50
+
51
+	/**
52
+	 * When registering a dependency,
53
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
54
+	 */
55
+	const OVERWRITE_DEPENDENCIES = 1;
56
+
57
+
58
+
59
+	/**
60
+	 * @type EE_Dependency_Map $_instance
61
+	 */
62
+	protected static $_instance;
63
+
64
+	/**
65
+	 * @type RequestInterface $request
66
+	 */
67
+	protected $request;
68
+
69
+	/**
70
+	 * @type LegacyRequestInterface $legacy_request
71
+	 */
72
+	protected $legacy_request;
73
+
74
+	/**
75
+	 * @type ResponseInterface $response
76
+	 */
77
+	protected $response;
78
+
79
+	/**
80
+	 * @type LoaderInterface $loader
81
+	 */
82
+	protected $loader;
83
+
84
+	/**
85
+	 * @type array $_dependency_map
86
+	 */
87
+	protected $_dependency_map = array();
88
+
89
+	/**
90
+	 * @type array $_class_loaders
91
+	 */
92
+	protected $_class_loaders = array();
93
+
94
+	/**
95
+	 * @type array $_aliases
96
+	 */
97
+	protected $_aliases = array();
98
+
99
+
100
+
101
+	/**
102
+	 * EE_Dependency_Map constructor.
103
+	 */
104
+	protected function __construct()
105
+	{
106
+		// add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
107
+		do_action('EE_Dependency_Map____construct');
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidArgumentException
116
+	 */
117
+	public function initialize()
118
+	{
119
+		$this->_register_core_dependencies();
120
+		$this->_register_core_class_loaders();
121
+		$this->_register_core_aliases();
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * @singleton method used to instantiate class object
128
+	 * @return EE_Dependency_Map
129
+	 */
130
+	public static function instance() {
131
+		// check if class object is instantiated, and instantiated properly
132
+		if (! self::$_instance instanceof EE_Dependency_Map) {
133
+			self::$_instance = new EE_Dependency_Map(/*$request, $response, $legacy_request*/);
134
+		}
135
+		return self::$_instance;
136
+	}
137
+
138
+
139
+	/**
140
+	 * @param RequestInterface $request
141
+	 */
142
+	public function setRequest(RequestInterface $request)
143
+	{
144
+		$this->request = $request;
145
+	}
146
+
147
+
148
+	/**
149
+	 * @param LegacyRequestInterface $legacy_request
150
+	 */
151
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
152
+	{
153
+		$this->legacy_request = $legacy_request;
154
+	}
155
+
156
+
157
+	/**
158
+	 * @param ResponseInterface $response
159
+	 */
160
+	public function setResponse(ResponseInterface $response)
161
+	{
162
+		$this->response = $response;
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @param LoaderInterface $loader
169
+	 */
170
+	public function setLoader(LoaderInterface $loader)
171
+	{
172
+		$this->loader = $loader;
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * @param string $class
179
+	 * @param array  $dependencies
180
+	 * @param int    $overwrite
181
+	 * @return bool
182
+	 */
183
+	public static function register_dependencies(
184
+		$class,
185
+		array $dependencies,
186
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
187
+	) {
188
+		return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
189
+	}
190
+
191
+
192
+
193
+	/**
194
+	 * Assigns an array of class names and corresponding load sources (new or cached)
195
+	 * to the class specified by the first parameter.
196
+	 * IMPORTANT !!!
197
+	 * The order of elements in the incoming $dependencies array MUST match
198
+	 * the order of the constructor parameters for the class in question.
199
+	 * This is especially important when overriding any existing dependencies that are registered.
200
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
201
+	 *
202
+	 * @param string $class
203
+	 * @param array  $dependencies
204
+	 * @param int    $overwrite
205
+	 * @return bool
206
+	 */
207
+	public function registerDependencies(
208
+		$class,
209
+		array $dependencies,
210
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
211
+	) {
212
+		$class = trim($class, '\\');
213
+		$registered = false;
214
+		if (empty(self::$_instance->_dependency_map[ $class ])) {
215
+			self::$_instance->_dependency_map[ $class ] = array();
216
+		}
217
+		// we need to make sure that any aliases used when registering a dependency
218
+		// get resolved to the correct class name
219
+		foreach ($dependencies as $dependency => $load_source) {
220
+			$alias = self::$_instance->get_alias($dependency);
221
+			if (
222
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
223
+				|| ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
224
+			) {
225
+				unset($dependencies[$dependency]);
226
+				$dependencies[$alias] = $load_source;
227
+				$registered = true;
228
+			}
229
+		}
230
+		// now add our two lists of dependencies together.
231
+		// using Union (+=) favours the arrays in precedence from left to right,
232
+		// so $dependencies is NOT overwritten because it is listed first
233
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
234
+		// Union is way faster than array_merge() but should be used with caution...
235
+		// especially with numerically indexed arrays
236
+		$dependencies += self::$_instance->_dependency_map[ $class ];
237
+		// now we need to ensure that the resulting dependencies
238
+		// array only has the entries that are required for the class
239
+		// so first count how many dependencies were originally registered for the class
240
+		$dependency_count = count(self::$_instance->_dependency_map[ $class ]);
241
+		// if that count is non-zero (meaning dependencies were already registered)
242
+		self::$_instance->_dependency_map[ $class ] = $dependency_count
243
+			// then truncate the  final array to match that count
244
+			? array_slice($dependencies, 0, $dependency_count)
245
+			// otherwise just take the incoming array because nothing previously existed
246
+			: $dependencies;
247
+		return $registered;
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * @param string $class_name
254
+	 * @param string $loader
255
+	 * @return bool
256
+	 * @throws DomainException
257
+	 */
258
+	public static function register_class_loader($class_name, $loader = 'load_core')
259
+	{
260
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
261
+			throw new DomainException(
262
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
263
+			);
264
+		}
265
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
266
+		if (
267
+			! is_callable($loader)
268
+			&& (
269
+				strpos($loader, 'load_') !== 0
270
+				|| ! method_exists('EE_Registry', $loader)
271
+			)
272
+		) {
273
+			throw new DomainException(
274
+				sprintf(
275
+					esc_html__(
276
+						'"%1$s" is not a valid loader method on EE_Registry.',
277
+						'event_espresso'
278
+					),
279
+					$loader
280
+				)
281
+			);
282
+		}
283
+		$class_name = self::$_instance->get_alias($class_name);
284
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
285
+			self::$_instance->_class_loaders[$class_name] = $loader;
286
+			return true;
287
+		}
288
+		return false;
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * @return array
295
+	 */
296
+	public function dependency_map()
297
+	{
298
+		return $this->_dependency_map;
299
+	}
300
+
301
+
302
+
303
+	/**
304
+	 * returns TRUE if dependency map contains a listing for the provided class name
305
+	 *
306
+	 * @param string $class_name
307
+	 * @return boolean
308
+	 */
309
+	public function has($class_name = '')
310
+	{
311
+		// all legacy models have the same dependencies
312
+		if (strpos($class_name, 'EEM_') === 0) {
313
+			$class_name = 'LEGACY_MODELS';
314
+		}
315
+		return isset($this->_dependency_map[$class_name]) ? true : false;
316
+	}
317
+
318
+
319
+
320
+	/**
321
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
322
+	 *
323
+	 * @param string $class_name
324
+	 * @param string $dependency
325
+	 * @return bool
326
+	 */
327
+	public function has_dependency_for_class($class_name = '', $dependency = '')
328
+	{
329
+		// all legacy models have the same dependencies
330
+		if (strpos($class_name, 'EEM_') === 0) {
331
+			$class_name = 'LEGACY_MODELS';
332
+		}
333
+		$dependency = $this->get_alias($dependency);
334
+		return isset($this->_dependency_map[$class_name][$dependency])
335
+			? true
336
+			: false;
337
+	}
338
+
339
+
340
+
341
+	/**
342
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
343
+	 *
344
+	 * @param string $class_name
345
+	 * @param string $dependency
346
+	 * @return int
347
+	 */
348
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
349
+	{
350
+		// all legacy models have the same dependencies
351
+		if (strpos($class_name, 'EEM_') === 0) {
352
+			$class_name = 'LEGACY_MODELS';
353
+		}
354
+		$dependency = $this->get_alias($dependency);
355
+		return $this->has_dependency_for_class($class_name, $dependency)
356
+			? $this->_dependency_map[$class_name][$dependency]
357
+			: EE_Dependency_Map::not_registered;
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * @param string $class_name
364
+	 * @return string | Closure
365
+	 */
366
+	public function class_loader($class_name)
367
+	{
368
+		// all legacy models use load_model()
369
+		if(strpos($class_name, 'EEM_') === 0){
370
+			return 'load_model';
371
+		}
372
+		$class_name = $this->get_alias($class_name);
373
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
374
+	}
375
+
376
+
377
+
378
+	/**
379
+	 * @return array
380
+	 */
381
+	public function class_loaders()
382
+	{
383
+		return $this->_class_loaders;
384
+	}
385
+
386
+
387
+
388
+	/**
389
+	 * adds an alias for a classname
390
+	 *
391
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
392
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
393
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
394
+	 */
395
+	public function add_alias($class_name, $alias, $for_class = '')
396
+	{
397
+		if ($for_class !== '') {
398
+			if (! isset($this->_aliases[$for_class])) {
399
+				$this->_aliases[$for_class] = array();
400
+			}
401
+			$this->_aliases[$for_class][$class_name] = $alias;
402
+		}
403
+		$this->_aliases[$class_name] = $alias;
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * returns TRUE if the provided class name has an alias
410
+	 *
411
+	 * @param string $class_name
412
+	 * @param string $for_class
413
+	 * @return bool
414
+	 */
415
+	public function has_alias($class_name = '', $for_class = '')
416
+	{
417
+		return isset($this->_aliases[$for_class][$class_name])
418
+			   || (
419
+				   isset($this->_aliases[$class_name])
420
+				   && ! is_array($this->_aliases[$class_name])
421
+			   );
422
+	}
423
+
424
+
425
+
426
+	/**
427
+	 * returns alias for class name if one exists, otherwise returns the original classname
428
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
429
+	 *  for example:
430
+	 *      if the following two entries were added to the _aliases array:
431
+	 *          array(
432
+	 *              'interface_alias'           => 'some\namespace\interface'
433
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
434
+	 *          )
435
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
436
+	 *      to load an instance of 'some\namespace\classname'
437
+	 *
438
+	 * @param string $class_name
439
+	 * @param string $for_class
440
+	 * @return string
441
+	 */
442
+	public function get_alias($class_name = '', $for_class = '')
443
+	{
444
+		if (! $this->has_alias($class_name, $for_class)) {
445
+			return $class_name;
446
+		}
447
+		if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
448
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
449
+		}
450
+		return $this->get_alias($this->_aliases[$class_name]);
451
+	}
452
+
453
+
454
+
455
+	/**
456
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
457
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
458
+	 * This is done by using the following class constants:
459
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
460
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
461
+	 */
462
+	protected function _register_core_dependencies()
463
+	{
464
+		$this->_dependency_map = array(
465
+			'EE_Request_Handler'                                                                                          => array(
466
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
467
+			),
468
+			'EE_System'                                                                                                   => array(
469
+				'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
470
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
471
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
472
+				'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
473
+			),
474
+			'EE_Session'                                                                                                  => array(
475
+				'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
476
+				'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
477
+				'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
478
+				'EE_Encryption'                                            => EE_Dependency_Map::load_from_cache,
479
+			),
480
+			'EE_Cart'                                                                                                     => array(
481
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
482
+			),
483
+			'EE_Front_Controller'                                                                                         => array(
484
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
485
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
486
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
487
+			),
488
+			'EE_Messenger_Collection_Loader'                                                                              => array(
489
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
490
+			),
491
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
492
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
493
+			),
494
+			'EE_Message_Resource_Manager'                                                                                 => array(
495
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
496
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
497
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
498
+			),
499
+			'EE_Message_Factory'                                                                                          => array(
500
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
501
+			),
502
+			'EE_messages'                                                                                                 => array(
503
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
504
+			),
505
+			'EE_Messages_Generator'                                                                                       => array(
506
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
507
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
508
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
509
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
510
+			),
511
+			'EE_Messages_Processor'                                                                                       => array(
512
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
513
+			),
514
+			'EE_Messages_Queue'                                                                                           => array(
515
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
516
+			),
517
+			'EE_Messages_Template_Defaults'                                                                               => array(
518
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
519
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
520
+			),
521
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
522
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
523
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
524
+			),
525
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
526
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
527
+			),
528
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
529
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
530
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
531
+			),
532
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
533
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
534
+			),
535
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
536
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
537
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
538
+			),
539
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
540
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
541
+			),
542
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
543
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
544
+			),
545
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
546
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
547
+			),
548
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
549
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
550
+			),
551
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
552
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
553
+			),
554
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
555
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
556
+			),
557
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
558
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
559
+			),
560
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
561
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
+			),
563
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
564
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
565
+			),
566
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
567
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
+			),
569
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
570
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
571
+			),
572
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
573
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
574
+			),
575
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
576
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
577
+			),
578
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
579
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
+			),
581
+			'EE_Data_Migration_Class_Base'                                                                                => array(
582
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
583
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
584
+			),
585
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
586
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
587
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
588
+			),
589
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
590
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
591
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
592
+			),
593
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
594
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
595
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
596
+			),
597
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
598
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
599
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
600
+			),
601
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
602
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
603
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
604
+			),
605
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
606
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
607
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
608
+			),
609
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
610
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
611
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
612
+			),
613
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
614
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
615
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
616
+			),
617
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
618
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
619
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
620
+			),
621
+			'EventEspresso\core\services\assets\I18nRegistry' => array(
622
+				array(),
623
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
624
+			),
625
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
626
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
627
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
628
+				'EventEspresso\core\services\assets\I18nRegistry' => EE_Dependency_Map::load_from_cache,
629
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
630
+			),
631
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
632
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
633
+			),
634
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
635
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
636
+			),
637
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
638
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
639
+			),
640
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
641
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
642
+			),
643
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
644
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
+			),
646
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
647
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
+			),
649
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
650
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
+			),
652
+			'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
653
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
654
+			),
655
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
656
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
657
+			),
658
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
659
+				'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
660
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
661
+			),
662
+			'EventEspresso\core\domain\values\EmailAddress'                              => array(
663
+				null,
664
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
665
+			),
666
+			'EventEspresso\core\services\orm\ModelFieldFactory' => array(
667
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
668
+			),
669
+			'LEGACY_MODELS'                                                   => array(
670
+				null,
671
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
672
+			),
673
+			'EE_Module_Request_Router' => array(
674
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
675
+			),
676
+			'EE_Registration_Processor' => array(
677
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
678
+			),
679
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager' => array(
680
+				null,
681
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
682
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
683
+			),
684
+			'EventEspresso\core\services\licensing\LicenseService' => array(
685
+				'EventEspresso\core\domain\services\pue\Stats' => EE_Dependency_Map::load_from_cache,
686
+				'EventEspresso\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache
687
+			),
688 688
 			'EE_Admin_Transactions_List_Table' => array(
689
-                null,
690
-                'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
691
-			),
692
-            'EventEspresso\core\domain\services\pue\Stats' => array(
693
-                'EventEspresso\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache,
694
-                'EE_Maintenance_Mode' => EE_Dependency_Map::load_from_cache,
695
-                'EventEspresso\core\domain\services\pue\StatsGatherer' => EE_Dependency_Map::load_from_cache
696
-            ),
697
-            'EventEspresso\core\domain\services\pue\Config' => array(
698
-                'EE_Network_Config' => EE_Dependency_Map::load_from_cache,
699
-                'EE_Config' => EE_Dependency_Map::load_from_cache
700
-            ),
701
-            'EventEspresso\core\domain\services\pue\StatsGatherer' => array(
702
-                'EEM_Payment_Method' => EE_Dependency_Map::load_from_cache,
703
-                'EEM_Event' => EE_Dependency_Map::load_from_cache,
704
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
705
-                'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
706
-                'EEM_Registration' => EE_Dependency_Map::load_from_cache,
707
-                'EEM_Transaction' => EE_Dependency_Map::load_from_cache,
708
-                'EE_Config' => EE_Dependency_Map::load_from_cache
709
-            ),
710
-            'EventEspresso\core\domain\services\admin\ExitModal' => array(
711
-                'EventEspresso\core\services\assets\Registry' => EE_Dependency_Map::load_from_cache
712
-            ),
713
-            'EventEspresso\core\domain\services\admin\PluginUpsells' => array(
714
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
715
-            ),
716
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha' => array(
717
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
718
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
719
-            ),
720
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\RecaptchaAdminSettings' => array(
721
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
722
-            ),
723
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector' => array(
724
-                'EE_Core_Config' => EE_Dependency_Map::load_from_cache,
725
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
726
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
727
-                'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
728
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
729
-            ),
730
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => array(
731
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
732
-            ),
733
-        );
734
-    }
735
-
736
-
737
-
738
-    /**
739
-     * Registers how core classes are loaded.
740
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
741
-     *        'EE_Request_Handler' => 'load_core'
742
-     *        'EE_Messages_Queue'  => 'load_lib'
743
-     *        'EEH_Debug_Tools'    => 'load_helper'
744
-     * or, if greater control is required, by providing a custom closure. For example:
745
-     *        'Some_Class' => function () {
746
-     *            return new Some_Class();
747
-     *        },
748
-     * This is required for instantiating dependencies
749
-     * where an interface has been type hinted in a class constructor. For example:
750
-     *        'Required_Interface' => function () {
751
-     *            return new A_Class_That_Implements_Required_Interface();
752
-     *        },
753
-     *
754
-     * @throws InvalidInterfaceException
755
-     * @throws InvalidDataTypeException
756
-     * @throws InvalidArgumentException
757
-     */
758
-    protected function _register_core_class_loaders()
759
-    {
760
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
761
-        //be used in a closure.
762
-        $request = &$this->request;
763
-        $response = &$this->response;
764
-        $legacy_request = &$this->legacy_request;
765
-        // $loader = &$this->loader;
766
-        $this->_class_loaders = array(
767
-            //load_core
768
-            'EE_Capabilities'          => 'load_core',
769
-            'EE_Encryption'            => 'load_core',
770
-            'EE_Front_Controller'      => 'load_core',
771
-            'EE_Module_Request_Router' => 'load_core',
772
-            'EE_Registry'              => 'load_core',
773
-            'EE_Request'               => function () use (&$legacy_request) {
774
-                return $legacy_request;
775
-            },
776
-            'EventEspresso\core\services\request\Request' => function () use (&$request) {
777
-                return $request;
778
-            },
779
-            'EventEspresso\core\services\request\Response' => function () use (&$response) {
780
-                return $response;
781
-            },
782
-            'EE_Request_Handler'       => 'load_core',
783
-            'EE_Session'               => 'load_core',
784
-            'EE_Cron_Tasks'            => 'load_core',
785
-            'EE_System'                => 'load_core',
786
-            'EE_Maintenance_Mode'      => 'load_core',
787
-            'EE_Register_CPTs'         => 'load_core',
788
-            'EE_Admin'                 => 'load_core',
789
-            //load_lib
790
-            'EE_Message_Resource_Manager'          => 'load_lib',
791
-            'EE_Message_Type_Collection'           => 'load_lib',
792
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
793
-            'EE_Messenger_Collection'              => 'load_lib',
794
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
795
-            'EE_Messages_Processor'                => 'load_lib',
796
-            'EE_Message_Repository'                => 'load_lib',
797
-            'EE_Messages_Queue'                    => 'load_lib',
798
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
799
-            'EE_Message_Template_Group_Collection' => 'load_lib',
800
-            'EE_Payment_Method_Manager'            => 'load_lib',
801
-            'EE_Messages_Generator'                => function () {
802
-                return EE_Registry::instance()->load_lib(
803
-                    'Messages_Generator',
804
-                    array(),
805
-                    false,
806
-                    false
807
-                );
808
-            },
809
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
810
-                return EE_Registry::instance()->load_lib(
811
-                    'Messages_Template_Defaults',
812
-                    $arguments,
813
-                    false,
814
-                    false
815
-                );
816
-            },
817
-            //load_helper
818
-            'EEH_Parse_Shortcodes'                 => function () {
819
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
820
-                    return new EEH_Parse_Shortcodes();
821
-                }
822
-                return null;
823
-            },
824
-            'EE_Template_Config'                   => function () {
825
-                return EE_Config::instance()->template_settings;
826
-            },
827
-            'EE_Currency_Config'                   => function () {
828
-                return EE_Config::instance()->currency;
829
-            },
830
-            'EE_Registration_Config'                   => function () {
831
-                return EE_Config::instance()->registration;
832
-            },
833
-            'EE_Core_Config'                   => function () {
834
-                return EE_Config::instance()->core;
835
-            },
836
-            'EventEspresso\core\services\loaders\Loader' => function () {
837
-                return LoaderFactory::getLoader();
838
-            },
839
-            'EE_Network_Config' => function() {
840
-                return EE_Network_Config::instance();
841
-            },
842
-            'EE_Config' => function () {
843
-                return EE_Config::instance();
844
-            }
845
-        );
846
-    }
847
-
848
-
849
-
850
-    /**
851
-     * can be used for supplying alternate names for classes,
852
-     * or for connecting interface names to instantiable classes
853
-     */
854
-    protected function _register_core_aliases()
855
-    {
856
-        $this->_aliases = array(
857
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
858
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
859
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
860
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
861
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
862
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
863
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
864
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
865
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
866
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
867
-            'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
868
-            'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
869
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
870
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
871
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
872
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
873
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
874
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
875
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
876
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
877
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
878
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
879
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
880
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
881
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
882
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
883
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
884
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
885
-            'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
886
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
887
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
888
-            'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
889
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
890
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
891
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
892
-            'NoticesContainerInterface'                                           => 'EventEspresso\core\services\notices\NoticesContainerInterface',
893
-            'EventEspresso\core\services\notices\NoticesContainerInterface'       => 'EventEspresso\core\services\notices\NoticesContainer',
894
-            'EventEspresso\core\services\request\RequestInterface'                => 'EventEspresso\core\services\request\Request',
895
-            'EventEspresso\core\services\request\ResponseInterface'               => 'EventEspresso\core\services\request\Response',
896
-            'EventEspresso\core\domain\DomainInterface'                           => 'EventEspresso\core\domain\Domain',
897
-        );
898
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
899
-            $this->_aliases['EventEspresso\core\services\notices\NoticeConverterInterface'] = 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices';
900
-        }
901
-    }
902
-
903
-
904
-
905
-    /**
906
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
907
-     * request Primarily used by unit tests.
908
-     *
909
-     * @throws InvalidDataTypeException
910
-     * @throws InvalidInterfaceException
911
-     * @throws InvalidArgumentException
912
-     */
913
-    public function reset()
914
-    {
915
-        $this->_register_core_class_loaders();
916
-        $this->_register_core_dependencies();
917
-    }
689
+				null,
690
+				'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
691
+			),
692
+			'EventEspresso\core\domain\services\pue\Stats' => array(
693
+				'EventEspresso\core\domain\services\pue\Config' => EE_Dependency_Map::load_from_cache,
694
+				'EE_Maintenance_Mode' => EE_Dependency_Map::load_from_cache,
695
+				'EventEspresso\core\domain\services\pue\StatsGatherer' => EE_Dependency_Map::load_from_cache
696
+			),
697
+			'EventEspresso\core\domain\services\pue\Config' => array(
698
+				'EE_Network_Config' => EE_Dependency_Map::load_from_cache,
699
+				'EE_Config' => EE_Dependency_Map::load_from_cache
700
+			),
701
+			'EventEspresso\core\domain\services\pue\StatsGatherer' => array(
702
+				'EEM_Payment_Method' => EE_Dependency_Map::load_from_cache,
703
+				'EEM_Event' => EE_Dependency_Map::load_from_cache,
704
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
705
+				'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
706
+				'EEM_Registration' => EE_Dependency_Map::load_from_cache,
707
+				'EEM_Transaction' => EE_Dependency_Map::load_from_cache,
708
+				'EE_Config' => EE_Dependency_Map::load_from_cache
709
+			),
710
+			'EventEspresso\core\domain\services\admin\ExitModal' => array(
711
+				'EventEspresso\core\services\assets\Registry' => EE_Dependency_Map::load_from_cache
712
+			),
713
+			'EventEspresso\core\domain\services\admin\PluginUpsells' => array(
714
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache
715
+			),
716
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha' => array(
717
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
718
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
719
+			),
720
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\RecaptchaAdminSettings' => array(
721
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
722
+			),
723
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector' => array(
724
+				'EE_Core_Config' => EE_Dependency_Map::load_from_cache,
725
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
726
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
727
+				'EEM_Ticket' => EE_Dependency_Map::load_from_cache,
728
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
729
+			),
730
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => array(
731
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
732
+			),
733
+		);
734
+	}
735
+
736
+
737
+
738
+	/**
739
+	 * Registers how core classes are loaded.
740
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
741
+	 *        'EE_Request_Handler' => 'load_core'
742
+	 *        'EE_Messages_Queue'  => 'load_lib'
743
+	 *        'EEH_Debug_Tools'    => 'load_helper'
744
+	 * or, if greater control is required, by providing a custom closure. For example:
745
+	 *        'Some_Class' => function () {
746
+	 *            return new Some_Class();
747
+	 *        },
748
+	 * This is required for instantiating dependencies
749
+	 * where an interface has been type hinted in a class constructor. For example:
750
+	 *        'Required_Interface' => function () {
751
+	 *            return new A_Class_That_Implements_Required_Interface();
752
+	 *        },
753
+	 *
754
+	 * @throws InvalidInterfaceException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws InvalidArgumentException
757
+	 */
758
+	protected function _register_core_class_loaders()
759
+	{
760
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
761
+		//be used in a closure.
762
+		$request = &$this->request;
763
+		$response = &$this->response;
764
+		$legacy_request = &$this->legacy_request;
765
+		// $loader = &$this->loader;
766
+		$this->_class_loaders = array(
767
+			//load_core
768
+			'EE_Capabilities'          => 'load_core',
769
+			'EE_Encryption'            => 'load_core',
770
+			'EE_Front_Controller'      => 'load_core',
771
+			'EE_Module_Request_Router' => 'load_core',
772
+			'EE_Registry'              => 'load_core',
773
+			'EE_Request'               => function () use (&$legacy_request) {
774
+				return $legacy_request;
775
+			},
776
+			'EventEspresso\core\services\request\Request' => function () use (&$request) {
777
+				return $request;
778
+			},
779
+			'EventEspresso\core\services\request\Response' => function () use (&$response) {
780
+				return $response;
781
+			},
782
+			'EE_Request_Handler'       => 'load_core',
783
+			'EE_Session'               => 'load_core',
784
+			'EE_Cron_Tasks'            => 'load_core',
785
+			'EE_System'                => 'load_core',
786
+			'EE_Maintenance_Mode'      => 'load_core',
787
+			'EE_Register_CPTs'         => 'load_core',
788
+			'EE_Admin'                 => 'load_core',
789
+			//load_lib
790
+			'EE_Message_Resource_Manager'          => 'load_lib',
791
+			'EE_Message_Type_Collection'           => 'load_lib',
792
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
793
+			'EE_Messenger_Collection'              => 'load_lib',
794
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
795
+			'EE_Messages_Processor'                => 'load_lib',
796
+			'EE_Message_Repository'                => 'load_lib',
797
+			'EE_Messages_Queue'                    => 'load_lib',
798
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
799
+			'EE_Message_Template_Group_Collection' => 'load_lib',
800
+			'EE_Payment_Method_Manager'            => 'load_lib',
801
+			'EE_Messages_Generator'                => function () {
802
+				return EE_Registry::instance()->load_lib(
803
+					'Messages_Generator',
804
+					array(),
805
+					false,
806
+					false
807
+				);
808
+			},
809
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
810
+				return EE_Registry::instance()->load_lib(
811
+					'Messages_Template_Defaults',
812
+					$arguments,
813
+					false,
814
+					false
815
+				);
816
+			},
817
+			//load_helper
818
+			'EEH_Parse_Shortcodes'                 => function () {
819
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
820
+					return new EEH_Parse_Shortcodes();
821
+				}
822
+				return null;
823
+			},
824
+			'EE_Template_Config'                   => function () {
825
+				return EE_Config::instance()->template_settings;
826
+			},
827
+			'EE_Currency_Config'                   => function () {
828
+				return EE_Config::instance()->currency;
829
+			},
830
+			'EE_Registration_Config'                   => function () {
831
+				return EE_Config::instance()->registration;
832
+			},
833
+			'EE_Core_Config'                   => function () {
834
+				return EE_Config::instance()->core;
835
+			},
836
+			'EventEspresso\core\services\loaders\Loader' => function () {
837
+				return LoaderFactory::getLoader();
838
+			},
839
+			'EE_Network_Config' => function() {
840
+				return EE_Network_Config::instance();
841
+			},
842
+			'EE_Config' => function () {
843
+				return EE_Config::instance();
844
+			}
845
+		);
846
+	}
847
+
848
+
849
+
850
+	/**
851
+	 * can be used for supplying alternate names for classes,
852
+	 * or for connecting interface names to instantiable classes
853
+	 */
854
+	protected function _register_core_aliases()
855
+	{
856
+		$this->_aliases = array(
857
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
858
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
859
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
860
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
861
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
862
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
863
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
864
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
865
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
866
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
867
+			'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
868
+			'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
869
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
870
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
871
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
872
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
873
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
874
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
875
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
876
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
877
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
878
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
879
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
880
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
881
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
882
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
883
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
884
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
885
+			'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
886
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
887
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
888
+			'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
889
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
890
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
891
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
892
+			'NoticesContainerInterface'                                           => 'EventEspresso\core\services\notices\NoticesContainerInterface',
893
+			'EventEspresso\core\services\notices\NoticesContainerInterface'       => 'EventEspresso\core\services\notices\NoticesContainer',
894
+			'EventEspresso\core\services\request\RequestInterface'                => 'EventEspresso\core\services\request\Request',
895
+			'EventEspresso\core\services\request\ResponseInterface'               => 'EventEspresso\core\services\request\Response',
896
+			'EventEspresso\core\domain\DomainInterface'                           => 'EventEspresso\core\domain\Domain',
897
+		);
898
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
899
+			$this->_aliases['EventEspresso\core\services\notices\NoticeConverterInterface'] = 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices';
900
+		}
901
+	}
902
+
903
+
904
+
905
+	/**
906
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
907
+	 * request Primarily used by unit tests.
908
+	 *
909
+	 * @throws InvalidDataTypeException
910
+	 * @throws InvalidInterfaceException
911
+	 * @throws InvalidArgumentException
912
+	 */
913
+	public function reset()
914
+	{
915
+		$this->_register_core_class_loaders();
916
+		$this->_register_core_dependencies();
917
+	}
918 918
 
919 919
 
920 920
 }
Please login to merge, or discard this patch.
core/services/assets/I18nRegistry.php 2 patches
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -14,228 +14,228 @@
 block discarded – undo
14 14
  */
15 15
 class I18nRegistry
16 16
 {
17
-    /**
18
-     * @var DomainInterface
19
-     */
20
-    private $domain;
21
-
22
-    /**
23
-     * Will hold all registered i18n scripts.
24
-     *
25
-     * @var array
26
-     */
27
-    private $registered_i18n = array();
28
-
29
-
30
-    /**
31
-     * Used to hold queued translations for the chunks loading in a view.
32
-     *
33
-     * @var array
34
-     */
35
-    private $queued_handle_translations = array();
36
-
37
-
38
-    /**
39
-     * Obtained from the generated json file from the all javascript using wp.i18n with a map of script handle names to
40
-     * translation strings.
41
-     *
42
-     * @var array
43
-     */
44
-    private $i18n_map;
45
-
46
-
47
-    /**
48
-     * I18nRegistry constructor.
49
-     *
50
-     * @param array() $i18n_map  An array of script handle names and the strings translated for those handles.  If not
51
-     *                            provided, the class will look for map in root of plugin with filename of
52
-     *                            'translation-map.json'.
53
-     * @param DomainInterface $domain
54
-     */
55
-    public function __construct(array $i18n_map = array(), DomainInterface $domain)
56
-    {
57
-        $this->domain = $domain;
58
-        $this->setI18nMap($i18n_map);
59
-        add_filter('print_scripts_array', array($this, 'queueI18n'));
60
-    }
61
-
62
-
63
-    /**
64
-     * Used to register a script that has i18n strings for its $handle
65
-     *
66
-     * @param string $handle The script handle reference.
67
-     * @param string $domain The i18n domain for the strings.
68
-     */
69
-    public function registerScriptI18n($handle, $domain = 'event_espresso')
70
-    {
71
-        $this->registered_i18n[$handle] = $domain;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * Callback on print_scripts_array to listen for scripts enqueued and handle setting up the localized data.
78
-     *
79
-     * @param array $handles Array of registered script handles.
80
-     * @return array
81
-     */
82
-    public function queueI18n(array $handles)
83
-    {
84
-        if (empty($this->registered_i18n) || empty($this->i18n_map)) {
85
-            return $handles;
86
-        }
87
-        foreach ($handles as $handle) {
88
-            $this->queueI18nTranslationsForHandle($handle);
89
-        }
90
-        if ($this->queued_handle_translations) {
91
-            foreach ($this->queued_handle_translations as $handle => $translations_for_domain) {
92
-                $this->registerInlineScript(
93
-                    $handle,
94
-                    $translations_for_domain['translations'],
95
-                    $translations_for_domain['domain']
96
-                );
97
-            }
98
-        }
99
-        return $handles;
100
-    }
101
-
102
-
103
-    /**
104
-     * Registers inline script with translations for given handle and domain.
105
-     *
106
-     * @param string $handle       Handle used to register javascript file containing translations.
107
-     * @param array  $translations Array of string translations.
108
-     * @param string $domain       Domain for translations.  If left empty then strings are registered with the default
109
-     *                             domain for the javascript.
110
-     */
111
-    private function registerInlineScript($handle, array $translations, $domain)
112
-    {
113
-        $script = $domain ?
114
-            'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ', ' . $domain . ' );' :
115
-            'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ' );';
116
-        wp_add_inline_script($handle, $script, 'before');
117
-    }
118
-
119
-
120
-    /**
121
-     * Queues up the translation strings for the given handle.
122
-     *
123
-     * @param string $handle The script handle being queued up.
124
-     */
125
-    private function queueI18nTranslationsForHandle($handle)
126
-    {
127
-        if (isset($this->registered_i18n[$handle])) {
128
-            $domain = $this->registered_i18n[$handle];
129
-            $translations = $this->getJedLocaleDataForDomainAndChunk($handle, $domain);
130
-            if (count($translations) > 1) {
131
-                $this->queued_handle_translations[$handle] = array(
132
-                    'domain'       => $domain,
133
-                    'translations' => $translations,
134
-                );
135
-            }
136
-            unset($this->registered_i18n[$handle]);
137
-        }
138
-    }
139
-
140
-
141
-    /**
142
-     * Sets the internal i18n_map property.
143
-     * If $chunk_map is empty or not an array, will attempt to load a chunk map from a default named map.
144
-     *
145
-     * @param array $i18n_map  If provided, an array of translation strings indexed by script handle names they
146
-     *                         correspond to.
147
-     */
148
-    private function setI18nMap(array $i18n_map)
149
-    {
150
-        if (empty($i18n_map)) {
151
-            $i18n_map = file_exists($this->domain->pluginPath() . 'translation-map.json')
152
-                ? json_decode(
153
-                        file_get_contents($this->domain->pluginPath() . 'translation-map.json'),
154
-                        true
155
-                    )
156
-                : array();
157
-        }
158
-        $this->i18n_map = $i18n_map;
159
-    }
160
-
161
-
162
-    /**
163
-     * Get the jed locale data for a given $handle and domain
164
-     *
165
-     * @param string $handle The name for the script handle we want strings returned for.
166
-     * @param string $domain The i18n domain.
167
-     * @return array
168
-     */
169
-    protected function getJedLocaleDataForDomainAndChunk($handle, $domain)
170
-    {
171
-        $translations = $this->getJedLocaleData($domain);
172
-        // get index for adding back after extracting strings for this $chunk.
173
-        $index = $translations[''];
174
-        $translations = $this->getLocaleDataMatchingMap(
175
-            $this->getOriginalStringsForHandleFromMap($handle),
176
-            $translations
177
-        );
178
-        $translations[''] = $index;
179
-        return $translations;
180
-    }
181
-
182
-
183
-    /**
184
-     * Get locale data for given strings from given translations
185
-     *
186
-     * @param array $string_set   This is the subset of strings (msgIds) we want to extract from the translations array.
187
-     * @param array $translations Translation data to extra strings from.
188
-     * @return array
189
-     */
190
-    protected function getLocaleDataMatchingMap(array $string_set, array $translations)
191
-    {
192
-        if (empty($string_set)) {
193
-            return array();
194
-        }
195
-        // some strings with quotes in them will break on the array_flip, so making sure quotes in the string are
196
-        // slashed also filter falsey values.
197
-        $string_set = array_unique(array_filter(wp_slash($string_set)));
198
-        return array_intersect_key($translations, array_flip($string_set));
199
-    }
200
-
201
-
202
-    /**
203
-     * Get original strings to translate for the given chunk from the map
204
-     *
205
-     * @param string $handle The script handle name to get strings from the map for.
206
-     * @return array
207
-     */
208
-    protected function getOriginalStringsForHandleFromMap($handle)
209
-    {
210
-        return isset($this->i18n_map[$handle]) ? $this->i18n_map[$handle] : array();
211
-    }
212
-
213
-
214
-    /**
215
-     * Returns Jed-formatted localization data.
216
-     *
217
-     * @param  string $domain Translation domain.
218
-     * @return array
219
-     */
220
-    private function getJedLocaleData($domain)
221
-    {
222
-        $translations = get_translations_for_domain($domain);
223
-
224
-        $locale = array(
225
-            '' => array(
226
-                'domain' => $domain,
227
-                'lang'   => is_admin() ? get_user_locale() : get_locale(),
228
-            ),
229
-        );
230
-
231
-        if (! empty($translations->headers['Plural-Forms'])) {
232
-            $locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
233
-        }
234
-
235
-        foreach ($translations->entries as $msgid => $entry) {
236
-            $locale[$msgid] = $entry->translations;
237
-        }
238
-
239
-        return $locale;
240
-    }
17
+	/**
18
+	 * @var DomainInterface
19
+	 */
20
+	private $domain;
21
+
22
+	/**
23
+	 * Will hold all registered i18n scripts.
24
+	 *
25
+	 * @var array
26
+	 */
27
+	private $registered_i18n = array();
28
+
29
+
30
+	/**
31
+	 * Used to hold queued translations for the chunks loading in a view.
32
+	 *
33
+	 * @var array
34
+	 */
35
+	private $queued_handle_translations = array();
36
+
37
+
38
+	/**
39
+	 * Obtained from the generated json file from the all javascript using wp.i18n with a map of script handle names to
40
+	 * translation strings.
41
+	 *
42
+	 * @var array
43
+	 */
44
+	private $i18n_map;
45
+
46
+
47
+	/**
48
+	 * I18nRegistry constructor.
49
+	 *
50
+	 * @param array() $i18n_map  An array of script handle names and the strings translated for those handles.  If not
51
+	 *                            provided, the class will look for map in root of plugin with filename of
52
+	 *                            'translation-map.json'.
53
+	 * @param DomainInterface $domain
54
+	 */
55
+	public function __construct(array $i18n_map = array(), DomainInterface $domain)
56
+	{
57
+		$this->domain = $domain;
58
+		$this->setI18nMap($i18n_map);
59
+		add_filter('print_scripts_array', array($this, 'queueI18n'));
60
+	}
61
+
62
+
63
+	/**
64
+	 * Used to register a script that has i18n strings for its $handle
65
+	 *
66
+	 * @param string $handle The script handle reference.
67
+	 * @param string $domain The i18n domain for the strings.
68
+	 */
69
+	public function registerScriptI18n($handle, $domain = 'event_espresso')
70
+	{
71
+		$this->registered_i18n[$handle] = $domain;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * Callback on print_scripts_array to listen for scripts enqueued and handle setting up the localized data.
78
+	 *
79
+	 * @param array $handles Array of registered script handles.
80
+	 * @return array
81
+	 */
82
+	public function queueI18n(array $handles)
83
+	{
84
+		if (empty($this->registered_i18n) || empty($this->i18n_map)) {
85
+			return $handles;
86
+		}
87
+		foreach ($handles as $handle) {
88
+			$this->queueI18nTranslationsForHandle($handle);
89
+		}
90
+		if ($this->queued_handle_translations) {
91
+			foreach ($this->queued_handle_translations as $handle => $translations_for_domain) {
92
+				$this->registerInlineScript(
93
+					$handle,
94
+					$translations_for_domain['translations'],
95
+					$translations_for_domain['domain']
96
+				);
97
+			}
98
+		}
99
+		return $handles;
100
+	}
101
+
102
+
103
+	/**
104
+	 * Registers inline script with translations for given handle and domain.
105
+	 *
106
+	 * @param string $handle       Handle used to register javascript file containing translations.
107
+	 * @param array  $translations Array of string translations.
108
+	 * @param string $domain       Domain for translations.  If left empty then strings are registered with the default
109
+	 *                             domain for the javascript.
110
+	 */
111
+	private function registerInlineScript($handle, array $translations, $domain)
112
+	{
113
+		$script = $domain ?
114
+			'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ', ' . $domain . ' );' :
115
+			'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ' );';
116
+		wp_add_inline_script($handle, $script, 'before');
117
+	}
118
+
119
+
120
+	/**
121
+	 * Queues up the translation strings for the given handle.
122
+	 *
123
+	 * @param string $handle The script handle being queued up.
124
+	 */
125
+	private function queueI18nTranslationsForHandle($handle)
126
+	{
127
+		if (isset($this->registered_i18n[$handle])) {
128
+			$domain = $this->registered_i18n[$handle];
129
+			$translations = $this->getJedLocaleDataForDomainAndChunk($handle, $domain);
130
+			if (count($translations) > 1) {
131
+				$this->queued_handle_translations[$handle] = array(
132
+					'domain'       => $domain,
133
+					'translations' => $translations,
134
+				);
135
+			}
136
+			unset($this->registered_i18n[$handle]);
137
+		}
138
+	}
139
+
140
+
141
+	/**
142
+	 * Sets the internal i18n_map property.
143
+	 * If $chunk_map is empty or not an array, will attempt to load a chunk map from a default named map.
144
+	 *
145
+	 * @param array $i18n_map  If provided, an array of translation strings indexed by script handle names they
146
+	 *                         correspond to.
147
+	 */
148
+	private function setI18nMap(array $i18n_map)
149
+	{
150
+		if (empty($i18n_map)) {
151
+			$i18n_map = file_exists($this->domain->pluginPath() . 'translation-map.json')
152
+				? json_decode(
153
+						file_get_contents($this->domain->pluginPath() . 'translation-map.json'),
154
+						true
155
+					)
156
+				: array();
157
+		}
158
+		$this->i18n_map = $i18n_map;
159
+	}
160
+
161
+
162
+	/**
163
+	 * Get the jed locale data for a given $handle and domain
164
+	 *
165
+	 * @param string $handle The name for the script handle we want strings returned for.
166
+	 * @param string $domain The i18n domain.
167
+	 * @return array
168
+	 */
169
+	protected function getJedLocaleDataForDomainAndChunk($handle, $domain)
170
+	{
171
+		$translations = $this->getJedLocaleData($domain);
172
+		// get index for adding back after extracting strings for this $chunk.
173
+		$index = $translations[''];
174
+		$translations = $this->getLocaleDataMatchingMap(
175
+			$this->getOriginalStringsForHandleFromMap($handle),
176
+			$translations
177
+		);
178
+		$translations[''] = $index;
179
+		return $translations;
180
+	}
181
+
182
+
183
+	/**
184
+	 * Get locale data for given strings from given translations
185
+	 *
186
+	 * @param array $string_set   This is the subset of strings (msgIds) we want to extract from the translations array.
187
+	 * @param array $translations Translation data to extra strings from.
188
+	 * @return array
189
+	 */
190
+	protected function getLocaleDataMatchingMap(array $string_set, array $translations)
191
+	{
192
+		if (empty($string_set)) {
193
+			return array();
194
+		}
195
+		// some strings with quotes in them will break on the array_flip, so making sure quotes in the string are
196
+		// slashed also filter falsey values.
197
+		$string_set = array_unique(array_filter(wp_slash($string_set)));
198
+		return array_intersect_key($translations, array_flip($string_set));
199
+	}
200
+
201
+
202
+	/**
203
+	 * Get original strings to translate for the given chunk from the map
204
+	 *
205
+	 * @param string $handle The script handle name to get strings from the map for.
206
+	 * @return array
207
+	 */
208
+	protected function getOriginalStringsForHandleFromMap($handle)
209
+	{
210
+		return isset($this->i18n_map[$handle]) ? $this->i18n_map[$handle] : array();
211
+	}
212
+
213
+
214
+	/**
215
+	 * Returns Jed-formatted localization data.
216
+	 *
217
+	 * @param  string $domain Translation domain.
218
+	 * @return array
219
+	 */
220
+	private function getJedLocaleData($domain)
221
+	{
222
+		$translations = get_translations_for_domain($domain);
223
+
224
+		$locale = array(
225
+			'' => array(
226
+				'domain' => $domain,
227
+				'lang'   => is_admin() ? get_user_locale() : get_locale(),
228
+			),
229
+		);
230
+
231
+		if (! empty($translations->headers['Plural-Forms'])) {
232
+			$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
233
+		}
234
+
235
+		foreach ($translations->entries as $msgid => $entry) {
236
+			$locale[$msgid] = $entry->translations;
237
+		}
238
+
239
+		return $locale;
240
+	}
241 241
 }
242 242
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +4 added lines, -5 removed lines patch added patch discarded remove patch
@@ -111,8 +111,7 @@  discard block
 block discarded – undo
111 111
     private function registerInlineScript($handle, array $translations, $domain)
112 112
     {
113 113
         $script = $domain ?
114
-            'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ', ' . $domain . ' );' :
115
-            'wp.i18n.setLocaleData( ' . wp_json_encode($translations) . ' );';
114
+            'wp.i18n.setLocaleData( '.wp_json_encode($translations).', '.$domain.' );' : 'wp.i18n.setLocaleData( '.wp_json_encode($translations).' );';
116 115
         wp_add_inline_script($handle, $script, 'before');
117 116
     }
118 117
 
@@ -148,9 +147,9 @@  discard block
 block discarded – undo
148 147
     private function setI18nMap(array $i18n_map)
149 148
     {
150 149
         if (empty($i18n_map)) {
151
-            $i18n_map = file_exists($this->domain->pluginPath() . 'translation-map.json')
150
+            $i18n_map = file_exists($this->domain->pluginPath().'translation-map.json')
152 151
                 ? json_decode(
153
-                        file_get_contents($this->domain->pluginPath() . 'translation-map.json'),
152
+                        file_get_contents($this->domain->pluginPath().'translation-map.json'),
154 153
                         true
155 154
                     )
156 155
                 : array();
@@ -228,7 +227,7 @@  discard block
 block discarded – undo
228 227
             ),
229 228
         );
230 229
 
231
-        if (! empty($translations->headers['Plural-Forms'])) {
230
+        if ( ! empty($translations->headers['Plural-Forms'])) {
232 231
             $locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
233 232
         }
234 233
 
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Indentation   +2032 added lines, -2032 removed lines patch added patch discarded remove patch
@@ -19,2038 +19,2038 @@
 block discarded – undo
19 19
 {
20 20
 
21 21
 
22
-    /**
23
-     * Used to reference when a registration has never been checked in.
24
-     *
25
-     * @deprecated use \EE_Checkin::status_checked_never instead
26
-     * @type int
27
-     */
28
-    const checkin_status_never = 2;
29
-
30
-    /**
31
-     * Used to reference when a registration has been checked in.
32
-     *
33
-     * @deprecated use \EE_Checkin::status_checked_in instead
34
-     * @type int
35
-     */
36
-    const checkin_status_in = 1;
37
-
38
-
39
-    /**
40
-     * Used to reference when a registration has been checked out.
41
-     *
42
-     * @deprecated use \EE_Checkin::status_checked_out instead
43
-     * @type int
44
-     */
45
-    const checkin_status_out = 0;
46
-
47
-
48
-    /**
49
-     * extra meta key for tracking reg status os trashed registrations
50
-     *
51
-     * @type string
52
-     */
53
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
54
-
55
-
56
-    /**
57
-     * extra meta key for tracking if registration has reserved ticket
58
-     *
59
-     * @type string
60
-     */
61
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
62
-
63
-
64
-    /**
65
-     * @param array  $props_n_values          incoming values
66
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
67
-     *                                        used.)
68
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
69
-     *                                        date_format and the second value is the time format
70
-     * @return EE_Registration
71
-     * @throws EE_Error
72
-     */
73
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
74
-    {
75
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
76
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
77
-    }
78
-
79
-
80
-    /**
81
-     * @param array  $props_n_values  incoming values from the database
82
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
83
-     *                                the website will be used.
84
-     * @return EE_Registration
85
-     */
86
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
87
-    {
88
-        return new self($props_n_values, true, $timezone);
89
-    }
90
-
91
-
92
-    /**
93
-     *        Set Event ID
94
-     *
95
-     * @param        int $EVT_ID Event ID
96
-     * @throws EE_Error
97
-     * @throws RuntimeException
98
-     */
99
-    public function set_event($EVT_ID = 0)
100
-    {
101
-        $this->set('EVT_ID', $EVT_ID);
102
-    }
103
-
104
-
105
-    /**
106
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
107
-     * be routed to internal methods
108
-     *
109
-     * @param string $field_name
110
-     * @param mixed  $field_value
111
-     * @param bool   $use_default
112
-     * @throws EE_Error
113
-     * @throws EntityNotFoundException
114
-     * @throws InvalidArgumentException
115
-     * @throws InvalidDataTypeException
116
-     * @throws InvalidInterfaceException
117
-     * @throws ReflectionException
118
-     * @throws RuntimeException
119
-     */
120
-    public function set($field_name, $field_value, $use_default = false)
121
-    {
122
-        switch ($field_name) {
123
-            case 'REG_code':
124
-                if (! empty($field_value) && $this->reg_code() === null) {
125
-                    $this->set_reg_code($field_value, $use_default);
126
-                }
127
-                break;
128
-            case 'STS_ID':
129
-                $this->set_status($field_value, $use_default);
130
-                break;
131
-            default:
132
-                parent::set($field_name, $field_value, $use_default);
133
-        }
134
-    }
135
-
136
-
137
-    /**
138
-     * Set Status ID
139
-     * updates the registration status and ALSO...
140
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
141
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
142
-     *
143
-     * @param string       $new_STS_ID
144
-     * @param boolean      $use_default
145
-     * @param ContextInterface|null $context
146
-     * @return bool
147
-     * @throws EE_Error
148
-     * @throws EntityNotFoundException
149
-     * @throws InvalidArgumentException
150
-     * @throws ReflectionException
151
-     * @throws RuntimeException
152
-     * @throws InvalidDataTypeException
153
-     * @throws InvalidInterfaceException
154
-     */
155
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
-    {
157
-        // get current REG_Status
158
-        $old_STS_ID = $this->status_ID();
159
-        // if status has changed
160
-        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
161
-            && ! empty($old_STS_ID) // and that old status is actually set
162
-            && ! empty($new_STS_ID) // as well as the new status
163
-            && $this->ID() // ensure registration is in the db
164
-        ) {
165
-            // TO approved
166
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
167
-                // reserve a space by incrementing ticket and datetime sold values
168
-                $this->_reserve_registration_space();
169
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
170
-                // OR FROM  approved
171
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
172
-                // release a space by decrementing ticket and datetime sold values
173
-                $this->_release_registration_space();
174
-                do_action(
175
-                    'AHEE__EE_Registration__set_status__from_approved',
176
-                    $this,
177
-                    $old_STS_ID,
178
-                    $new_STS_ID,
179
-                    $context
180
-                );
181
-            }
182
-            // update status
183
-            parent::set('STS_ID', $new_STS_ID, $use_default);
184
-            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
185
-            if($this->statusChangeUpdatesTransaction($context)) {
186
-                $this->updateTransactionAfterStatusChange();
187
-            }
188
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
189
-            return true;
190
-        }
191
-        //even though the old value matches the new value, it's still good to
192
-        //allow the parent set method to have a say
193
-        parent::set('STS_ID', $new_STS_ID, $use_default);
194
-        return true;
195
-    }
196
-
197
-
198
-    /**
199
-     * update REGs and TXN when cancelled or declined registrations involved
200
-     *
201
-     * @param string       $new_STS_ID
202
-     * @param string       $old_STS_ID
203
-     * @param ContextInterface|null $context
204
-     * @throws EE_Error
205
-     * @throws InvalidArgumentException
206
-     * @throws InvalidDataTypeException
207
-     * @throws InvalidInterfaceException
208
-     * @throws ReflectionException
209
-     */
210
-    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
211
-    {
212
-        // these reg statuses should not be considered in any calculations involving monies owing
213
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
214
-        // true if registration has been cancelled or declined
215
-        $this->updateIfCanceled(
216
-            $closed_reg_statuses,
217
-            $new_STS_ID,
218
-            $old_STS_ID,
219
-            $context
220
-        );
221
-        $this->updateIfDeclined(
222
-            $closed_reg_statuses,
223
-            $new_STS_ID,
224
-            $old_STS_ID,
225
-            $context
226
-        );
227
-    }
228
-
229
-
230
-    /**
231
-     * update REGs and TXN when cancelled or declined registrations involved
232
-     *
233
-     * @param array        $closed_reg_statuses
234
-     * @param string       $new_STS_ID
235
-     * @param string       $old_STS_ID
236
-     * @param ContextInterface|null $context
237
-     * @throws EE_Error
238
-     * @throws InvalidArgumentException
239
-     * @throws InvalidDataTypeException
240
-     * @throws InvalidInterfaceException
241
-     * @throws ReflectionException
242
-     */
243
-    private function updateIfCanceled(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, ContextInterface $context = null)
244
-    {
245
-        // true if registration has been cancelled or declined
246
-        if (in_array($new_STS_ID, $closed_reg_statuses, true)
247
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
248
-        ) {
249
-            /** @type EE_Registration_Processor $registration_processor */
250
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
251
-            /** @type EE_Transaction_Processor $transaction_processor */
252
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
253
-            // cancelled or declined registration
254
-            $registration_processor->update_registration_after_being_canceled_or_declined(
255
-                $this,
256
-                $closed_reg_statuses
257
-            );
258
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
259
-                $this,
260
-                $closed_reg_statuses,
261
-                false
262
-            );
263
-            do_action(
264
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
265
-                $this,
266
-                $old_STS_ID,
267
-                $new_STS_ID,
268
-                $context
269
-            );
270
-            return;
271
-        }
272
-    }
273
-
274
-
275
-    /**
276
-     * update REGs and TXN when cancelled or declined registrations involved
277
-     *
278
-     * @param array        $closed_reg_statuses
279
-     * @param string       $new_STS_ID
280
-     * @param string       $old_STS_ID
281
-     * @param ContextInterface|null $context
282
-     * @throws EE_Error
283
-     * @throws InvalidArgumentException
284
-     * @throws InvalidDataTypeException
285
-     * @throws InvalidInterfaceException
286
-     * @throws ReflectionException
287
-     */
288
-    private function updateIfDeclined(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, ContextInterface $context = null)
289
-    {
290
-        // true if reinstating cancelled or declined registration
291
-        if (in_array($old_STS_ID, $closed_reg_statuses, true)
292
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
293
-        ) {
294
-            /** @type EE_Registration_Processor $registration_processor */
295
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
296
-            /** @type EE_Transaction_Processor $transaction_processor */
297
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
298
-            // reinstating cancelled or declined registration
299
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
300
-                $this,
301
-                $closed_reg_statuses
302
-            );
303
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
304
-                $this,
305
-                $closed_reg_statuses,
306
-                false
307
-            );
308
-            do_action(
309
-                'AHEE__EE_Registration__set_status__after_reinstated',
310
-                $this,
311
-                $old_STS_ID,
312
-                $new_STS_ID,
313
-                $context
314
-            );
315
-        }
316
-    }
317
-
318
-
319
-    /**
320
-     * @param ContextInterface|null $context
321
-     * @return bool
322
-     */
323
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
324
-    {
325
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
326
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
327
-            array('spco_reg_step_attendee_information_process_registrations'),
328
-            $context,
329
-            $this
330
-        );
331
-        return ! (
332
-            $context instanceof ContextInterface
333
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
334
-        );
335
-    }
336
-
337
-
338
-    /**
339
-     * @throws EE_Error
340
-     * @throws EntityNotFoundException
341
-     * @throws InvalidArgumentException
342
-     * @throws InvalidDataTypeException
343
-     * @throws InvalidInterfaceException
344
-     * @throws ReflectionException
345
-     * @throws RuntimeException
346
-     */
347
-    private function updateTransactionAfterStatusChange()
348
-    {
349
-        /** @type EE_Transaction_Payments $transaction_payments */
350
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
351
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
352
-        $this->transaction()->update_status_based_on_total_paid(true);
353
-    }
354
-
355
-
356
-    /**
357
-     *        get Status ID
358
-     */
359
-    public function status_ID()
360
-    {
361
-        return $this->get('STS_ID');
362
-    }
363
-
364
-
365
-    /**
366
-     * Gets the ticket this registration is for
367
-     *
368
-     * @param boolean $include_archived whether to include archived tickets or not.
369
-     *
370
-     * @return EE_Ticket|EE_Base_Class
371
-     * @throws EE_Error
372
-     */
373
-    public function ticket($include_archived = true)
374
-    {
375
-        $query_params = array();
376
-        if ($include_archived) {
377
-            $query_params['default_where_conditions'] = 'none';
378
-        }
379
-        return $this->get_first_related('Ticket', $query_params);
380
-    }
381
-
382
-
383
-    /**
384
-     * Gets the event this registration is for
385
-     *
386
-     * @return EE_Event
387
-     * @throws EE_Error
388
-     * @throws EntityNotFoundException
389
-     */
390
-    public function event()
391
-    {
392
-        $event = $this->get_first_related('Event');
393
-        if (! $event instanceof \EE_Event) {
394
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
395
-        }
396
-        return $event;
397
-    }
398
-
399
-
400
-    /**
401
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
402
-     * with the author of the event this registration is for.
403
-     *
404
-     * @since 4.5.0
405
-     * @return int
406
-     * @throws EE_Error
407
-     * @throws EntityNotFoundException
408
-     */
409
-    public function wp_user()
410
-    {
411
-        $event = $this->event();
412
-        if ($event instanceof EE_Event) {
413
-            return $event->wp_user();
414
-        }
415
-        return 0;
416
-    }
417
-
418
-
419
-    /**
420
-     * increments this registration's related ticket sold and corresponding datetime sold values
421
-     *
422
-     * @return void
423
-     * @throws DomainException
424
-     * @throws EE_Error
425
-     * @throws EntityNotFoundException
426
-     * @throws InvalidArgumentException
427
-     * @throws InvalidDataTypeException
428
-     * @throws InvalidInterfaceException
429
-     * @throws ReflectionException
430
-     * @throws UnexpectedEntityException
431
-     */
432
-    private function _reserve_registration_space()
433
-    {
434
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
435
-        // so stop tracking that this reg has a ticket reserved
436
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
437
-        $ticket = $this->ticket();
438
-        $ticket->increase_sold();
439
-        $ticket->save();
440
-        // possibly set event status to sold out
441
-        $this->event()->perform_sold_out_status_check();
442
-    }
443
-
444
-
445
-    /**
446
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
447
-     *
448
-     * @return void
449
-     * @throws DomainException
450
-     * @throws EE_Error
451
-     * @throws EntityNotFoundException
452
-     * @throws InvalidArgumentException
453
-     * @throws InvalidDataTypeException
454
-     * @throws InvalidInterfaceException
455
-     * @throws ReflectionException
456
-     * @throws UnexpectedEntityException
457
-     */
458
-    private function _release_registration_space()
459
-    {
460
-        $ticket = $this->ticket();
461
-        $ticket->decrease_sold();
462
-        $ticket->save();
463
-        // possibly change event status from sold out back to previous status
464
-        $this->event()->perform_sold_out_status_check();
465
-    }
466
-
467
-
468
-    /**
469
-     * tracks this registration's ticket reservation in extra meta
470
-     * and can increment related ticket reserved and corresponding datetime reserved values
471
-     *
472
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
473
-     * @return void
474
-     * @throws EE_Error
475
-     * @throws InvalidArgumentException
476
-     * @throws InvalidDataTypeException
477
-     * @throws InvalidInterfaceException
478
-     * @throws ReflectionException
479
-     */
480
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
481
-    {
482
-        // only reserve ticket if space is not currently reserved
483
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
484
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
485
-            // IMPORTANT !!!
486
-            // although checking $update_ticket first would be more efficient,
487
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
488
-            if (
489
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
490
-                && $update_ticket
491
-            ) {
492
-                $ticket = $this->ticket();
493
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
494
-                $ticket->save();
495
-            }
496
-        }
497
-    }
498
-
499
-
500
-    /**
501
-     * stops tracking this registration's ticket reservation in extra meta
502
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
503
-     *
504
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
505
-     * @return void
506
-     * @throws EE_Error
507
-     * @throws InvalidArgumentException
508
-     * @throws InvalidDataTypeException
509
-     * @throws InvalidInterfaceException
510
-     * @throws ReflectionException
511
-     */
512
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
513
-    {
514
-        // only release ticket if space is currently reserved
515
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
516
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
517
-            // IMPORTANT !!!
518
-            // although checking $update_ticket first would be more efficient,
519
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
520
-            if (
521
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
522
-                && $update_ticket
523
-            ) {
524
-                $ticket = $this->ticket();
525
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
526
-                $ticket->save();
527
-            }
528
-        }
529
-    }
530
-
531
-
532
-    /**
533
-     * Set Attendee ID
534
-     *
535
-     * @param        int $ATT_ID Attendee ID
536
-     * @throws EE_Error
537
-     * @throws RuntimeException
538
-     */
539
-    public function set_attendee_id($ATT_ID = 0)
540
-    {
541
-        $this->set('ATT_ID', $ATT_ID);
542
-    }
543
-
544
-
545
-    /**
546
-     *        Set Transaction ID
547
-     *
548
-     * @param        int $TXN_ID Transaction ID
549
-     * @throws EE_Error
550
-     * @throws RuntimeException
551
-     */
552
-    public function set_transaction_id($TXN_ID = 0)
553
-    {
554
-        $this->set('TXN_ID', $TXN_ID);
555
-    }
556
-
557
-
558
-    /**
559
-     *        Set Session
560
-     *
561
-     * @param    string $REG_session PHP Session ID
562
-     * @throws EE_Error
563
-     * @throws RuntimeException
564
-     */
565
-    public function set_session($REG_session = '')
566
-    {
567
-        $this->set('REG_session', $REG_session);
568
-    }
569
-
570
-
571
-    /**
572
-     *        Set Registration URL Link
573
-     *
574
-     * @param    string $REG_url_link Registration URL Link
575
-     * @throws EE_Error
576
-     * @throws RuntimeException
577
-     */
578
-    public function set_reg_url_link($REG_url_link = '')
579
-    {
580
-        $this->set('REG_url_link', $REG_url_link);
581
-    }
582
-
583
-
584
-    /**
585
-     *        Set Attendee Counter
586
-     *
587
-     * @param        int $REG_count Primary Attendee
588
-     * @throws EE_Error
589
-     * @throws RuntimeException
590
-     */
591
-    public function set_count($REG_count = 1)
592
-    {
593
-        $this->set('REG_count', $REG_count);
594
-    }
595
-
596
-
597
-    /**
598
-     *        Set Group Size
599
-     *
600
-     * @param        boolean $REG_group_size Group Registration
601
-     * @throws EE_Error
602
-     * @throws RuntimeException
603
-     */
604
-    public function set_group_size($REG_group_size = false)
605
-    {
606
-        $this->set('REG_group_size', $REG_group_size);
607
-    }
608
-
609
-
610
-    /**
611
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
612
-     *    EEM_Registration::status_id_not_approved
613
-     *
614
-     * @return        boolean
615
-     */
616
-    public function is_not_approved()
617
-    {
618
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
619
-    }
620
-
621
-
622
-    /**
623
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
624
-     *    EEM_Registration::status_id_pending_payment
625
-     *
626
-     * @return        boolean
627
-     */
628
-    public function is_pending_payment()
629
-    {
630
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
631
-    }
632
-
633
-
634
-    /**
635
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
636
-     *
637
-     * @return        boolean
638
-     */
639
-    public function is_approved()
640
-    {
641
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
642
-    }
643
-
644
-
645
-    /**
646
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
647
-     *
648
-     * @return        boolean
649
-     */
650
-    public function is_cancelled()
651
-    {
652
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
653
-    }
654
-
655
-
656
-    /**
657
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
658
-     *
659
-     * @return        boolean
660
-     */
661
-    public function is_declined()
662
-    {
663
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
664
-    }
665
-
666
-
667
-    /**
668
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
669
-     *    EEM_Registration::status_id_incomplete
670
-     *
671
-     * @return        boolean
672
-     */
673
-    public function is_incomplete()
674
-    {
675
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
676
-    }
677
-
678
-
679
-    /**
680
-     *        Set Registration Date
681
-     *
682
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
683
-     *                                                 Date
684
-     * @throws EE_Error
685
-     * @throws RuntimeException
686
-     */
687
-    public function set_reg_date($REG_date = false)
688
-    {
689
-        $this->set('REG_date', $REG_date);
690
-    }
691
-
692
-
693
-    /**
694
-     *    Set final price owing for this registration after all ticket/price modifications
695
-     *
696
-     * @access    public
697
-     * @param    float $REG_final_price
698
-     * @throws EE_Error
699
-     * @throws RuntimeException
700
-     */
701
-    public function set_final_price($REG_final_price = 0.00)
702
-    {
703
-        $this->set('REG_final_price', $REG_final_price);
704
-    }
705
-
706
-
707
-    /**
708
-     *    Set amount paid towards this registration's final price
709
-     *
710
-     * @access    public
711
-     * @param    float $REG_paid
712
-     * @throws EE_Error
713
-     * @throws RuntimeException
714
-     */
715
-    public function set_paid($REG_paid = 0.00)
716
-    {
717
-        $this->set('REG_paid', $REG_paid);
718
-    }
719
-
720
-
721
-    /**
722
-     *        Attendee Is Going
723
-     *
724
-     * @param        boolean $REG_att_is_going Attendee Is Going
725
-     * @throws EE_Error
726
-     * @throws RuntimeException
727
-     */
728
-    public function set_att_is_going($REG_att_is_going = false)
729
-    {
730
-        $this->set('REG_att_is_going', $REG_att_is_going);
731
-    }
732
-
733
-
734
-    /**
735
-     * Gets the related attendee
736
-     *
737
-     * @return EE_Attendee
738
-     * @throws EE_Error
739
-     */
740
-    public function attendee()
741
-    {
742
-        return $this->get_first_related('Attendee');
743
-    }
744
-
745
-
746
-    /**
747
-     *        get Event ID
748
-     */
749
-    public function event_ID()
750
-    {
751
-        return $this->get('EVT_ID');
752
-    }
753
-
754
-
755
-    /**
756
-     *        get Event ID
757
-     */
758
-    public function event_name()
759
-    {
760
-        $event = $this->event_obj();
761
-        if ($event) {
762
-            return $event->name();
763
-        } else {
764
-            return null;
765
-        }
766
-    }
767
-
768
-
769
-    /**
770
-     * Fetches the event this registration is for
771
-     *
772
-     * @return EE_Event
773
-     * @throws EE_Error
774
-     */
775
-    public function event_obj()
776
-    {
777
-        return $this->get_first_related('Event');
778
-    }
779
-
780
-
781
-    /**
782
-     *        get Attendee ID
783
-     */
784
-    public function attendee_ID()
785
-    {
786
-        return $this->get('ATT_ID');
787
-    }
788
-
789
-
790
-    /**
791
-     *        get PHP Session ID
792
-     */
793
-    public function session_ID()
794
-    {
795
-        return $this->get('REG_session');
796
-    }
797
-
798
-
799
-    /**
800
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
801
-     *
802
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
803
-     * @return string
804
-     */
805
-    public function receipt_url($messenger = 'html')
806
-    {
807
-
808
-        /**
809
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
810
-         * already in use on old system.  If there is then we just return the standard url for it.
811
-         *
812
-         * @since 4.5.0
813
-         */
814
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
815
-        $has_custom             = EEH_Template::locate_template(
816
-            $template_relative_path,
817
-            array(),
818
-            true,
819
-            true,
820
-            true
821
-        );
822
-
823
-        if ($has_custom) {
824
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
825
-        }
826
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
827
-    }
828
-
829
-
830
-    /**
831
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
832
-     *
833
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
834
-     * @return string
835
-     * @throws EE_Error
836
-     */
837
-    public function invoice_url($messenger = 'html')
838
-    {
839
-        /**
840
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
841
-         * already in use on old system.  If there is then we just return the standard url for it.
842
-         *
843
-         * @since 4.5.0
844
-         */
845
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
846
-        $has_custom             = EEH_Template::locate_template(
847
-            $template_relative_path,
848
-            array(),
849
-            true,
850
-            true,
851
-            true
852
-        );
853
-
854
-        if ($has_custom) {
855
-            if ($messenger == 'html') {
856
-                return $this->invoice_url('launch');
857
-            }
858
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
859
-
860
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
861
-            if ($messenger == 'html') {
862
-                $query_args['html'] = true;
863
-            }
864
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
865
-        }
866
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
867
-    }
868
-
869
-
870
-    /**
871
-     * get Registration URL Link
872
-     *
873
-     * @access public
874
-     * @return string
875
-     * @throws EE_Error
876
-     */
877
-    public function reg_url_link()
878
-    {
879
-        return (string) $this->get('REG_url_link');
880
-    }
881
-
882
-
883
-    /**
884
-     * Echoes out invoice_url()
885
-     *
886
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
887
-     * @return void
888
-     * @throws EE_Error
889
-     */
890
-    public function e_invoice_url($type = 'launch')
891
-    {
892
-        echo $this->invoice_url($type);
893
-    }
894
-
895
-
896
-    /**
897
-     * Echoes out payment_overview_url
898
-     */
899
-    public function e_payment_overview_url()
900
-    {
901
-        echo $this->payment_overview_url();
902
-    }
903
-
904
-
905
-    /**
906
-     * Gets the URL for the checkout payment options reg step
907
-     * with this registration's REG_url_link added as a query parameter
908
-     *
909
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
910
-     *                            payment overview url.
911
-     * @return string
912
-     * @throws InvalidInterfaceException
913
-     * @throws InvalidDataTypeException
914
-     * @throws EE_Error
915
-     * @throws InvalidArgumentException
916
-     */
917
-    public function payment_overview_url($clear_session = false)
918
-    {
919
-        return add_query_arg(
920
-            (array) apply_filters(
921
-                'FHEE__EE_Registration__payment_overview_url__query_args',
922
-                array(
923
-                    'e_reg_url_link' => $this->reg_url_link(),
924
-                    'step'           => 'payment_options',
925
-                    'revisit'        => true,
926
-                    'clear_session'  => (bool) $clear_session,
927
-                ),
928
-                $this
929
-            ),
930
-            EE_Registry::instance()->CFG->core->reg_page_url()
931
-        );
932
-    }
933
-
934
-
935
-    /**
936
-     * Gets the URL for the checkout attendee information reg step
937
-     * with this registration's REG_url_link added as a query parameter
938
-     *
939
-     * @return string
940
-     * @throws InvalidInterfaceException
941
-     * @throws InvalidDataTypeException
942
-     * @throws EE_Error
943
-     * @throws InvalidArgumentException
944
-     */
945
-    public function edit_attendee_information_url()
946
-    {
947
-        return add_query_arg(
948
-            (array) apply_filters(
949
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
950
-                array(
951
-                    'e_reg_url_link' => $this->reg_url_link(),
952
-                    'step'           => 'attendee_information',
953
-                    'revisit'        => true,
954
-                ),
955
-                $this
956
-            ),
957
-            EE_Registry::instance()->CFG->core->reg_page_url()
958
-        );
959
-    }
960
-
961
-
962
-    /**
963
-     * Simply generates and returns the appropriate admin_url link to edit this registration
964
-     *
965
-     * @return string
966
-     * @throws EE_Error
967
-     */
968
-    public function get_admin_edit_url()
969
-    {
970
-        return EEH_URL::add_query_args_and_nonce(array(
971
-            'page'    => 'espresso_registrations',
972
-            'action'  => 'view_registration',
973
-            '_REG_ID' => $this->ID(),
974
-        ), admin_url('admin.php'));
975
-    }
976
-
977
-
978
-    /**
979
-     *    is_primary_registrant?
980
-     */
981
-    public function is_primary_registrant()
982
-    {
983
-        return $this->get('REG_count') == 1 ? true : false;
984
-    }
985
-
986
-
987
-    /**
988
-     * This returns the primary registration object for this registration group (which may be this object).
989
-     *
990
-     * @return EE_Registration
991
-     * @throws EE_Error
992
-     */
993
-    public function get_primary_registration()
994
-    {
995
-        if ($this->is_primary_registrant()) {
996
-            return $this;
997
-        }
998
-
999
-        //k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1000
-        /** @var EE_Registration $primary_registrant */
1001
-        $primary_registrant = EEM_Registration::instance()->get_one(array(
1002
-            array(
1003
-                'TXN_ID'    => $this->transaction_ID(),
1004
-                'REG_count' => 1,
1005
-            ),
1006
-        ));
1007
-        return $primary_registrant;
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     *        get  Attendee Number
1013
-     *
1014
-     * @access        public
1015
-     */
1016
-    public function count()
1017
-    {
1018
-        return $this->get('REG_count');
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     *        get Group Size
1024
-     */
1025
-    public function group_size()
1026
-    {
1027
-        return $this->get('REG_group_size');
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     *        get Registration Date
1033
-     */
1034
-    public function date()
1035
-    {
1036
-        return $this->get('REG_date');
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     * gets a pretty date
1042
-     *
1043
-     * @param string $date_format
1044
-     * @param string $time_format
1045
-     * @return string
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function pretty_date($date_format = null, $time_format = null)
1049
-    {
1050
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1051
-    }
1052
-
1053
-
1054
-    /**
1055
-     * final_price
1056
-     * the registration's share of the transaction total, so that the
1057
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1058
-     *
1059
-     * @return float
1060
-     * @throws EE_Error
1061
-     */
1062
-    public function final_price()
1063
-    {
1064
-        return $this->get('REG_final_price');
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * pretty_final_price
1070
-     *  final price as formatted string, with correct decimal places and currency symbol
1071
-     *
1072
-     * @return string
1073
-     * @throws EE_Error
1074
-     */
1075
-    public function pretty_final_price()
1076
-    {
1077
-        return $this->get_pretty('REG_final_price');
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * get paid (yeah)
1083
-     *
1084
-     * @return float
1085
-     * @throws EE_Error
1086
-     */
1087
-    public function paid()
1088
-    {
1089
-        return $this->get('REG_paid');
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * pretty_paid
1095
-     *
1096
-     * @return float
1097
-     * @throws EE_Error
1098
-     */
1099
-    public function pretty_paid()
1100
-    {
1101
-        return $this->get_pretty('REG_paid');
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * owes_monies_and_can_pay
1107
-     * whether or not this registration has monies owing and it's' status allows payment
1108
-     *
1109
-     * @param array $requires_payment
1110
-     * @return bool
1111
-     * @throws EE_Error
1112
-     */
1113
-    public function owes_monies_and_can_pay($requires_payment = array())
1114
-    {
1115
-        // these reg statuses require payment (if event is not free)
1116
-        $requires_payment = ! empty($requires_payment)
1117
-            ? $requires_payment
1118
-            : EEM_Registration::reg_statuses_that_allow_payment();
1119
-        if (in_array($this->status_ID(), $requires_payment) &&
1120
-            $this->final_price() != 0 &&
1121
-            $this->final_price() != $this->paid()
1122
-        ) {
1123
-            return true;
1124
-        } else {
1125
-            return false;
1126
-        }
1127
-    }
1128
-
1129
-
1130
-    /**
1131
-     * Prints out the return value of $this->pretty_status()
1132
-     *
1133
-     * @param bool $show_icons
1134
-     * @return void
1135
-     * @throws EE_Error
1136
-     */
1137
-    public function e_pretty_status($show_icons = false)
1138
-    {
1139
-        echo $this->pretty_status($show_icons);
1140
-    }
1141
-
1142
-
1143
-    /**
1144
-     * Returns a nice version of the status for displaying to customers
1145
-     *
1146
-     * @param bool $show_icons
1147
-     * @return string
1148
-     * @throws EE_Error
1149
-     */
1150
-    public function pretty_status($show_icons = false)
1151
-    {
1152
-        $status = EEM_Status::instance()->localized_status(
1153
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1154
-            false,
1155
-            'sentence'
1156
-        );
1157
-        $icon   = '';
1158
-        switch ($this->status_ID()) {
1159
-            case EEM_Registration::status_id_approved:
1160
-                $icon = $show_icons
1161
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1162
-                    : '';
1163
-                break;
1164
-            case EEM_Registration::status_id_pending_payment:
1165
-                $icon = $show_icons
1166
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1167
-                    : '';
1168
-                break;
1169
-            case EEM_Registration::status_id_not_approved:
1170
-                $icon = $show_icons
1171
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1172
-                    : '';
1173
-                break;
1174
-            case EEM_Registration::status_id_cancelled:
1175
-                $icon = $show_icons
1176
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1177
-                    : '';
1178
-                break;
1179
-            case EEM_Registration::status_id_incomplete:
1180
-                $icon = $show_icons
1181
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1182
-                    : '';
1183
-                break;
1184
-            case EEM_Registration::status_id_declined:
1185
-                $icon = $show_icons
1186
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1187
-                    : '';
1188
-                break;
1189
-            case EEM_Registration::status_id_wait_list:
1190
-                $icon = $show_icons
1191
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1192
-                    : '';
1193
-                break;
1194
-        }
1195
-        return $icon . $status[$this->status_ID()];
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     *        get Attendee Is Going
1201
-     */
1202
-    public function att_is_going()
1203
-    {
1204
-        return $this->get('REG_att_is_going');
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * Gets related answers
1210
-     *
1211
-     * @param array $query_params like EEM_Base::get_all
1212
-     * @return EE_Answer[]
1213
-     * @throws EE_Error
1214
-     */
1215
-    public function answers($query_params = null)
1216
-    {
1217
-        return $this->get_many_related('Answer', $query_params);
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * Gets the registration's answer value to the specified question
1223
-     * (either the question's ID or a question object)
1224
-     *
1225
-     * @param EE_Question|int $question
1226
-     * @param bool            $pretty_value
1227
-     * @return array|string if pretty_value= true, the result will always be a string
1228
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1229
-     * will convert it into some kind of string)
1230
-     * @throws EE_Error
1231
-     */
1232
-    public function answer_value_to_question($question, $pretty_value = true)
1233
-    {
1234
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1235
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     * question_groups
1241
-     * returns an array of EE_Question_Group objects for this registration
1242
-     *
1243
-     * @return EE_Question_Group[]
1244
-     * @throws EE_Error
1245
-     * @throws EntityNotFoundException
1246
-     */
1247
-    public function question_groups()
1248
-    {
1249
-        $question_groups = array();
1250
-        if ($this->event() instanceof EE_Event) {
1251
-            $question_groups = $this->event()->question_groups(
1252
-                array(
1253
-                    array(
1254
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1255
-                    ),
1256
-                    'order_by' => array('QSG_order' => 'ASC'),
1257
-                )
1258
-            );
1259
-        }
1260
-        return $question_groups;
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * count_question_groups
1266
-     * returns a count of the number of EE_Question_Group objects for this registration
1267
-     *
1268
-     * @return int
1269
-     * @throws EE_Error
1270
-     * @throws EntityNotFoundException
1271
-     */
1272
-    public function count_question_groups()
1273
-    {
1274
-        $qg_count = 0;
1275
-        if ($this->event() instanceof EE_Event) {
1276
-            $qg_count = $this->event()->count_related(
1277
-                'Question_Group',
1278
-                array(
1279
-                    array(
1280
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1281
-                    ),
1282
-                )
1283
-            );
1284
-        }
1285
-        return $qg_count;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * Returns the registration date in the 'standard' string format
1291
-     * (function may be improved in the future to allow for different formats and timezones)
1292
-     *
1293
-     * @return string
1294
-     * @throws EE_Error
1295
-     */
1296
-    public function reg_date()
1297
-    {
1298
-        return $this->get_datetime('REG_date');
1299
-    }
1300
-
1301
-
1302
-    /**
1303
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1304
-     * the ticket this registration purchased, or the datetime they have registered
1305
-     * to attend)
1306
-     *
1307
-     * @return EE_Datetime_Ticket
1308
-     * @throws EE_Error
1309
-     */
1310
-    public function datetime_ticket()
1311
-    {
1312
-        return $this->get_first_related('Datetime_Ticket');
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * Sets the registration's datetime_ticket.
1318
-     *
1319
-     * @param EE_Datetime_Ticket $datetime_ticket
1320
-     * @return EE_Datetime_Ticket
1321
-     * @throws EE_Error
1322
-     */
1323
-    public function set_datetime_ticket($datetime_ticket)
1324
-    {
1325
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1326
-    }
1327
-
1328
-    /**
1329
-     * Gets deleted
1330
-     *
1331
-     * @return bool
1332
-     * @throws EE_Error
1333
-     */
1334
-    public function deleted()
1335
-    {
1336
-        return $this->get('REG_deleted');
1337
-    }
1338
-
1339
-    /**
1340
-     * Sets deleted
1341
-     *
1342
-     * @param boolean $deleted
1343
-     * @return bool
1344
-     * @throws EE_Error
1345
-     * @throws RuntimeException
1346
-     */
1347
-    public function set_deleted($deleted)
1348
-    {
1349
-        if ($deleted) {
1350
-            $this->delete();
1351
-        } else {
1352
-            $this->restore();
1353
-        }
1354
-    }
1355
-
1356
-
1357
-    /**
1358
-     * Get the status object of this object
1359
-     *
1360
-     * @return EE_Status
1361
-     * @throws EE_Error
1362
-     */
1363
-    public function status_obj()
1364
-    {
1365
-        return $this->get_first_related('Status');
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Returns the number of times this registration has checked into any of the datetimes
1371
-     * its available for
1372
-     *
1373
-     * @return int
1374
-     * @throws EE_Error
1375
-     */
1376
-    public function count_checkins()
1377
-    {
1378
-        return $this->get_model()->count_related($this, 'Checkin');
1379
-    }
1380
-
1381
-
1382
-    /**
1383
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1384
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1385
-     *
1386
-     * @return int
1387
-     * @throws EE_Error
1388
-     */
1389
-    public function count_checkins_not_checkedout()
1390
-    {
1391
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1397
-     *
1398
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1399
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1400
-     *                                          consider registration status as well as datetime access.
1401
-     * @return bool
1402
-     * @throws EE_Error
1403
-     */
1404
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1405
-    {
1406
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1407
-
1408
-        //first check registration status
1409
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1410
-            return false;
1411
-        }
1412
-        //is there a datetime ticket that matches this dtt_ID?
1413
-        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1414
-            array(
1415
-                'TKT_ID' => $this->get('TKT_ID'),
1416
-                'DTT_ID' => $DTT_ID,
1417
-            ),
1418
-        )))
1419
-        ) {
1420
-            return false;
1421
-        }
1422
-
1423
-        //final check is against TKT_uses
1424
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1425
-    }
1426
-
1427
-
1428
-    /**
1429
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1430
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1431
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1432
-     * then return false.  Otherwise return true.
1433
-     *
1434
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1435
-     * @return bool true means can checkin.  false means cannot checkin.
1436
-     * @throws EE_Error
1437
-     */
1438
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1439
-    {
1440
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1441
-
1442
-        if (! $DTT_ID) {
1443
-            return false;
1444
-        }
1445
-
1446
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1447
-
1448
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1449
-        // check-in or not.
1450
-        if (! $max_uses || $max_uses === EE_INF) {
1451
-            return true;
1452
-        }
1453
-
1454
-        //does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1455
-        //go ahead and toggle.
1456
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1457
-            return true;
1458
-        }
1459
-
1460
-        //made it here so the last check is whether the number of checkins per unique datetime on this registration
1461
-        //disallows further check-ins.
1462
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1463
-            array(
1464
-                'REG_ID' => $this->ID(),
1465
-                'CHK_in' => true,
1466
-            ),
1467
-        ), 'DTT_ID', true);
1468
-        // checkins have already reached their max number of uses
1469
-        // so registrant can NOT checkin
1470
-        if ($count_unique_dtt_checkins >= $max_uses) {
1471
-            EE_Error::add_error(
1472
-                esc_html__(
1473
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1474
-                    'event_espresso'
1475
-                ),
1476
-                __FILE__,
1477
-                __FUNCTION__,
1478
-                __LINE__
1479
-            );
1480
-            return false;
1481
-        }
1482
-        return true;
1483
-    }
1484
-
1485
-
1486
-    /**
1487
-     * toggle Check-in status for this registration
1488
-     * Check-ins are toggled in the following order:
1489
-     * never checked in -> checked in
1490
-     * checked in -> checked out
1491
-     * checked out -> checked in
1492
-     *
1493
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1494
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1495
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1496
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1497
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1498
-     * @throws EE_Error
1499
-     */
1500
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1501
-    {
1502
-        if (empty($DTT_ID)) {
1503
-            $datetime = $this->get_latest_related_datetime();
1504
-            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1505
-            // verify the registration can checkin for the given DTT_ID
1506
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1507
-            EE_Error::add_error(
1508
-                sprintf(
1509
-                    esc_html__(
1510
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1511
-                        'event_espresso'
1512
-                    ),
1513
-                    $this->ID(),
1514
-                    $DTT_ID
1515
-                ),
1516
-                __FILE__,
1517
-                __FUNCTION__,
1518
-                __LINE__
1519
-            );
1520
-            return false;
1521
-        }
1522
-        $status_paths = array(
1523
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1524
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1525
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1526
-        );
1527
-        //start by getting the current status so we know what status we'll be changing to.
1528
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1529
-        $status_to  = $status_paths[$cur_status];
1530
-        // database only records true for checked IN or false for checked OUT
1531
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1532
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1533
-        // add relation - note Check-ins are always creating new rows
1534
-        // because we are keeping track of Check-ins over time.
1535
-        // Eventually we'll probably want to show a list table
1536
-        // for the individual Check-ins so that they can be managed.
1537
-        $checkin = EE_Checkin::new_instance(array(
1538
-            'REG_ID' => $this->ID(),
1539
-            'DTT_ID' => $DTT_ID,
1540
-            'CHK_in' => $new_status,
1541
-        ));
1542
-        // if the record could not be saved then return false
1543
-        if ($checkin->save() === 0) {
1544
-            if (WP_DEBUG) {
1545
-                global $wpdb;
1546
-                $error = sprintf(
1547
-                    esc_html__(
1548
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1549
-                        'event_espresso'
1550
-                    ),
1551
-                    '<br />',
1552
-                    $wpdb->last_error
1553
-                );
1554
-            } else {
1555
-                $error = esc_html__(
1556
-                    'Registration check in update failed because of an unknown database error',
1557
-                    'event_espresso'
1558
-                );
1559
-            }
1560
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1561
-            return false;
1562
-        }
1563
-        return $status_to;
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1569
-     * "Latest" is defined by the `DTT_EVT_start` column.
1570
-     *
1571
-     * @return EE_Datetime|null
1572
-     * @throws EE_Error
1573
-     */
1574
-    public function get_latest_related_datetime()
1575
-    {
1576
-        return EEM_Datetime::instance()->get_one(
1577
-            array(
1578
-                array(
1579
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1580
-                ),
1581
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1582
-            )
1583
-        );
1584
-    }
1585
-
1586
-
1587
-    /**
1588
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1589
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1590
-     *
1591
-     * @throws EE_Error
1592
-     */
1593
-    public function get_earliest_related_datetime()
1594
-    {
1595
-        return EEM_Datetime::instance()->get_one(
1596
-            array(
1597
-                array(
1598
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1599
-                ),
1600
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1601
-            )
1602
-        );
1603
-    }
1604
-
1605
-
1606
-    /**
1607
-     * This method simply returns the check-in status for this registration and the given datetime.
1608
-     * If neither the datetime nor the checkin values are provided as arguments,
1609
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1610
-     *
1611
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1612
-     *                            (if empty we'll get the primary datetime for
1613
-     *                            this registration (via event) and use it's ID);
1614
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1615
-     *
1616
-     * @return int                Integer representing Check-in status.
1617
-     * @throws EE_Error
1618
-     */
1619
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1620
-    {
1621
-        $checkin_query_params = array(
1622
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1623
-        );
1624
-
1625
-        if ($DTT_ID > 0) {
1626
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1627
-        }
1628
-
1629
-        //get checkin object (if exists)
1630
-        $checkin = $checkin instanceof EE_Checkin
1631
-            ? $checkin
1632
-            : $this->get_first_related('Checkin', $checkin_query_params);
1633
-        if ($checkin instanceof EE_Checkin) {
1634
-            if ($checkin->get('CHK_in')) {
1635
-                return EE_Checkin::status_checked_in; //checked in
1636
-            }
1637
-            return EE_Checkin::status_checked_out; //had checked in but is now checked out.
1638
-        }
1639
-        return EE_Checkin::status_checked_never; //never been checked in
1640
-    }
1641
-
1642
-
1643
-    /**
1644
-     * This method returns a localized message for the toggled Check-in message.
1645
-     *
1646
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1647
-     *                     then it is assumed Check-in for primary datetime was toggled.
1648
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1649
-     *                     message can be customized with the attendee name.
1650
-     * @return string internationalized message
1651
-     * @throws EE_Error
1652
-     */
1653
-    public function get_checkin_msg($DTT_ID, $error = false)
1654
-    {
1655
-        //let's get the attendee first so we can include the name of the attendee
1656
-        $attendee = $this->get_first_related('Attendee');
1657
-        if ($attendee instanceof EE_Attendee) {
1658
-            if ($error) {
1659
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1660
-            }
1661
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1662
-            //what is the status message going to be?
1663
-            switch ($cur_status) {
1664
-                case EE_Checkin::status_checked_never:
1665
-                    return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1666
-                        $attendee->full_name());
1667
-                    break;
1668
-                case EE_Checkin::status_checked_in:
1669
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1670
-                    break;
1671
-                case EE_Checkin::status_checked_out:
1672
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1673
-                    break;
1674
-            }
1675
-        }
1676
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1677
-    }
1678
-
1679
-
1680
-    /**
1681
-     * Returns the related EE_Transaction to this registration
1682
-     *
1683
-     * @return EE_Transaction
1684
-     * @throws EE_Error
1685
-     * @throws EntityNotFoundException
1686
-     */
1687
-    public function transaction()
1688
-    {
1689
-        $transaction = $this->get_first_related('Transaction');
1690
-        if (! $transaction instanceof \EE_Transaction) {
1691
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1692
-        }
1693
-        return $transaction;
1694
-    }
1695
-
1696
-
1697
-    /**
1698
-     *        get Registration Code
1699
-     */
1700
-    public function reg_code()
1701
-    {
1702
-        return $this->get('REG_code');
1703
-    }
1704
-
1705
-
1706
-    /**
1707
-     *        get Transaction ID
1708
-     */
1709
-    public function transaction_ID()
1710
-    {
1711
-        return $this->get('TXN_ID');
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * @return int
1717
-     * @throws EE_Error
1718
-     */
1719
-    public function ticket_ID()
1720
-    {
1721
-        return $this->get('TKT_ID');
1722
-    }
1723
-
1724
-
1725
-    /**
1726
-     *        Set Registration Code
1727
-     *
1728
-     * @access    public
1729
-     * @param    string  $REG_code Registration Code
1730
-     * @param    boolean $use_default
1731
-     * @throws EE_Error
1732
-     */
1733
-    public function set_reg_code($REG_code, $use_default = false)
1734
-    {
1735
-        if (empty($REG_code)) {
1736
-            EE_Error::add_error(
1737
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1738
-                __FILE__,
1739
-                __FUNCTION__,
1740
-                __LINE__
1741
-            );
1742
-            return;
1743
-        }
1744
-        if (! $this->reg_code()) {
1745
-            parent::set('REG_code', $REG_code, $use_default);
1746
-        } else {
1747
-            EE_Error::doing_it_wrong(
1748
-                __CLASS__ . '::' . __FUNCTION__,
1749
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1750
-                '4.6.0'
1751
-            );
1752
-        }
1753
-    }
1754
-
1755
-
1756
-    /**
1757
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1758
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1759
-     *    $registration->transaction()->registrations();
1760
-     *
1761
-     * @since 4.5.0
1762
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1763
-     * @throws EE_Error
1764
-     */
1765
-    public function get_all_other_registrations_in_group()
1766
-    {
1767
-        if ($this->group_size() < 2) {
1768
-            return array();
1769
-        }
1770
-
1771
-        $query[0] = array(
1772
-            'TXN_ID' => $this->transaction_ID(),
1773
-            'REG_ID' => array('!=', $this->ID()),
1774
-            'TKT_ID' => $this->ticket_ID(),
1775
-        );
1776
-        /** @var EE_Registration[] $registrations */
1777
-        $registrations = $this->get_model()->get_all($query);
1778
-        return $registrations;
1779
-    }
1780
-
1781
-    /**
1782
-     * Return the link to the admin details for the object.
1783
-     *
1784
-     * @return string
1785
-     * @throws EE_Error
1786
-     */
1787
-    public function get_admin_details_link()
1788
-    {
1789
-        EE_Registry::instance()->load_helper('URL');
1790
-        return EEH_URL::add_query_args_and_nonce(
1791
-            array(
1792
-                'page'    => 'espresso_registrations',
1793
-                'action'  => 'view_registration',
1794
-                '_REG_ID' => $this->ID(),
1795
-            ),
1796
-            admin_url('admin.php')
1797
-        );
1798
-    }
1799
-
1800
-    /**
1801
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1802
-     *
1803
-     * @return string
1804
-     * @throws EE_Error
1805
-     */
1806
-    public function get_admin_edit_link()
1807
-    {
1808
-        return $this->get_admin_details_link();
1809
-    }
1810
-
1811
-    /**
1812
-     * Returns the link to a settings page for the object.
1813
-     *
1814
-     * @return string
1815
-     * @throws EE_Error
1816
-     */
1817
-    public function get_admin_settings_link()
1818
-    {
1819
-        return $this->get_admin_details_link();
1820
-    }
1821
-
1822
-    /**
1823
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1824
-     *
1825
-     * @return string
1826
-     */
1827
-    public function get_admin_overview_link()
1828
-    {
1829
-        EE_Registry::instance()->load_helper('URL');
1830
-        return EEH_URL::add_query_args_and_nonce(
1831
-            array(
1832
-                'page' => 'espresso_registrations',
1833
-            ),
1834
-            admin_url('admin.php')
1835
-        );
1836
-    }
1837
-
1838
-
1839
-    /**
1840
-     * @param array $query_params
1841
-     *
1842
-     * @return \EE_Registration[]
1843
-     * @throws EE_Error
1844
-     */
1845
-    public function payments($query_params = array())
1846
-    {
1847
-        return $this->get_many_related('Payment', $query_params);
1848
-    }
1849
-
1850
-
1851
-    /**
1852
-     * @param array $query_params
1853
-     *
1854
-     * @return \EE_Registration_Payment[]
1855
-     * @throws EE_Error
1856
-     */
1857
-    public function registration_payments($query_params = array())
1858
-    {
1859
-        return $this->get_many_related('Registration_Payment', $query_params);
1860
-    }
1861
-
1862
-
1863
-    /**
1864
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1865
-     * Note: if there are no payments on the registration there will be no payment method returned.
1866
-     *
1867
-     * @return EE_Payment_Method|null
1868
-     */
1869
-    public function payment_method()
1870
-    {
1871
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1872
-    }
1873
-
1874
-
1875
-    /**
1876
-     * @return \EE_Line_Item
1877
-     * @throws EntityNotFoundException
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function ticket_line_item()
1881
-    {
1882
-        $ticket            = $this->ticket();
1883
-        $transaction       = $this->transaction();
1884
-        $line_item         = null;
1885
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1886
-            $transaction->total_line_item(),
1887
-            'Ticket',
1888
-            array($ticket->ID())
1889
-        );
1890
-        foreach ($ticket_line_items as $ticket_line_item) {
1891
-            if (
1892
-                $ticket_line_item instanceof \EE_Line_Item
1893
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1894
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1895
-            ) {
1896
-                $line_item = $ticket_line_item;
1897
-                break;
1898
-            }
1899
-        }
1900
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1901
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1902
-        }
1903
-        return $line_item;
1904
-    }
1905
-
1906
-
1907
-    /**
1908
-     * Soft Deletes this model object.
1909
-     *
1910
-     * @return boolean | int
1911
-     * @throws RuntimeException
1912
-     * @throws EE_Error
1913
-     */
1914
-    public function delete()
1915
-    {
1916
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1917
-            $this->set_status(EEM_Registration::status_id_cancelled);
1918
-        }
1919
-        return parent::delete();
1920
-    }
1921
-
1922
-
1923
-    /**
1924
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1925
-     *
1926
-     * @throws EE_Error
1927
-     * @throws RuntimeException
1928
-     */
1929
-    public function restore()
1930
-    {
1931
-        $previous_status = $this->get_extra_meta(
1932
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1933
-            true,
1934
-            EEM_Registration::status_id_cancelled
1935
-        );
1936
-        if ($previous_status) {
1937
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1938
-            $this->set_status($previous_status);
1939
-        }
1940
-        return parent::restore();
1941
-    }
1942
-
1943
-
1944
-    /**
1945
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1946
-     *
1947
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1948
-     *                                           depending on whether the reg status changes to or from "Approved"
1949
-     * @return boolean whether the Registration status was updated
1950
-     * @throws EE_Error
1951
-     * @throws RuntimeException
1952
-     */
1953
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1954
-    {
1955
-        $paid = $this->paid();
1956
-        $price = $this->final_price();
1957
-        switch(true) {
1958
-            // overpaid or paid
1959
-            case EEH_Money::compare_floats($paid, $price, '>'):
1960
-            case EEH_Money::compare_floats($paid, $price):
1961
-                $new_status = EEM_Registration::status_id_approved;
1962
-                break;
1963
-            //  underpaid
1964
-            case EEH_Money::compare_floats($paid, $price, '<'):
1965
-                $new_status = EEM_Registration::status_id_pending_payment;
1966
-                break;
1967
-            // uhhh Houston...
1968
-            default:
1969
-                throw new RuntimeException(
1970
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1971
-                );
1972
-        }
1973
-        if ($new_status !== $this->status_ID()) {
1974
-            if ($trigger_set_status_logic) {
1975
-                return $this->set_status($new_status);
1976
-            }
1977
-            parent::set('STS_ID', $new_status);
1978
-            return true;
1979
-        }
1980
-        return false;
1981
-    }
1982
-
1983
-
1984
-    /*************************** DEPRECATED ***************************/
1985
-
1986
-
1987
-    /**
1988
-     * @deprecated
1989
-     * @since     4.7.0
1990
-     * @access    public
1991
-     */
1992
-    public function price_paid()
1993
-    {
1994
-        EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1995
-            esc_html__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1996
-            '4.7.0');
1997
-        return $this->final_price();
1998
-    }
1999
-
2000
-
2001
-    /**
2002
-     * @deprecated
2003
-     * @since     4.7.0
2004
-     * @access    public
2005
-     * @param    float $REG_final_price
2006
-     * @throws EE_Error
2007
-     * @throws RuntimeException
2008
-     */
2009
-    public function set_price_paid($REG_final_price = 0.00)
2010
-    {
2011
-        EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
2012
-            esc_html__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
2013
-            '4.7.0');
2014
-        $this->set_final_price($REG_final_price);
2015
-    }
2016
-
2017
-
2018
-    /**
2019
-     * @deprecated
2020
-     * @since 4.7.0
2021
-     * @return string
2022
-     * @throws EE_Error
2023
-     */
2024
-    public function pretty_price_paid()
2025
-    {
2026
-        EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
2027
-            esc_html__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2028
-                'event_espresso'), '4.7.0');
2029
-        return $this->pretty_final_price();
2030
-    }
2031
-
2032
-
2033
-    /**
2034
-     * Gets the primary datetime related to this registration via the related Event to this registration
2035
-     *
2036
-     * @deprecated 4.9.17
2037
-     * @return EE_Datetime
2038
-     * @throws EE_Error
2039
-     * @throws EntityNotFoundException
2040
-     */
2041
-    public function get_related_primary_datetime()
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            __METHOD__,
2045
-            esc_html__(
2046
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2047
-                'event_espresso'
2048
-            ),
2049
-            '4.9.17',
2050
-            '5.0.0'
2051
-        );
2052
-        return $this->event()->primary_datetime();
2053
-    }
22
+	/**
23
+	 * Used to reference when a registration has never been checked in.
24
+	 *
25
+	 * @deprecated use \EE_Checkin::status_checked_never instead
26
+	 * @type int
27
+	 */
28
+	const checkin_status_never = 2;
29
+
30
+	/**
31
+	 * Used to reference when a registration has been checked in.
32
+	 *
33
+	 * @deprecated use \EE_Checkin::status_checked_in instead
34
+	 * @type int
35
+	 */
36
+	const checkin_status_in = 1;
37
+
38
+
39
+	/**
40
+	 * Used to reference when a registration has been checked out.
41
+	 *
42
+	 * @deprecated use \EE_Checkin::status_checked_out instead
43
+	 * @type int
44
+	 */
45
+	const checkin_status_out = 0;
46
+
47
+
48
+	/**
49
+	 * extra meta key for tracking reg status os trashed registrations
50
+	 *
51
+	 * @type string
52
+	 */
53
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
54
+
55
+
56
+	/**
57
+	 * extra meta key for tracking if registration has reserved ticket
58
+	 *
59
+	 * @type string
60
+	 */
61
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
62
+
63
+
64
+	/**
65
+	 * @param array  $props_n_values          incoming values
66
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
67
+	 *                                        used.)
68
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
69
+	 *                                        date_format and the second value is the time format
70
+	 * @return EE_Registration
71
+	 * @throws EE_Error
72
+	 */
73
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
74
+	{
75
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
76
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
77
+	}
78
+
79
+
80
+	/**
81
+	 * @param array  $props_n_values  incoming values from the database
82
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
83
+	 *                                the website will be used.
84
+	 * @return EE_Registration
85
+	 */
86
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
87
+	{
88
+		return new self($props_n_values, true, $timezone);
89
+	}
90
+
91
+
92
+	/**
93
+	 *        Set Event ID
94
+	 *
95
+	 * @param        int $EVT_ID Event ID
96
+	 * @throws EE_Error
97
+	 * @throws RuntimeException
98
+	 */
99
+	public function set_event($EVT_ID = 0)
100
+	{
101
+		$this->set('EVT_ID', $EVT_ID);
102
+	}
103
+
104
+
105
+	/**
106
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
107
+	 * be routed to internal methods
108
+	 *
109
+	 * @param string $field_name
110
+	 * @param mixed  $field_value
111
+	 * @param bool   $use_default
112
+	 * @throws EE_Error
113
+	 * @throws EntityNotFoundException
114
+	 * @throws InvalidArgumentException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws InvalidInterfaceException
117
+	 * @throws ReflectionException
118
+	 * @throws RuntimeException
119
+	 */
120
+	public function set($field_name, $field_value, $use_default = false)
121
+	{
122
+		switch ($field_name) {
123
+			case 'REG_code':
124
+				if (! empty($field_value) && $this->reg_code() === null) {
125
+					$this->set_reg_code($field_value, $use_default);
126
+				}
127
+				break;
128
+			case 'STS_ID':
129
+				$this->set_status($field_value, $use_default);
130
+				break;
131
+			default:
132
+				parent::set($field_name, $field_value, $use_default);
133
+		}
134
+	}
135
+
136
+
137
+	/**
138
+	 * Set Status ID
139
+	 * updates the registration status and ALSO...
140
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
141
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
142
+	 *
143
+	 * @param string       $new_STS_ID
144
+	 * @param boolean      $use_default
145
+	 * @param ContextInterface|null $context
146
+	 * @return bool
147
+	 * @throws EE_Error
148
+	 * @throws EntityNotFoundException
149
+	 * @throws InvalidArgumentException
150
+	 * @throws ReflectionException
151
+	 * @throws RuntimeException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws InvalidInterfaceException
154
+	 */
155
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
+	{
157
+		// get current REG_Status
158
+		$old_STS_ID = $this->status_ID();
159
+		// if status has changed
160
+		if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
161
+			&& ! empty($old_STS_ID) // and that old status is actually set
162
+			&& ! empty($new_STS_ID) // as well as the new status
163
+			&& $this->ID() // ensure registration is in the db
164
+		) {
165
+			// TO approved
166
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
167
+				// reserve a space by incrementing ticket and datetime sold values
168
+				$this->_reserve_registration_space();
169
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
170
+				// OR FROM  approved
171
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
172
+				// release a space by decrementing ticket and datetime sold values
173
+				$this->_release_registration_space();
174
+				do_action(
175
+					'AHEE__EE_Registration__set_status__from_approved',
176
+					$this,
177
+					$old_STS_ID,
178
+					$new_STS_ID,
179
+					$context
180
+				);
181
+			}
182
+			// update status
183
+			parent::set('STS_ID', $new_STS_ID, $use_default);
184
+			$this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
185
+			if($this->statusChangeUpdatesTransaction($context)) {
186
+				$this->updateTransactionAfterStatusChange();
187
+			}
188
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
189
+			return true;
190
+		}
191
+		//even though the old value matches the new value, it's still good to
192
+		//allow the parent set method to have a say
193
+		parent::set('STS_ID', $new_STS_ID, $use_default);
194
+		return true;
195
+	}
196
+
197
+
198
+	/**
199
+	 * update REGs and TXN when cancelled or declined registrations involved
200
+	 *
201
+	 * @param string       $new_STS_ID
202
+	 * @param string       $old_STS_ID
203
+	 * @param ContextInterface|null $context
204
+	 * @throws EE_Error
205
+	 * @throws InvalidArgumentException
206
+	 * @throws InvalidDataTypeException
207
+	 * @throws InvalidInterfaceException
208
+	 * @throws ReflectionException
209
+	 */
210
+	private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
211
+	{
212
+		// these reg statuses should not be considered in any calculations involving monies owing
213
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
214
+		// true if registration has been cancelled or declined
215
+		$this->updateIfCanceled(
216
+			$closed_reg_statuses,
217
+			$new_STS_ID,
218
+			$old_STS_ID,
219
+			$context
220
+		);
221
+		$this->updateIfDeclined(
222
+			$closed_reg_statuses,
223
+			$new_STS_ID,
224
+			$old_STS_ID,
225
+			$context
226
+		);
227
+	}
228
+
229
+
230
+	/**
231
+	 * update REGs and TXN when cancelled or declined registrations involved
232
+	 *
233
+	 * @param array        $closed_reg_statuses
234
+	 * @param string       $new_STS_ID
235
+	 * @param string       $old_STS_ID
236
+	 * @param ContextInterface|null $context
237
+	 * @throws EE_Error
238
+	 * @throws InvalidArgumentException
239
+	 * @throws InvalidDataTypeException
240
+	 * @throws InvalidInterfaceException
241
+	 * @throws ReflectionException
242
+	 */
243
+	private function updateIfCanceled(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, ContextInterface $context = null)
244
+	{
245
+		// true if registration has been cancelled or declined
246
+		if (in_array($new_STS_ID, $closed_reg_statuses, true)
247
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
248
+		) {
249
+			/** @type EE_Registration_Processor $registration_processor */
250
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
251
+			/** @type EE_Transaction_Processor $transaction_processor */
252
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
253
+			// cancelled or declined registration
254
+			$registration_processor->update_registration_after_being_canceled_or_declined(
255
+				$this,
256
+				$closed_reg_statuses
257
+			);
258
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
259
+				$this,
260
+				$closed_reg_statuses,
261
+				false
262
+			);
263
+			do_action(
264
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
265
+				$this,
266
+				$old_STS_ID,
267
+				$new_STS_ID,
268
+				$context
269
+			);
270
+			return;
271
+		}
272
+	}
273
+
274
+
275
+	/**
276
+	 * update REGs and TXN when cancelled or declined registrations involved
277
+	 *
278
+	 * @param array        $closed_reg_statuses
279
+	 * @param string       $new_STS_ID
280
+	 * @param string       $old_STS_ID
281
+	 * @param ContextInterface|null $context
282
+	 * @throws EE_Error
283
+	 * @throws InvalidArgumentException
284
+	 * @throws InvalidDataTypeException
285
+	 * @throws InvalidInterfaceException
286
+	 * @throws ReflectionException
287
+	 */
288
+	private function updateIfDeclined(array $closed_reg_statuses, $new_STS_ID, $old_STS_ID, ContextInterface $context = null)
289
+	{
290
+		// true if reinstating cancelled or declined registration
291
+		if (in_array($old_STS_ID, $closed_reg_statuses, true)
292
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
293
+		) {
294
+			/** @type EE_Registration_Processor $registration_processor */
295
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
296
+			/** @type EE_Transaction_Processor $transaction_processor */
297
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
298
+			// reinstating cancelled or declined registration
299
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
300
+				$this,
301
+				$closed_reg_statuses
302
+			);
303
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
304
+				$this,
305
+				$closed_reg_statuses,
306
+				false
307
+			);
308
+			do_action(
309
+				'AHEE__EE_Registration__set_status__after_reinstated',
310
+				$this,
311
+				$old_STS_ID,
312
+				$new_STS_ID,
313
+				$context
314
+			);
315
+		}
316
+	}
317
+
318
+
319
+	/**
320
+	 * @param ContextInterface|null $context
321
+	 * @return bool
322
+	 */
323
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
324
+	{
325
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
326
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
327
+			array('spco_reg_step_attendee_information_process_registrations'),
328
+			$context,
329
+			$this
330
+		);
331
+		return ! (
332
+			$context instanceof ContextInterface
333
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
334
+		);
335
+	}
336
+
337
+
338
+	/**
339
+	 * @throws EE_Error
340
+	 * @throws EntityNotFoundException
341
+	 * @throws InvalidArgumentException
342
+	 * @throws InvalidDataTypeException
343
+	 * @throws InvalidInterfaceException
344
+	 * @throws ReflectionException
345
+	 * @throws RuntimeException
346
+	 */
347
+	private function updateTransactionAfterStatusChange()
348
+	{
349
+		/** @type EE_Transaction_Payments $transaction_payments */
350
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
351
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
352
+		$this->transaction()->update_status_based_on_total_paid(true);
353
+	}
354
+
355
+
356
+	/**
357
+	 *        get Status ID
358
+	 */
359
+	public function status_ID()
360
+	{
361
+		return $this->get('STS_ID');
362
+	}
363
+
364
+
365
+	/**
366
+	 * Gets the ticket this registration is for
367
+	 *
368
+	 * @param boolean $include_archived whether to include archived tickets or not.
369
+	 *
370
+	 * @return EE_Ticket|EE_Base_Class
371
+	 * @throws EE_Error
372
+	 */
373
+	public function ticket($include_archived = true)
374
+	{
375
+		$query_params = array();
376
+		if ($include_archived) {
377
+			$query_params['default_where_conditions'] = 'none';
378
+		}
379
+		return $this->get_first_related('Ticket', $query_params);
380
+	}
381
+
382
+
383
+	/**
384
+	 * Gets the event this registration is for
385
+	 *
386
+	 * @return EE_Event
387
+	 * @throws EE_Error
388
+	 * @throws EntityNotFoundException
389
+	 */
390
+	public function event()
391
+	{
392
+		$event = $this->get_first_related('Event');
393
+		if (! $event instanceof \EE_Event) {
394
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
395
+		}
396
+		return $event;
397
+	}
398
+
399
+
400
+	/**
401
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
402
+	 * with the author of the event this registration is for.
403
+	 *
404
+	 * @since 4.5.0
405
+	 * @return int
406
+	 * @throws EE_Error
407
+	 * @throws EntityNotFoundException
408
+	 */
409
+	public function wp_user()
410
+	{
411
+		$event = $this->event();
412
+		if ($event instanceof EE_Event) {
413
+			return $event->wp_user();
414
+		}
415
+		return 0;
416
+	}
417
+
418
+
419
+	/**
420
+	 * increments this registration's related ticket sold and corresponding datetime sold values
421
+	 *
422
+	 * @return void
423
+	 * @throws DomainException
424
+	 * @throws EE_Error
425
+	 * @throws EntityNotFoundException
426
+	 * @throws InvalidArgumentException
427
+	 * @throws InvalidDataTypeException
428
+	 * @throws InvalidInterfaceException
429
+	 * @throws ReflectionException
430
+	 * @throws UnexpectedEntityException
431
+	 */
432
+	private function _reserve_registration_space()
433
+	{
434
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
435
+		// so stop tracking that this reg has a ticket reserved
436
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
437
+		$ticket = $this->ticket();
438
+		$ticket->increase_sold();
439
+		$ticket->save();
440
+		// possibly set event status to sold out
441
+		$this->event()->perform_sold_out_status_check();
442
+	}
443
+
444
+
445
+	/**
446
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
447
+	 *
448
+	 * @return void
449
+	 * @throws DomainException
450
+	 * @throws EE_Error
451
+	 * @throws EntityNotFoundException
452
+	 * @throws InvalidArgumentException
453
+	 * @throws InvalidDataTypeException
454
+	 * @throws InvalidInterfaceException
455
+	 * @throws ReflectionException
456
+	 * @throws UnexpectedEntityException
457
+	 */
458
+	private function _release_registration_space()
459
+	{
460
+		$ticket = $this->ticket();
461
+		$ticket->decrease_sold();
462
+		$ticket->save();
463
+		// possibly change event status from sold out back to previous status
464
+		$this->event()->perform_sold_out_status_check();
465
+	}
466
+
467
+
468
+	/**
469
+	 * tracks this registration's ticket reservation in extra meta
470
+	 * and can increment related ticket reserved and corresponding datetime reserved values
471
+	 *
472
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
473
+	 * @return void
474
+	 * @throws EE_Error
475
+	 * @throws InvalidArgumentException
476
+	 * @throws InvalidDataTypeException
477
+	 * @throws InvalidInterfaceException
478
+	 * @throws ReflectionException
479
+	 */
480
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
481
+	{
482
+		// only reserve ticket if space is not currently reserved
483
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
484
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
485
+			// IMPORTANT !!!
486
+			// although checking $update_ticket first would be more efficient,
487
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
488
+			if (
489
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
490
+				&& $update_ticket
491
+			) {
492
+				$ticket = $this->ticket();
493
+				$ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
494
+				$ticket->save();
495
+			}
496
+		}
497
+	}
498
+
499
+
500
+	/**
501
+	 * stops tracking this registration's ticket reservation in extra meta
502
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
503
+	 *
504
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
505
+	 * @return void
506
+	 * @throws EE_Error
507
+	 * @throws InvalidArgumentException
508
+	 * @throws InvalidDataTypeException
509
+	 * @throws InvalidInterfaceException
510
+	 * @throws ReflectionException
511
+	 */
512
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
513
+	{
514
+		// only release ticket if space is currently reserved
515
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
516
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
517
+			// IMPORTANT !!!
518
+			// although checking $update_ticket first would be more efficient,
519
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
520
+			if (
521
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
522
+				&& $update_ticket
523
+			) {
524
+				$ticket = $this->ticket();
525
+				$ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
526
+				$ticket->save();
527
+			}
528
+		}
529
+	}
530
+
531
+
532
+	/**
533
+	 * Set Attendee ID
534
+	 *
535
+	 * @param        int $ATT_ID Attendee ID
536
+	 * @throws EE_Error
537
+	 * @throws RuntimeException
538
+	 */
539
+	public function set_attendee_id($ATT_ID = 0)
540
+	{
541
+		$this->set('ATT_ID', $ATT_ID);
542
+	}
543
+
544
+
545
+	/**
546
+	 *        Set Transaction ID
547
+	 *
548
+	 * @param        int $TXN_ID Transaction ID
549
+	 * @throws EE_Error
550
+	 * @throws RuntimeException
551
+	 */
552
+	public function set_transaction_id($TXN_ID = 0)
553
+	{
554
+		$this->set('TXN_ID', $TXN_ID);
555
+	}
556
+
557
+
558
+	/**
559
+	 *        Set Session
560
+	 *
561
+	 * @param    string $REG_session PHP Session ID
562
+	 * @throws EE_Error
563
+	 * @throws RuntimeException
564
+	 */
565
+	public function set_session($REG_session = '')
566
+	{
567
+		$this->set('REG_session', $REG_session);
568
+	}
569
+
570
+
571
+	/**
572
+	 *        Set Registration URL Link
573
+	 *
574
+	 * @param    string $REG_url_link Registration URL Link
575
+	 * @throws EE_Error
576
+	 * @throws RuntimeException
577
+	 */
578
+	public function set_reg_url_link($REG_url_link = '')
579
+	{
580
+		$this->set('REG_url_link', $REG_url_link);
581
+	}
582
+
583
+
584
+	/**
585
+	 *        Set Attendee Counter
586
+	 *
587
+	 * @param        int $REG_count Primary Attendee
588
+	 * @throws EE_Error
589
+	 * @throws RuntimeException
590
+	 */
591
+	public function set_count($REG_count = 1)
592
+	{
593
+		$this->set('REG_count', $REG_count);
594
+	}
595
+
596
+
597
+	/**
598
+	 *        Set Group Size
599
+	 *
600
+	 * @param        boolean $REG_group_size Group Registration
601
+	 * @throws EE_Error
602
+	 * @throws RuntimeException
603
+	 */
604
+	public function set_group_size($REG_group_size = false)
605
+	{
606
+		$this->set('REG_group_size', $REG_group_size);
607
+	}
608
+
609
+
610
+	/**
611
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
612
+	 *    EEM_Registration::status_id_not_approved
613
+	 *
614
+	 * @return        boolean
615
+	 */
616
+	public function is_not_approved()
617
+	{
618
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
619
+	}
620
+
621
+
622
+	/**
623
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
624
+	 *    EEM_Registration::status_id_pending_payment
625
+	 *
626
+	 * @return        boolean
627
+	 */
628
+	public function is_pending_payment()
629
+	{
630
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
631
+	}
632
+
633
+
634
+	/**
635
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
636
+	 *
637
+	 * @return        boolean
638
+	 */
639
+	public function is_approved()
640
+	{
641
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
642
+	}
643
+
644
+
645
+	/**
646
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
647
+	 *
648
+	 * @return        boolean
649
+	 */
650
+	public function is_cancelled()
651
+	{
652
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
653
+	}
654
+
655
+
656
+	/**
657
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
658
+	 *
659
+	 * @return        boolean
660
+	 */
661
+	public function is_declined()
662
+	{
663
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
664
+	}
665
+
666
+
667
+	/**
668
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
669
+	 *    EEM_Registration::status_id_incomplete
670
+	 *
671
+	 * @return        boolean
672
+	 */
673
+	public function is_incomplete()
674
+	{
675
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
676
+	}
677
+
678
+
679
+	/**
680
+	 *        Set Registration Date
681
+	 *
682
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
683
+	 *                                                 Date
684
+	 * @throws EE_Error
685
+	 * @throws RuntimeException
686
+	 */
687
+	public function set_reg_date($REG_date = false)
688
+	{
689
+		$this->set('REG_date', $REG_date);
690
+	}
691
+
692
+
693
+	/**
694
+	 *    Set final price owing for this registration after all ticket/price modifications
695
+	 *
696
+	 * @access    public
697
+	 * @param    float $REG_final_price
698
+	 * @throws EE_Error
699
+	 * @throws RuntimeException
700
+	 */
701
+	public function set_final_price($REG_final_price = 0.00)
702
+	{
703
+		$this->set('REG_final_price', $REG_final_price);
704
+	}
705
+
706
+
707
+	/**
708
+	 *    Set amount paid towards this registration's final price
709
+	 *
710
+	 * @access    public
711
+	 * @param    float $REG_paid
712
+	 * @throws EE_Error
713
+	 * @throws RuntimeException
714
+	 */
715
+	public function set_paid($REG_paid = 0.00)
716
+	{
717
+		$this->set('REG_paid', $REG_paid);
718
+	}
719
+
720
+
721
+	/**
722
+	 *        Attendee Is Going
723
+	 *
724
+	 * @param        boolean $REG_att_is_going Attendee Is Going
725
+	 * @throws EE_Error
726
+	 * @throws RuntimeException
727
+	 */
728
+	public function set_att_is_going($REG_att_is_going = false)
729
+	{
730
+		$this->set('REG_att_is_going', $REG_att_is_going);
731
+	}
732
+
733
+
734
+	/**
735
+	 * Gets the related attendee
736
+	 *
737
+	 * @return EE_Attendee
738
+	 * @throws EE_Error
739
+	 */
740
+	public function attendee()
741
+	{
742
+		return $this->get_first_related('Attendee');
743
+	}
744
+
745
+
746
+	/**
747
+	 *        get Event ID
748
+	 */
749
+	public function event_ID()
750
+	{
751
+		return $this->get('EVT_ID');
752
+	}
753
+
754
+
755
+	/**
756
+	 *        get Event ID
757
+	 */
758
+	public function event_name()
759
+	{
760
+		$event = $this->event_obj();
761
+		if ($event) {
762
+			return $event->name();
763
+		} else {
764
+			return null;
765
+		}
766
+	}
767
+
768
+
769
+	/**
770
+	 * Fetches the event this registration is for
771
+	 *
772
+	 * @return EE_Event
773
+	 * @throws EE_Error
774
+	 */
775
+	public function event_obj()
776
+	{
777
+		return $this->get_first_related('Event');
778
+	}
779
+
780
+
781
+	/**
782
+	 *        get Attendee ID
783
+	 */
784
+	public function attendee_ID()
785
+	{
786
+		return $this->get('ATT_ID');
787
+	}
788
+
789
+
790
+	/**
791
+	 *        get PHP Session ID
792
+	 */
793
+	public function session_ID()
794
+	{
795
+		return $this->get('REG_session');
796
+	}
797
+
798
+
799
+	/**
800
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
801
+	 *
802
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
803
+	 * @return string
804
+	 */
805
+	public function receipt_url($messenger = 'html')
806
+	{
807
+
808
+		/**
809
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
810
+		 * already in use on old system.  If there is then we just return the standard url for it.
811
+		 *
812
+		 * @since 4.5.0
813
+		 */
814
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
815
+		$has_custom             = EEH_Template::locate_template(
816
+			$template_relative_path,
817
+			array(),
818
+			true,
819
+			true,
820
+			true
821
+		);
822
+
823
+		if ($has_custom) {
824
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
825
+		}
826
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
827
+	}
828
+
829
+
830
+	/**
831
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
832
+	 *
833
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
834
+	 * @return string
835
+	 * @throws EE_Error
836
+	 */
837
+	public function invoice_url($messenger = 'html')
838
+	{
839
+		/**
840
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
841
+		 * already in use on old system.  If there is then we just return the standard url for it.
842
+		 *
843
+		 * @since 4.5.0
844
+		 */
845
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
846
+		$has_custom             = EEH_Template::locate_template(
847
+			$template_relative_path,
848
+			array(),
849
+			true,
850
+			true,
851
+			true
852
+		);
853
+
854
+		if ($has_custom) {
855
+			if ($messenger == 'html') {
856
+				return $this->invoice_url('launch');
857
+			}
858
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
859
+
860
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
861
+			if ($messenger == 'html') {
862
+				$query_args['html'] = true;
863
+			}
864
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
865
+		}
866
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
867
+	}
868
+
869
+
870
+	/**
871
+	 * get Registration URL Link
872
+	 *
873
+	 * @access public
874
+	 * @return string
875
+	 * @throws EE_Error
876
+	 */
877
+	public function reg_url_link()
878
+	{
879
+		return (string) $this->get('REG_url_link');
880
+	}
881
+
882
+
883
+	/**
884
+	 * Echoes out invoice_url()
885
+	 *
886
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
887
+	 * @return void
888
+	 * @throws EE_Error
889
+	 */
890
+	public function e_invoice_url($type = 'launch')
891
+	{
892
+		echo $this->invoice_url($type);
893
+	}
894
+
895
+
896
+	/**
897
+	 * Echoes out payment_overview_url
898
+	 */
899
+	public function e_payment_overview_url()
900
+	{
901
+		echo $this->payment_overview_url();
902
+	}
903
+
904
+
905
+	/**
906
+	 * Gets the URL for the checkout payment options reg step
907
+	 * with this registration's REG_url_link added as a query parameter
908
+	 *
909
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
910
+	 *                            payment overview url.
911
+	 * @return string
912
+	 * @throws InvalidInterfaceException
913
+	 * @throws InvalidDataTypeException
914
+	 * @throws EE_Error
915
+	 * @throws InvalidArgumentException
916
+	 */
917
+	public function payment_overview_url($clear_session = false)
918
+	{
919
+		return add_query_arg(
920
+			(array) apply_filters(
921
+				'FHEE__EE_Registration__payment_overview_url__query_args',
922
+				array(
923
+					'e_reg_url_link' => $this->reg_url_link(),
924
+					'step'           => 'payment_options',
925
+					'revisit'        => true,
926
+					'clear_session'  => (bool) $clear_session,
927
+				),
928
+				$this
929
+			),
930
+			EE_Registry::instance()->CFG->core->reg_page_url()
931
+		);
932
+	}
933
+
934
+
935
+	/**
936
+	 * Gets the URL for the checkout attendee information reg step
937
+	 * with this registration's REG_url_link added as a query parameter
938
+	 *
939
+	 * @return string
940
+	 * @throws InvalidInterfaceException
941
+	 * @throws InvalidDataTypeException
942
+	 * @throws EE_Error
943
+	 * @throws InvalidArgumentException
944
+	 */
945
+	public function edit_attendee_information_url()
946
+	{
947
+		return add_query_arg(
948
+			(array) apply_filters(
949
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
950
+				array(
951
+					'e_reg_url_link' => $this->reg_url_link(),
952
+					'step'           => 'attendee_information',
953
+					'revisit'        => true,
954
+				),
955
+				$this
956
+			),
957
+			EE_Registry::instance()->CFG->core->reg_page_url()
958
+		);
959
+	}
960
+
961
+
962
+	/**
963
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
964
+	 *
965
+	 * @return string
966
+	 * @throws EE_Error
967
+	 */
968
+	public function get_admin_edit_url()
969
+	{
970
+		return EEH_URL::add_query_args_and_nonce(array(
971
+			'page'    => 'espresso_registrations',
972
+			'action'  => 'view_registration',
973
+			'_REG_ID' => $this->ID(),
974
+		), admin_url('admin.php'));
975
+	}
976
+
977
+
978
+	/**
979
+	 *    is_primary_registrant?
980
+	 */
981
+	public function is_primary_registrant()
982
+	{
983
+		return $this->get('REG_count') == 1 ? true : false;
984
+	}
985
+
986
+
987
+	/**
988
+	 * This returns the primary registration object for this registration group (which may be this object).
989
+	 *
990
+	 * @return EE_Registration
991
+	 * @throws EE_Error
992
+	 */
993
+	public function get_primary_registration()
994
+	{
995
+		if ($this->is_primary_registrant()) {
996
+			return $this;
997
+		}
998
+
999
+		//k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1000
+		/** @var EE_Registration $primary_registrant */
1001
+		$primary_registrant = EEM_Registration::instance()->get_one(array(
1002
+			array(
1003
+				'TXN_ID'    => $this->transaction_ID(),
1004
+				'REG_count' => 1,
1005
+			),
1006
+		));
1007
+		return $primary_registrant;
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 *        get  Attendee Number
1013
+	 *
1014
+	 * @access        public
1015
+	 */
1016
+	public function count()
1017
+	{
1018
+		return $this->get('REG_count');
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 *        get Group Size
1024
+	 */
1025
+	public function group_size()
1026
+	{
1027
+		return $this->get('REG_group_size');
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 *        get Registration Date
1033
+	 */
1034
+	public function date()
1035
+	{
1036
+		return $this->get('REG_date');
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 * gets a pretty date
1042
+	 *
1043
+	 * @param string $date_format
1044
+	 * @param string $time_format
1045
+	 * @return string
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function pretty_date($date_format = null, $time_format = null)
1049
+	{
1050
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1051
+	}
1052
+
1053
+
1054
+	/**
1055
+	 * final_price
1056
+	 * the registration's share of the transaction total, so that the
1057
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1058
+	 *
1059
+	 * @return float
1060
+	 * @throws EE_Error
1061
+	 */
1062
+	public function final_price()
1063
+	{
1064
+		return $this->get('REG_final_price');
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * pretty_final_price
1070
+	 *  final price as formatted string, with correct decimal places and currency symbol
1071
+	 *
1072
+	 * @return string
1073
+	 * @throws EE_Error
1074
+	 */
1075
+	public function pretty_final_price()
1076
+	{
1077
+		return $this->get_pretty('REG_final_price');
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * get paid (yeah)
1083
+	 *
1084
+	 * @return float
1085
+	 * @throws EE_Error
1086
+	 */
1087
+	public function paid()
1088
+	{
1089
+		return $this->get('REG_paid');
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * pretty_paid
1095
+	 *
1096
+	 * @return float
1097
+	 * @throws EE_Error
1098
+	 */
1099
+	public function pretty_paid()
1100
+	{
1101
+		return $this->get_pretty('REG_paid');
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * owes_monies_and_can_pay
1107
+	 * whether or not this registration has monies owing and it's' status allows payment
1108
+	 *
1109
+	 * @param array $requires_payment
1110
+	 * @return bool
1111
+	 * @throws EE_Error
1112
+	 */
1113
+	public function owes_monies_and_can_pay($requires_payment = array())
1114
+	{
1115
+		// these reg statuses require payment (if event is not free)
1116
+		$requires_payment = ! empty($requires_payment)
1117
+			? $requires_payment
1118
+			: EEM_Registration::reg_statuses_that_allow_payment();
1119
+		if (in_array($this->status_ID(), $requires_payment) &&
1120
+			$this->final_price() != 0 &&
1121
+			$this->final_price() != $this->paid()
1122
+		) {
1123
+			return true;
1124
+		} else {
1125
+			return false;
1126
+		}
1127
+	}
1128
+
1129
+
1130
+	/**
1131
+	 * Prints out the return value of $this->pretty_status()
1132
+	 *
1133
+	 * @param bool $show_icons
1134
+	 * @return void
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	public function e_pretty_status($show_icons = false)
1138
+	{
1139
+		echo $this->pretty_status($show_icons);
1140
+	}
1141
+
1142
+
1143
+	/**
1144
+	 * Returns a nice version of the status for displaying to customers
1145
+	 *
1146
+	 * @param bool $show_icons
1147
+	 * @return string
1148
+	 * @throws EE_Error
1149
+	 */
1150
+	public function pretty_status($show_icons = false)
1151
+	{
1152
+		$status = EEM_Status::instance()->localized_status(
1153
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1154
+			false,
1155
+			'sentence'
1156
+		);
1157
+		$icon   = '';
1158
+		switch ($this->status_ID()) {
1159
+			case EEM_Registration::status_id_approved:
1160
+				$icon = $show_icons
1161
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1162
+					: '';
1163
+				break;
1164
+			case EEM_Registration::status_id_pending_payment:
1165
+				$icon = $show_icons
1166
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1167
+					: '';
1168
+				break;
1169
+			case EEM_Registration::status_id_not_approved:
1170
+				$icon = $show_icons
1171
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1172
+					: '';
1173
+				break;
1174
+			case EEM_Registration::status_id_cancelled:
1175
+				$icon = $show_icons
1176
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1177
+					: '';
1178
+				break;
1179
+			case EEM_Registration::status_id_incomplete:
1180
+				$icon = $show_icons
1181
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1182
+					: '';
1183
+				break;
1184
+			case EEM_Registration::status_id_declined:
1185
+				$icon = $show_icons
1186
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1187
+					: '';
1188
+				break;
1189
+			case EEM_Registration::status_id_wait_list:
1190
+				$icon = $show_icons
1191
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1192
+					: '';
1193
+				break;
1194
+		}
1195
+		return $icon . $status[$this->status_ID()];
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 *        get Attendee Is Going
1201
+	 */
1202
+	public function att_is_going()
1203
+	{
1204
+		return $this->get('REG_att_is_going');
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * Gets related answers
1210
+	 *
1211
+	 * @param array $query_params like EEM_Base::get_all
1212
+	 * @return EE_Answer[]
1213
+	 * @throws EE_Error
1214
+	 */
1215
+	public function answers($query_params = null)
1216
+	{
1217
+		return $this->get_many_related('Answer', $query_params);
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * Gets the registration's answer value to the specified question
1223
+	 * (either the question's ID or a question object)
1224
+	 *
1225
+	 * @param EE_Question|int $question
1226
+	 * @param bool            $pretty_value
1227
+	 * @return array|string if pretty_value= true, the result will always be a string
1228
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1229
+	 * will convert it into some kind of string)
1230
+	 * @throws EE_Error
1231
+	 */
1232
+	public function answer_value_to_question($question, $pretty_value = true)
1233
+	{
1234
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1235
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 * question_groups
1241
+	 * returns an array of EE_Question_Group objects for this registration
1242
+	 *
1243
+	 * @return EE_Question_Group[]
1244
+	 * @throws EE_Error
1245
+	 * @throws EntityNotFoundException
1246
+	 */
1247
+	public function question_groups()
1248
+	{
1249
+		$question_groups = array();
1250
+		if ($this->event() instanceof EE_Event) {
1251
+			$question_groups = $this->event()->question_groups(
1252
+				array(
1253
+					array(
1254
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1255
+					),
1256
+					'order_by' => array('QSG_order' => 'ASC'),
1257
+				)
1258
+			);
1259
+		}
1260
+		return $question_groups;
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * count_question_groups
1266
+	 * returns a count of the number of EE_Question_Group objects for this registration
1267
+	 *
1268
+	 * @return int
1269
+	 * @throws EE_Error
1270
+	 * @throws EntityNotFoundException
1271
+	 */
1272
+	public function count_question_groups()
1273
+	{
1274
+		$qg_count = 0;
1275
+		if ($this->event() instanceof EE_Event) {
1276
+			$qg_count = $this->event()->count_related(
1277
+				'Question_Group',
1278
+				array(
1279
+					array(
1280
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1281
+					),
1282
+				)
1283
+			);
1284
+		}
1285
+		return $qg_count;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * Returns the registration date in the 'standard' string format
1291
+	 * (function may be improved in the future to allow for different formats and timezones)
1292
+	 *
1293
+	 * @return string
1294
+	 * @throws EE_Error
1295
+	 */
1296
+	public function reg_date()
1297
+	{
1298
+		return $this->get_datetime('REG_date');
1299
+	}
1300
+
1301
+
1302
+	/**
1303
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1304
+	 * the ticket this registration purchased, or the datetime they have registered
1305
+	 * to attend)
1306
+	 *
1307
+	 * @return EE_Datetime_Ticket
1308
+	 * @throws EE_Error
1309
+	 */
1310
+	public function datetime_ticket()
1311
+	{
1312
+		return $this->get_first_related('Datetime_Ticket');
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * Sets the registration's datetime_ticket.
1318
+	 *
1319
+	 * @param EE_Datetime_Ticket $datetime_ticket
1320
+	 * @return EE_Datetime_Ticket
1321
+	 * @throws EE_Error
1322
+	 */
1323
+	public function set_datetime_ticket($datetime_ticket)
1324
+	{
1325
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1326
+	}
1327
+
1328
+	/**
1329
+	 * Gets deleted
1330
+	 *
1331
+	 * @return bool
1332
+	 * @throws EE_Error
1333
+	 */
1334
+	public function deleted()
1335
+	{
1336
+		return $this->get('REG_deleted');
1337
+	}
1338
+
1339
+	/**
1340
+	 * Sets deleted
1341
+	 *
1342
+	 * @param boolean $deleted
1343
+	 * @return bool
1344
+	 * @throws EE_Error
1345
+	 * @throws RuntimeException
1346
+	 */
1347
+	public function set_deleted($deleted)
1348
+	{
1349
+		if ($deleted) {
1350
+			$this->delete();
1351
+		} else {
1352
+			$this->restore();
1353
+		}
1354
+	}
1355
+
1356
+
1357
+	/**
1358
+	 * Get the status object of this object
1359
+	 *
1360
+	 * @return EE_Status
1361
+	 * @throws EE_Error
1362
+	 */
1363
+	public function status_obj()
1364
+	{
1365
+		return $this->get_first_related('Status');
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Returns the number of times this registration has checked into any of the datetimes
1371
+	 * its available for
1372
+	 *
1373
+	 * @return int
1374
+	 * @throws EE_Error
1375
+	 */
1376
+	public function count_checkins()
1377
+	{
1378
+		return $this->get_model()->count_related($this, 'Checkin');
1379
+	}
1380
+
1381
+
1382
+	/**
1383
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1384
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1385
+	 *
1386
+	 * @return int
1387
+	 * @throws EE_Error
1388
+	 */
1389
+	public function count_checkins_not_checkedout()
1390
+	{
1391
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1397
+	 *
1398
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1399
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1400
+	 *                                          consider registration status as well as datetime access.
1401
+	 * @return bool
1402
+	 * @throws EE_Error
1403
+	 */
1404
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1405
+	{
1406
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1407
+
1408
+		//first check registration status
1409
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1410
+			return false;
1411
+		}
1412
+		//is there a datetime ticket that matches this dtt_ID?
1413
+		if (! (EEM_Datetime_Ticket::instance()->exists(array(
1414
+			array(
1415
+				'TKT_ID' => $this->get('TKT_ID'),
1416
+				'DTT_ID' => $DTT_ID,
1417
+			),
1418
+		)))
1419
+		) {
1420
+			return false;
1421
+		}
1422
+
1423
+		//final check is against TKT_uses
1424
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1425
+	}
1426
+
1427
+
1428
+	/**
1429
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1430
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1431
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1432
+	 * then return false.  Otherwise return true.
1433
+	 *
1434
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1435
+	 * @return bool true means can checkin.  false means cannot checkin.
1436
+	 * @throws EE_Error
1437
+	 */
1438
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1439
+	{
1440
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1441
+
1442
+		if (! $DTT_ID) {
1443
+			return false;
1444
+		}
1445
+
1446
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1447
+
1448
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1449
+		// check-in or not.
1450
+		if (! $max_uses || $max_uses === EE_INF) {
1451
+			return true;
1452
+		}
1453
+
1454
+		//does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1455
+		//go ahead and toggle.
1456
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1457
+			return true;
1458
+		}
1459
+
1460
+		//made it here so the last check is whether the number of checkins per unique datetime on this registration
1461
+		//disallows further check-ins.
1462
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1463
+			array(
1464
+				'REG_ID' => $this->ID(),
1465
+				'CHK_in' => true,
1466
+			),
1467
+		), 'DTT_ID', true);
1468
+		// checkins have already reached their max number of uses
1469
+		// so registrant can NOT checkin
1470
+		if ($count_unique_dtt_checkins >= $max_uses) {
1471
+			EE_Error::add_error(
1472
+				esc_html__(
1473
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1474
+					'event_espresso'
1475
+				),
1476
+				__FILE__,
1477
+				__FUNCTION__,
1478
+				__LINE__
1479
+			);
1480
+			return false;
1481
+		}
1482
+		return true;
1483
+	}
1484
+
1485
+
1486
+	/**
1487
+	 * toggle Check-in status for this registration
1488
+	 * Check-ins are toggled in the following order:
1489
+	 * never checked in -> checked in
1490
+	 * checked in -> checked out
1491
+	 * checked out -> checked in
1492
+	 *
1493
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1494
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1495
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1496
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1497
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1498
+	 * @throws EE_Error
1499
+	 */
1500
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1501
+	{
1502
+		if (empty($DTT_ID)) {
1503
+			$datetime = $this->get_latest_related_datetime();
1504
+			$DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1505
+			// verify the registration can checkin for the given DTT_ID
1506
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1507
+			EE_Error::add_error(
1508
+				sprintf(
1509
+					esc_html__(
1510
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1511
+						'event_espresso'
1512
+					),
1513
+					$this->ID(),
1514
+					$DTT_ID
1515
+				),
1516
+				__FILE__,
1517
+				__FUNCTION__,
1518
+				__LINE__
1519
+			);
1520
+			return false;
1521
+		}
1522
+		$status_paths = array(
1523
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1524
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1525
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1526
+		);
1527
+		//start by getting the current status so we know what status we'll be changing to.
1528
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1529
+		$status_to  = $status_paths[$cur_status];
1530
+		// database only records true for checked IN or false for checked OUT
1531
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1532
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1533
+		// add relation - note Check-ins are always creating new rows
1534
+		// because we are keeping track of Check-ins over time.
1535
+		// Eventually we'll probably want to show a list table
1536
+		// for the individual Check-ins so that they can be managed.
1537
+		$checkin = EE_Checkin::new_instance(array(
1538
+			'REG_ID' => $this->ID(),
1539
+			'DTT_ID' => $DTT_ID,
1540
+			'CHK_in' => $new_status,
1541
+		));
1542
+		// if the record could not be saved then return false
1543
+		if ($checkin->save() === 0) {
1544
+			if (WP_DEBUG) {
1545
+				global $wpdb;
1546
+				$error = sprintf(
1547
+					esc_html__(
1548
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1549
+						'event_espresso'
1550
+					),
1551
+					'<br />',
1552
+					$wpdb->last_error
1553
+				);
1554
+			} else {
1555
+				$error = esc_html__(
1556
+					'Registration check in update failed because of an unknown database error',
1557
+					'event_espresso'
1558
+				);
1559
+			}
1560
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1561
+			return false;
1562
+		}
1563
+		return $status_to;
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1569
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1570
+	 *
1571
+	 * @return EE_Datetime|null
1572
+	 * @throws EE_Error
1573
+	 */
1574
+	public function get_latest_related_datetime()
1575
+	{
1576
+		return EEM_Datetime::instance()->get_one(
1577
+			array(
1578
+				array(
1579
+					'Ticket.Registration.REG_ID' => $this->ID(),
1580
+				),
1581
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1582
+			)
1583
+		);
1584
+	}
1585
+
1586
+
1587
+	/**
1588
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1589
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1590
+	 *
1591
+	 * @throws EE_Error
1592
+	 */
1593
+	public function get_earliest_related_datetime()
1594
+	{
1595
+		return EEM_Datetime::instance()->get_one(
1596
+			array(
1597
+				array(
1598
+					'Ticket.Registration.REG_ID' => $this->ID(),
1599
+				),
1600
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1601
+			)
1602
+		);
1603
+	}
1604
+
1605
+
1606
+	/**
1607
+	 * This method simply returns the check-in status for this registration and the given datetime.
1608
+	 * If neither the datetime nor the checkin values are provided as arguments,
1609
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1610
+	 *
1611
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1612
+	 *                            (if empty we'll get the primary datetime for
1613
+	 *                            this registration (via event) and use it's ID);
1614
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1615
+	 *
1616
+	 * @return int                Integer representing Check-in status.
1617
+	 * @throws EE_Error
1618
+	 */
1619
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1620
+	{
1621
+		$checkin_query_params = array(
1622
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1623
+		);
1624
+
1625
+		if ($DTT_ID > 0) {
1626
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1627
+		}
1628
+
1629
+		//get checkin object (if exists)
1630
+		$checkin = $checkin instanceof EE_Checkin
1631
+			? $checkin
1632
+			: $this->get_first_related('Checkin', $checkin_query_params);
1633
+		if ($checkin instanceof EE_Checkin) {
1634
+			if ($checkin->get('CHK_in')) {
1635
+				return EE_Checkin::status_checked_in; //checked in
1636
+			}
1637
+			return EE_Checkin::status_checked_out; //had checked in but is now checked out.
1638
+		}
1639
+		return EE_Checkin::status_checked_never; //never been checked in
1640
+	}
1641
+
1642
+
1643
+	/**
1644
+	 * This method returns a localized message for the toggled Check-in message.
1645
+	 *
1646
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1647
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1648
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1649
+	 *                     message can be customized with the attendee name.
1650
+	 * @return string internationalized message
1651
+	 * @throws EE_Error
1652
+	 */
1653
+	public function get_checkin_msg($DTT_ID, $error = false)
1654
+	{
1655
+		//let's get the attendee first so we can include the name of the attendee
1656
+		$attendee = $this->get_first_related('Attendee');
1657
+		if ($attendee instanceof EE_Attendee) {
1658
+			if ($error) {
1659
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1660
+			}
1661
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1662
+			//what is the status message going to be?
1663
+			switch ($cur_status) {
1664
+				case EE_Checkin::status_checked_never:
1665
+					return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1666
+						$attendee->full_name());
1667
+					break;
1668
+				case EE_Checkin::status_checked_in:
1669
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1670
+					break;
1671
+				case EE_Checkin::status_checked_out:
1672
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1673
+					break;
1674
+			}
1675
+		}
1676
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1677
+	}
1678
+
1679
+
1680
+	/**
1681
+	 * Returns the related EE_Transaction to this registration
1682
+	 *
1683
+	 * @return EE_Transaction
1684
+	 * @throws EE_Error
1685
+	 * @throws EntityNotFoundException
1686
+	 */
1687
+	public function transaction()
1688
+	{
1689
+		$transaction = $this->get_first_related('Transaction');
1690
+		if (! $transaction instanceof \EE_Transaction) {
1691
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1692
+		}
1693
+		return $transaction;
1694
+	}
1695
+
1696
+
1697
+	/**
1698
+	 *        get Registration Code
1699
+	 */
1700
+	public function reg_code()
1701
+	{
1702
+		return $this->get('REG_code');
1703
+	}
1704
+
1705
+
1706
+	/**
1707
+	 *        get Transaction ID
1708
+	 */
1709
+	public function transaction_ID()
1710
+	{
1711
+		return $this->get('TXN_ID');
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * @return int
1717
+	 * @throws EE_Error
1718
+	 */
1719
+	public function ticket_ID()
1720
+	{
1721
+		return $this->get('TKT_ID');
1722
+	}
1723
+
1724
+
1725
+	/**
1726
+	 *        Set Registration Code
1727
+	 *
1728
+	 * @access    public
1729
+	 * @param    string  $REG_code Registration Code
1730
+	 * @param    boolean $use_default
1731
+	 * @throws EE_Error
1732
+	 */
1733
+	public function set_reg_code($REG_code, $use_default = false)
1734
+	{
1735
+		if (empty($REG_code)) {
1736
+			EE_Error::add_error(
1737
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1738
+				__FILE__,
1739
+				__FUNCTION__,
1740
+				__LINE__
1741
+			);
1742
+			return;
1743
+		}
1744
+		if (! $this->reg_code()) {
1745
+			parent::set('REG_code', $REG_code, $use_default);
1746
+		} else {
1747
+			EE_Error::doing_it_wrong(
1748
+				__CLASS__ . '::' . __FUNCTION__,
1749
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1750
+				'4.6.0'
1751
+			);
1752
+		}
1753
+	}
1754
+
1755
+
1756
+	/**
1757
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1758
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1759
+	 *    $registration->transaction()->registrations();
1760
+	 *
1761
+	 * @since 4.5.0
1762
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1763
+	 * @throws EE_Error
1764
+	 */
1765
+	public function get_all_other_registrations_in_group()
1766
+	{
1767
+		if ($this->group_size() < 2) {
1768
+			return array();
1769
+		}
1770
+
1771
+		$query[0] = array(
1772
+			'TXN_ID' => $this->transaction_ID(),
1773
+			'REG_ID' => array('!=', $this->ID()),
1774
+			'TKT_ID' => $this->ticket_ID(),
1775
+		);
1776
+		/** @var EE_Registration[] $registrations */
1777
+		$registrations = $this->get_model()->get_all($query);
1778
+		return $registrations;
1779
+	}
1780
+
1781
+	/**
1782
+	 * Return the link to the admin details for the object.
1783
+	 *
1784
+	 * @return string
1785
+	 * @throws EE_Error
1786
+	 */
1787
+	public function get_admin_details_link()
1788
+	{
1789
+		EE_Registry::instance()->load_helper('URL');
1790
+		return EEH_URL::add_query_args_and_nonce(
1791
+			array(
1792
+				'page'    => 'espresso_registrations',
1793
+				'action'  => 'view_registration',
1794
+				'_REG_ID' => $this->ID(),
1795
+			),
1796
+			admin_url('admin.php')
1797
+		);
1798
+	}
1799
+
1800
+	/**
1801
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1802
+	 *
1803
+	 * @return string
1804
+	 * @throws EE_Error
1805
+	 */
1806
+	public function get_admin_edit_link()
1807
+	{
1808
+		return $this->get_admin_details_link();
1809
+	}
1810
+
1811
+	/**
1812
+	 * Returns the link to a settings page for the object.
1813
+	 *
1814
+	 * @return string
1815
+	 * @throws EE_Error
1816
+	 */
1817
+	public function get_admin_settings_link()
1818
+	{
1819
+		return $this->get_admin_details_link();
1820
+	}
1821
+
1822
+	/**
1823
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1824
+	 *
1825
+	 * @return string
1826
+	 */
1827
+	public function get_admin_overview_link()
1828
+	{
1829
+		EE_Registry::instance()->load_helper('URL');
1830
+		return EEH_URL::add_query_args_and_nonce(
1831
+			array(
1832
+				'page' => 'espresso_registrations',
1833
+			),
1834
+			admin_url('admin.php')
1835
+		);
1836
+	}
1837
+
1838
+
1839
+	/**
1840
+	 * @param array $query_params
1841
+	 *
1842
+	 * @return \EE_Registration[]
1843
+	 * @throws EE_Error
1844
+	 */
1845
+	public function payments($query_params = array())
1846
+	{
1847
+		return $this->get_many_related('Payment', $query_params);
1848
+	}
1849
+
1850
+
1851
+	/**
1852
+	 * @param array $query_params
1853
+	 *
1854
+	 * @return \EE_Registration_Payment[]
1855
+	 * @throws EE_Error
1856
+	 */
1857
+	public function registration_payments($query_params = array())
1858
+	{
1859
+		return $this->get_many_related('Registration_Payment', $query_params);
1860
+	}
1861
+
1862
+
1863
+	/**
1864
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1865
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1866
+	 *
1867
+	 * @return EE_Payment_Method|null
1868
+	 */
1869
+	public function payment_method()
1870
+	{
1871
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1872
+	}
1873
+
1874
+
1875
+	/**
1876
+	 * @return \EE_Line_Item
1877
+	 * @throws EntityNotFoundException
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function ticket_line_item()
1881
+	{
1882
+		$ticket            = $this->ticket();
1883
+		$transaction       = $this->transaction();
1884
+		$line_item         = null;
1885
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1886
+			$transaction->total_line_item(),
1887
+			'Ticket',
1888
+			array($ticket->ID())
1889
+		);
1890
+		foreach ($ticket_line_items as $ticket_line_item) {
1891
+			if (
1892
+				$ticket_line_item instanceof \EE_Line_Item
1893
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1894
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1895
+			) {
1896
+				$line_item = $ticket_line_item;
1897
+				break;
1898
+			}
1899
+		}
1900
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1901
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1902
+		}
1903
+		return $line_item;
1904
+	}
1905
+
1906
+
1907
+	/**
1908
+	 * Soft Deletes this model object.
1909
+	 *
1910
+	 * @return boolean | int
1911
+	 * @throws RuntimeException
1912
+	 * @throws EE_Error
1913
+	 */
1914
+	public function delete()
1915
+	{
1916
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1917
+			$this->set_status(EEM_Registration::status_id_cancelled);
1918
+		}
1919
+		return parent::delete();
1920
+	}
1921
+
1922
+
1923
+	/**
1924
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1925
+	 *
1926
+	 * @throws EE_Error
1927
+	 * @throws RuntimeException
1928
+	 */
1929
+	public function restore()
1930
+	{
1931
+		$previous_status = $this->get_extra_meta(
1932
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1933
+			true,
1934
+			EEM_Registration::status_id_cancelled
1935
+		);
1936
+		if ($previous_status) {
1937
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1938
+			$this->set_status($previous_status);
1939
+		}
1940
+		return parent::restore();
1941
+	}
1942
+
1943
+
1944
+	/**
1945
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1946
+	 *
1947
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1948
+	 *                                           depending on whether the reg status changes to or from "Approved"
1949
+	 * @return boolean whether the Registration status was updated
1950
+	 * @throws EE_Error
1951
+	 * @throws RuntimeException
1952
+	 */
1953
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1954
+	{
1955
+		$paid = $this->paid();
1956
+		$price = $this->final_price();
1957
+		switch(true) {
1958
+			// overpaid or paid
1959
+			case EEH_Money::compare_floats($paid, $price, '>'):
1960
+			case EEH_Money::compare_floats($paid, $price):
1961
+				$new_status = EEM_Registration::status_id_approved;
1962
+				break;
1963
+			//  underpaid
1964
+			case EEH_Money::compare_floats($paid, $price, '<'):
1965
+				$new_status = EEM_Registration::status_id_pending_payment;
1966
+				break;
1967
+			// uhhh Houston...
1968
+			default:
1969
+				throw new RuntimeException(
1970
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1971
+				);
1972
+		}
1973
+		if ($new_status !== $this->status_ID()) {
1974
+			if ($trigger_set_status_logic) {
1975
+				return $this->set_status($new_status);
1976
+			}
1977
+			parent::set('STS_ID', $new_status);
1978
+			return true;
1979
+		}
1980
+		return false;
1981
+	}
1982
+
1983
+
1984
+	/*************************** DEPRECATED ***************************/
1985
+
1986
+
1987
+	/**
1988
+	 * @deprecated
1989
+	 * @since     4.7.0
1990
+	 * @access    public
1991
+	 */
1992
+	public function price_paid()
1993
+	{
1994
+		EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1995
+			esc_html__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1996
+			'4.7.0');
1997
+		return $this->final_price();
1998
+	}
1999
+
2000
+
2001
+	/**
2002
+	 * @deprecated
2003
+	 * @since     4.7.0
2004
+	 * @access    public
2005
+	 * @param    float $REG_final_price
2006
+	 * @throws EE_Error
2007
+	 * @throws RuntimeException
2008
+	 */
2009
+	public function set_price_paid($REG_final_price = 0.00)
2010
+	{
2011
+		EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
2012
+			esc_html__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
2013
+			'4.7.0');
2014
+		$this->set_final_price($REG_final_price);
2015
+	}
2016
+
2017
+
2018
+	/**
2019
+	 * @deprecated
2020
+	 * @since 4.7.0
2021
+	 * @return string
2022
+	 * @throws EE_Error
2023
+	 */
2024
+	public function pretty_price_paid()
2025
+	{
2026
+		EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
2027
+			esc_html__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2028
+				'event_espresso'), '4.7.0');
2029
+		return $this->pretty_final_price();
2030
+	}
2031
+
2032
+
2033
+	/**
2034
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2035
+	 *
2036
+	 * @deprecated 4.9.17
2037
+	 * @return EE_Datetime
2038
+	 * @throws EE_Error
2039
+	 * @throws EntityNotFoundException
2040
+	 */
2041
+	public function get_related_primary_datetime()
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			__METHOD__,
2045
+			esc_html__(
2046
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2047
+				'event_espresso'
2048
+			),
2049
+			'4.9.17',
2050
+			'5.0.0'
2051
+		);
2052
+		return $this->event()->primary_datetime();
2053
+	}
2054 2054
 
2055 2055
 
2056 2056
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
     {
122 122
         switch ($field_name) {
123 123
             case 'REG_code':
124
-                if (! empty($field_value) && $this->reg_code() === null) {
124
+                if ( ! empty($field_value) && $this->reg_code() === null) {
125 125
                     $this->set_reg_code($field_value, $use_default);
126 126
                 }
127 127
                 break;
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
             // update status
183 183
             parent::set('STS_ID', $new_STS_ID, $use_default);
184 184
             $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID, $context);
185
-            if($this->statusChangeUpdatesTransaction($context)) {
185
+            if ($this->statusChangeUpdatesTransaction($context)) {
186 186
                 $this->updateTransactionAfterStatusChange();
187 187
             }
188 188
             do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
     public function event()
391 391
     {
392 392
         $event = $this->get_first_related('Event');
393
-        if (! $event instanceof \EE_Event) {
393
+        if ( ! $event instanceof \EE_Event) {
394 394
             throw new EntityNotFoundException('Event ID', $this->event_ID());
395 395
         }
396 396
         return $event;
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
     {
434 434
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
435 435
         // so stop tracking that this reg has a ticket reserved
436
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
436
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
437 437
         $ticket = $this->ticket();
438 438
         $ticket->increase_sold();
439 439
         $ticket->save();
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
                 && $update_ticket
491 491
             ) {
492 492
                 $ticket = $this->ticket();
493
-                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
493
+                $ticket->increase_reserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
494 494
                 $ticket->save();
495 495
             }
496 496
         }
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
                 && $update_ticket
523 523
             ) {
524 524
                 $ticket = $this->ticket();
525
-                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
525
+                $ticket->decrease_reserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
526 526
                 $ticket->save();
527 527
             }
528 528
         }
@@ -1154,7 +1154,7 @@  discard block
 block discarded – undo
1154 1154
             false,
1155 1155
             'sentence'
1156 1156
         );
1157
-        $icon   = '';
1157
+        $icon = '';
1158 1158
         switch ($this->status_ID()) {
1159 1159
             case EEM_Registration::status_id_approved:
1160 1160
                 $icon = $show_icons
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
                     : '';
1193 1193
                 break;
1194 1194
         }
1195
-        return $icon . $status[$this->status_ID()];
1195
+        return $icon.$status[$this->status_ID()];
1196 1196
     }
1197 1197
 
1198 1198
 
@@ -1410,7 +1410,7 @@  discard block
 block discarded – undo
1410 1410
             return false;
1411 1411
         }
1412 1412
         //is there a datetime ticket that matches this dtt_ID?
1413
-        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1413
+        if ( ! (EEM_Datetime_Ticket::instance()->exists(array(
1414 1414
             array(
1415 1415
                 'TKT_ID' => $this->get('TKT_ID'),
1416 1416
                 'DTT_ID' => $DTT_ID,
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
     {
1440 1440
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1441 1441
 
1442
-        if (! $DTT_ID) {
1442
+        if ( ! $DTT_ID) {
1443 1443
             return false;
1444 1444
         }
1445 1445
 
@@ -1447,7 +1447,7 @@  discard block
 block discarded – undo
1447 1447
 
1448 1448
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1449 1449
         // check-in or not.
1450
-        if (! $max_uses || $max_uses === EE_INF) {
1450
+        if ( ! $max_uses || $max_uses === EE_INF) {
1451 1451
             return true;
1452 1452
         }
1453 1453
 
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
             $datetime = $this->get_latest_related_datetime();
1504 1504
             $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1505 1505
             // verify the registration can checkin for the given DTT_ID
1506
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1506
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1507 1507
             EE_Error::add_error(
1508 1508
                 sprintf(
1509 1509
                     esc_html__(
@@ -1687,7 +1687,7 @@  discard block
 block discarded – undo
1687 1687
     public function transaction()
1688 1688
     {
1689 1689
         $transaction = $this->get_first_related('Transaction');
1690
-        if (! $transaction instanceof \EE_Transaction) {
1690
+        if ( ! $transaction instanceof \EE_Transaction) {
1691 1691
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1692 1692
         }
1693 1693
         return $transaction;
@@ -1741,11 +1741,11 @@  discard block
 block discarded – undo
1741 1741
             );
1742 1742
             return;
1743 1743
         }
1744
-        if (! $this->reg_code()) {
1744
+        if ( ! $this->reg_code()) {
1745 1745
             parent::set('REG_code', $REG_code, $use_default);
1746 1746
         } else {
1747 1747
             EE_Error::doing_it_wrong(
1748
-                __CLASS__ . '::' . __FUNCTION__,
1748
+                __CLASS__.'::'.__FUNCTION__,
1749 1749
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1750 1750
                 '4.6.0'
1751 1751
             );
@@ -1897,7 +1897,7 @@  discard block
 block discarded – undo
1897 1897
                 break;
1898 1898
             }
1899 1899
         }
1900
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1900
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1901 1901
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1902 1902
         }
1903 1903
         return $line_item;
@@ -1954,7 +1954,7 @@  discard block
 block discarded – undo
1954 1954
     {
1955 1955
         $paid = $this->paid();
1956 1956
         $price = $this->final_price();
1957
-        switch(true) {
1957
+        switch (true) {
1958 1958
             // overpaid or paid
1959 1959
             case EEH_Money::compare_floats($paid, $price, '>'):
1960 1960
             case EEH_Money::compare_floats($paid, $price):
Please login to merge, or discard this patch.
core/services/assets/Registry.php 2 patches
Indentation   +691 added lines, -691 removed lines patch added patch discarded remove patch
@@ -26,702 +26,702 @@
 block discarded – undo
26 26
 class Registry
27 27
 {
28 28
 
29
-    const ASSET_TYPE_CSS = 'css';
30
-    const ASSET_TYPE_JS = 'js';
31
-    const ASSET_NAMESPACE = 'core';
32
-
33
-    /**
34
-     * @var EE_Template_Config $template_config
35
-     */
36
-    protected $template_config;
37
-
38
-    /**
39
-     * @var EE_Currency_Config $currency_config
40
-     */
41
-    protected $currency_config;
42
-
43
-    /**
44
-     * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
45
-     *
46
-     * @var array
47
-     */
48
-    protected $jsdata = array();
49
-
50
-
51
-    /**
52
-     * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
53
-     * page source.
54
-     * @var array
55
-     */
56
-    protected $script_handles_with_data = array();
57
-
58
-
59
-    /**
60
-     * @var DomainInterface
61
-     */
62
-    protected $domain;
63
-
64
-
65
-    /**
66
-     * @var I18nRegistry
67
-     */
68
-    private $i18n_registry;
69
-
70
-
71
-
72
-    /**
73
-     * Holds the manifest data obtained from registered manifest files.
74
-     * Manifests are maps of asset chunk name to actual built asset file names.
75
-     * Shape of this array is:
76
-     *
77
-     * array(
78
-     *  'some_namespace_slug' => array(
79
-     *      'some_chunk_name' => array(
80
-     *          'js' => 'filename.js'
81
-     *          'css' => 'filename.js'
82
-     *      ),
83
-     *      'url_base' => 'https://baseurl.com/to/assets
84
-     *  )
85
-     * )
86
-     *
87
-     * @var array
88
-     */
89
-    private $manifest_data = array();
90
-
91
-
92
-    /**
93
-     * Registry constructor.
94
-     * Hooking into WP actions for script registry.
95
-     *
96
-     * @param EE_Template_Config $template_config
97
-     * @param EE_Currency_Config $currency_config
98
-     * @param I18nRegistry       $i18n_registry
99
-     * @param DomainInterface    $domain
100
-     * @throws InvalidArgumentException
101
-     * @throws InvalidFilePathException
102
-     */
103
-    public function __construct(
104
-        EE_Template_Config $template_config,
105
-        EE_Currency_Config $currency_config,
106
-        I18nRegistry $i18n_registry,
107
-        DomainInterface $domain
108
-    ) {
109
-        $this->template_config = $template_config;
110
-        $this->currency_config = $currency_config;
111
-        $this->domain = $domain;
112
-        $this->i18n_registry = $i18n_registry;
113
-        $this->registerManifestFile(
114
-            self::ASSET_NAMESPACE,
115
-            $this->domain->distributionAssetsUrl(),
116
-            $this->domain->distributionAssetsPath() . 'build-manifest.json'
117
-        );
118
-        add_action('wp_enqueue_scripts', array($this, 'scripts'), 1);
119
-        add_action('admin_enqueue_scripts', array($this, 'scripts'), 1);
120
-        add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 2);
121
-        add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 2);
122
-        add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
123
-        add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
124
-    }
125
-
126
-
127
-    /**
128
-     * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
129
-     * translation handling.
130
-     *
131
-     * @return I18nRegistry
132
-     */
133
-    public function getI18nRegistry()
134
-    {
135
-        return $this->i18n_registry;
136
-    }
137
-
138
-    /**
139
-     * Callback for the WP script actions.
140
-     * Used to register globally accessible core scripts.
141
-     * Also used to add the eejs.data object to the source for any js having eejs-core as a dependency.
142
-     *
143
-     */
144
-    public function scripts()
145
-    {
146
-        global $wp_version;
147
-        wp_register_script(
148
-            'ee-manifest',
149
-            $this->getJsUrl(self::ASSET_NAMESPACE, 'manifest'),
150
-            array(),
151
-            null,
152
-            true
153
-        );
154
-        wp_register_script(
155
-            'eejs-core',
156
-            $this->getJsUrl(self::ASSET_NAMESPACE, 'eejs'),
157
-            array('ee-manifest'),
158
-            null,
159
-            true
160
-        );
161
-        wp_register_script(
162
-            'ee-vendor-react',
163
-            $this->getJsUrl(self::ASSET_NAMESPACE, 'reactVendor'),
164
-            array('eejs-core'),
165
-            null,
166
-            true
167
-        );
168
-        //only run this if WordPress 4.4.0 > is in use.
169
-        if (version_compare($wp_version, '4.4.0', '>')) {
170
-            //js.api
171
-            wp_register_script(
172
-                'eejs-api',
173
-                EE_LIBRARIES_URL . 'rest_api/assets/js/eejs-api.min.js',
174
-                array('underscore', 'eejs-core'),
175
-                EVENT_ESPRESSO_VERSION,
176
-                true
177
-            );
178
-            $this->jsdata['eejs_api_nonce'] = wp_create_nonce('wp_rest');
179
-            $this->jsdata['paths'] = array('rest_route' => rest_url('ee/v4.8.36/'));
180
-        }
181
-        if (! is_admin()) {
182
-            $this->loadCoreCss();
183
-        }
184
-        $this->registerTranslationsForHandles(array('eejs-core'));
185
-        $this->loadCoreJs();
186
-        $this->loadJqueryValidate();
187
-        $this->loadAccountingJs();
188
-        $this->loadQtipJs();
189
-        $this->registerAdminAssets();
190
-    }
191
-
192
-
193
-
194
-    /**
195
-     * Call back for the script print in frontend and backend.
196
-     * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
197
-     *
198
-     * @since 4.9.31.rc.015
199
-     */
200
-    public function enqueueData()
201
-    {
202
-        $this->removeAlreadyRegisteredDataForScriptHandles();
203
-        wp_add_inline_script(
204
-            'eejs-core',
205
-            'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
206
-            'before'
207
-        );
208
-        wp_localize_script('espresso_core', 'eei18n', EE_Registry::$i18n_js_strings);
209
-        $this->localizeAccountingJs();
210
-        $this->addRegisteredScriptHandlesWithData('eejs-core');
211
-        $this->addRegisteredScriptHandlesWithData('espresso_core');
212
-    }
213
-
214
-
215
-
216
-    /**
217
-     * Used to add data to eejs.data object.
218
-     * Note:  Overriding existing data is not allowed.
219
-     * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
220
-     * If the data you add is something like this:
221
-     *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
222
-     * It will be exposed in the page source as:
223
-     *  eejs.data.my_plugin_data.foo == gar
224
-     *
225
-     * @param string       $key   Key used to access your data
226
-     * @param string|array $value Value to attach to key
227
-     * @throws InvalidArgumentException
228
-     */
229
-    public function addData($key, $value)
230
-    {
231
-        if ($this->verifyDataNotExisting($key)) {
232
-            $this->jsdata[$key] = $value;
233
-        }
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * Similar to addData except this allows for users to push values to an existing key where the values on key are
240
-     * elements in an array.
241
-     * When you use this method, the value you include will be appended to the end of an array on $key.
242
-     * So if the $key was 'test' and you added a value of 'my_data' then it would be represented in the javascript
243
-     * object like this, eejs.data.test = [ my_data,
244
-     * ]
245
-     * If there has already been a scalar value attached to the data object given key, then
246
-     * this will throw an exception.
247
-     *
248
-     * @param string       $key   Key to attach data to.
249
-     * @param string|array $value Value being registered.
250
-     * @throws InvalidArgumentException
251
-     */
252
-    public function pushData($key, $value)
253
-    {
254
-        if (isset($this->jsdata[$key])
255
-            && ! is_array($this->jsdata[$key])
256
-        ) {
257
-            throw new invalidArgumentException(
258
-                sprintf(
259
-                    __(
260
-                        'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
29
+	const ASSET_TYPE_CSS = 'css';
30
+	const ASSET_TYPE_JS = 'js';
31
+	const ASSET_NAMESPACE = 'core';
32
+
33
+	/**
34
+	 * @var EE_Template_Config $template_config
35
+	 */
36
+	protected $template_config;
37
+
38
+	/**
39
+	 * @var EE_Currency_Config $currency_config
40
+	 */
41
+	protected $currency_config;
42
+
43
+	/**
44
+	 * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
45
+	 *
46
+	 * @var array
47
+	 */
48
+	protected $jsdata = array();
49
+
50
+
51
+	/**
52
+	 * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
53
+	 * page source.
54
+	 * @var array
55
+	 */
56
+	protected $script_handles_with_data = array();
57
+
58
+
59
+	/**
60
+	 * @var DomainInterface
61
+	 */
62
+	protected $domain;
63
+
64
+
65
+	/**
66
+	 * @var I18nRegistry
67
+	 */
68
+	private $i18n_registry;
69
+
70
+
71
+
72
+	/**
73
+	 * Holds the manifest data obtained from registered manifest files.
74
+	 * Manifests are maps of asset chunk name to actual built asset file names.
75
+	 * Shape of this array is:
76
+	 *
77
+	 * array(
78
+	 *  'some_namespace_slug' => array(
79
+	 *      'some_chunk_name' => array(
80
+	 *          'js' => 'filename.js'
81
+	 *          'css' => 'filename.js'
82
+	 *      ),
83
+	 *      'url_base' => 'https://baseurl.com/to/assets
84
+	 *  )
85
+	 * )
86
+	 *
87
+	 * @var array
88
+	 */
89
+	private $manifest_data = array();
90
+
91
+
92
+	/**
93
+	 * Registry constructor.
94
+	 * Hooking into WP actions for script registry.
95
+	 *
96
+	 * @param EE_Template_Config $template_config
97
+	 * @param EE_Currency_Config $currency_config
98
+	 * @param I18nRegistry       $i18n_registry
99
+	 * @param DomainInterface    $domain
100
+	 * @throws InvalidArgumentException
101
+	 * @throws InvalidFilePathException
102
+	 */
103
+	public function __construct(
104
+		EE_Template_Config $template_config,
105
+		EE_Currency_Config $currency_config,
106
+		I18nRegistry $i18n_registry,
107
+		DomainInterface $domain
108
+	) {
109
+		$this->template_config = $template_config;
110
+		$this->currency_config = $currency_config;
111
+		$this->domain = $domain;
112
+		$this->i18n_registry = $i18n_registry;
113
+		$this->registerManifestFile(
114
+			self::ASSET_NAMESPACE,
115
+			$this->domain->distributionAssetsUrl(),
116
+			$this->domain->distributionAssetsPath() . 'build-manifest.json'
117
+		);
118
+		add_action('wp_enqueue_scripts', array($this, 'scripts'), 1);
119
+		add_action('admin_enqueue_scripts', array($this, 'scripts'), 1);
120
+		add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 2);
121
+		add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 2);
122
+		add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
123
+		add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
124
+	}
125
+
126
+
127
+	/**
128
+	 * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
129
+	 * translation handling.
130
+	 *
131
+	 * @return I18nRegistry
132
+	 */
133
+	public function getI18nRegistry()
134
+	{
135
+		return $this->i18n_registry;
136
+	}
137
+
138
+	/**
139
+	 * Callback for the WP script actions.
140
+	 * Used to register globally accessible core scripts.
141
+	 * Also used to add the eejs.data object to the source for any js having eejs-core as a dependency.
142
+	 *
143
+	 */
144
+	public function scripts()
145
+	{
146
+		global $wp_version;
147
+		wp_register_script(
148
+			'ee-manifest',
149
+			$this->getJsUrl(self::ASSET_NAMESPACE, 'manifest'),
150
+			array(),
151
+			null,
152
+			true
153
+		);
154
+		wp_register_script(
155
+			'eejs-core',
156
+			$this->getJsUrl(self::ASSET_NAMESPACE, 'eejs'),
157
+			array('ee-manifest'),
158
+			null,
159
+			true
160
+		);
161
+		wp_register_script(
162
+			'ee-vendor-react',
163
+			$this->getJsUrl(self::ASSET_NAMESPACE, 'reactVendor'),
164
+			array('eejs-core'),
165
+			null,
166
+			true
167
+		);
168
+		//only run this if WordPress 4.4.0 > is in use.
169
+		if (version_compare($wp_version, '4.4.0', '>')) {
170
+			//js.api
171
+			wp_register_script(
172
+				'eejs-api',
173
+				EE_LIBRARIES_URL . 'rest_api/assets/js/eejs-api.min.js',
174
+				array('underscore', 'eejs-core'),
175
+				EVENT_ESPRESSO_VERSION,
176
+				true
177
+			);
178
+			$this->jsdata['eejs_api_nonce'] = wp_create_nonce('wp_rest');
179
+			$this->jsdata['paths'] = array('rest_route' => rest_url('ee/v4.8.36/'));
180
+		}
181
+		if (! is_admin()) {
182
+			$this->loadCoreCss();
183
+		}
184
+		$this->registerTranslationsForHandles(array('eejs-core'));
185
+		$this->loadCoreJs();
186
+		$this->loadJqueryValidate();
187
+		$this->loadAccountingJs();
188
+		$this->loadQtipJs();
189
+		$this->registerAdminAssets();
190
+	}
191
+
192
+
193
+
194
+	/**
195
+	 * Call back for the script print in frontend and backend.
196
+	 * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
197
+	 *
198
+	 * @since 4.9.31.rc.015
199
+	 */
200
+	public function enqueueData()
201
+	{
202
+		$this->removeAlreadyRegisteredDataForScriptHandles();
203
+		wp_add_inline_script(
204
+			'eejs-core',
205
+			'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
206
+			'before'
207
+		);
208
+		wp_localize_script('espresso_core', 'eei18n', EE_Registry::$i18n_js_strings);
209
+		$this->localizeAccountingJs();
210
+		$this->addRegisteredScriptHandlesWithData('eejs-core');
211
+		$this->addRegisteredScriptHandlesWithData('espresso_core');
212
+	}
213
+
214
+
215
+
216
+	/**
217
+	 * Used to add data to eejs.data object.
218
+	 * Note:  Overriding existing data is not allowed.
219
+	 * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
220
+	 * If the data you add is something like this:
221
+	 *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
222
+	 * It will be exposed in the page source as:
223
+	 *  eejs.data.my_plugin_data.foo == gar
224
+	 *
225
+	 * @param string       $key   Key used to access your data
226
+	 * @param string|array $value Value to attach to key
227
+	 * @throws InvalidArgumentException
228
+	 */
229
+	public function addData($key, $value)
230
+	{
231
+		if ($this->verifyDataNotExisting($key)) {
232
+			$this->jsdata[$key] = $value;
233
+		}
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * Similar to addData except this allows for users to push values to an existing key where the values on key are
240
+	 * elements in an array.
241
+	 * When you use this method, the value you include will be appended to the end of an array on $key.
242
+	 * So if the $key was 'test' and you added a value of 'my_data' then it would be represented in the javascript
243
+	 * object like this, eejs.data.test = [ my_data,
244
+	 * ]
245
+	 * If there has already been a scalar value attached to the data object given key, then
246
+	 * this will throw an exception.
247
+	 *
248
+	 * @param string       $key   Key to attach data to.
249
+	 * @param string|array $value Value being registered.
250
+	 * @throws InvalidArgumentException
251
+	 */
252
+	public function pushData($key, $value)
253
+	{
254
+		if (isset($this->jsdata[$key])
255
+			&& ! is_array($this->jsdata[$key])
256
+		) {
257
+			throw new invalidArgumentException(
258
+				sprintf(
259
+					__(
260
+						'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
261 261
                          push values to this data element when it is an array.',
262
-                        'event_espresso'
263
-                    ),
264
-                    $key,
265
-                    __METHOD__
266
-                )
267
-            );
268
-        }
269
-        $this->jsdata[$key][] = $value;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * Used to set content used by javascript for a template.
276
-     * Note: Overrides of existing registered templates are not allowed.
277
-     *
278
-     * @param string $template_reference
279
-     * @param string $template_content
280
-     * @throws InvalidArgumentException
281
-     */
282
-    public function addTemplate($template_reference, $template_content)
283
-    {
284
-        if (! isset($this->jsdata['templates'])) {
285
-            $this->jsdata['templates'] = array();
286
-        }
287
-        //no overrides allowed.
288
-        if (isset($this->jsdata['templates'][$template_reference])) {
289
-            throw new invalidArgumentException(
290
-                sprintf(
291
-                    __(
292
-                        'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
293
-                        'event_espresso'
294
-                    ),
295
-                    $template_reference
296
-                )
297
-            );
298
-        }
299
-        $this->jsdata['templates'][$template_reference] = $template_content;
300
-    }
301
-
302
-
303
-
304
-    /**
305
-     * Retrieve the template content already registered for the given reference.
306
-     *
307
-     * @param string $template_reference
308
-     * @return string
309
-     */
310
-    public function getTemplate($template_reference)
311
-    {
312
-        return isset($this->jsdata['templates'], $this->jsdata['templates'][$template_reference])
313
-            ? $this->jsdata['templates'][$template_reference]
314
-            : '';
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * Retrieve registered data.
321
-     *
322
-     * @param string $key Name of key to attach data to.
323
-     * @return mixed                If there is no for the given key, then false is returned.
324
-     */
325
-    public function getData($key)
326
-    {
327
-        return isset($this->jsdata[$key])
328
-            ? $this->jsdata[$key]
329
-            : false;
330
-    }
331
-
332
-
333
-    /**
334
-     * Get the actual asset path for asset manifests.
335
-     * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
336
-     * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
337
-     *                           asset file location.
338
-     * @param string $chunk_name
339
-     * @param string $asset_type
340
-     * @return string
341
-     * @since 4.9.59.p
342
-     */
343
-    public function getAssetUrl($namespace, $chunk_name, $asset_type)
344
-    {
345
-        $url = isset(
346
-            $this->manifest_data[$namespace][$chunk_name][$asset_type],
347
-            $this->manifest_data[$namespace]['url_base']
348
-        )
349
-            ? $this->manifest_data[$namespace]['url_base']
350
-              . $this->manifest_data[$namespace][$chunk_name][$asset_type]
351
-            : $chunk_name;
352
-        return apply_filters(
353
-            'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
354
-            $url,
355
-            $namespace,
356
-            $chunk_name,
357
-            $asset_type
358
-        );
359
-    }
360
-
361
-
362
-    /**
363
-     * Return the url to a js file for the given namespace and chunk name.
364
-     *
365
-     * @param string $namespace
366
-     * @param string $chunk_name
367
-     * @return string
368
-     */
369
-    public function getJsUrl($namespace, $chunk_name)
370
-    {
371
-        return $this->getAssetUrl($namespace, $chunk_name, self::ASSET_TYPE_JS);
372
-    }
373
-
374
-
375
-    /**
376
-     * Return the url to a css file for the given namespace and chunk name.
377
-     *
378
-     * @param string $namespace
379
-     * @param string $chunk_name
380
-     * @return string
381
-     */
382
-    public function getCssUrl($namespace, $chunk_name)
383
-    {
384
-        return $this->getAssetUrl($namespace, $chunk_name, self::ASSET_TYPE_CSS);
385
-    }
386
-
387
-
388
-    /**
389
-     * Used to register a js/css manifest file with the registered_manifest_files property.
390
-     *
391
-     * @param string $namespace     Provided to associate the manifest file with a specific namespace.
392
-     * @param string $url_base      The url base for the manifest file location.
393
-     * @param string $manifest_file The absolute path to the manifest file.
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidFilePathException
396
-     * @since 4.9.59.p
397
-     */
398
-    public function registerManifestFile($namespace, $url_base, $manifest_file)
399
-    {
400
-        if (isset($this->manifest_data[$namespace])) {
401
-            throw new InvalidArgumentException(
402
-                sprintf(
403
-                    esc_html__(
404
-                        'The namespace for this manifest file has already been registered, choose a namespace other than %s',
405
-                        'event_espresso'
406
-                    ),
407
-                    $namespace
408
-                )
409
-            );
410
-        }
411
-        if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
412
-            if (is_admin()) {
413
-                EE_Error::add_error(
414
-                    sprintf(
415
-                        esc_html__(
416
-                            'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
417
-                            'event_espresso'
418
-                        ),
419
-                        'Event Espresso',
420
-                        $url_base,
421
-                        'plugins_url',
422
-                        'WP_PLUGIN_URL'
423
-                    ),
424
-                    __FILE__,
425
-                    __FUNCTION__,
426
-                    __LINE__
427
-                );
428
-            }
429
-            return;
430
-        }
431
-        $this->manifest_data[$namespace] = $this->decodeManifestFile($manifest_file);
432
-        if (! isset($this->manifest_data[$namespace]['url_base'])) {
433
-            $this->manifest_data[$namespace]['url_base'] = trailingslashit($url_base);
434
-        }
435
-    }
436
-
437
-
438
-
439
-    /**
440
-     * Decodes json from the provided manifest file.
441
-     *
442
-     * @since 4.9.59.p
443
-     * @param string $manifest_file Path to manifest file.
444
-     * @return array
445
-     * @throws InvalidFilePathException
446
-     */
447
-    private function decodeManifestFile($manifest_file)
448
-    {
449
-        if (! file_exists($manifest_file)) {
450
-            throw new InvalidFilePathException($manifest_file);
451
-        }
452
-        return json_decode(file_get_contents($manifest_file), true);
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * Verifies whether the given data exists already on the jsdata array.
459
-     * Overriding data is not allowed.
460
-     *
461
-     * @param string $key Index for data.
462
-     * @return bool        If valid then return true.
463
-     * @throws InvalidArgumentException if data already exists.
464
-     */
465
-    protected function verifyDataNotExisting($key)
466
-    {
467
-        if (isset($this->jsdata[$key])) {
468
-            if (is_array($this->jsdata[$key])) {
469
-                throw new InvalidArgumentException(
470
-                    sprintf(
471
-                        __(
472
-                            'The value for %1$s already exists in the Registry::eejs object.
262
+						'event_espresso'
263
+					),
264
+					$key,
265
+					__METHOD__
266
+				)
267
+			);
268
+		}
269
+		$this->jsdata[$key][] = $value;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * Used to set content used by javascript for a template.
276
+	 * Note: Overrides of existing registered templates are not allowed.
277
+	 *
278
+	 * @param string $template_reference
279
+	 * @param string $template_content
280
+	 * @throws InvalidArgumentException
281
+	 */
282
+	public function addTemplate($template_reference, $template_content)
283
+	{
284
+		if (! isset($this->jsdata['templates'])) {
285
+			$this->jsdata['templates'] = array();
286
+		}
287
+		//no overrides allowed.
288
+		if (isset($this->jsdata['templates'][$template_reference])) {
289
+			throw new invalidArgumentException(
290
+				sprintf(
291
+					__(
292
+						'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
293
+						'event_espresso'
294
+					),
295
+					$template_reference
296
+				)
297
+			);
298
+		}
299
+		$this->jsdata['templates'][$template_reference] = $template_content;
300
+	}
301
+
302
+
303
+
304
+	/**
305
+	 * Retrieve the template content already registered for the given reference.
306
+	 *
307
+	 * @param string $template_reference
308
+	 * @return string
309
+	 */
310
+	public function getTemplate($template_reference)
311
+	{
312
+		return isset($this->jsdata['templates'], $this->jsdata['templates'][$template_reference])
313
+			? $this->jsdata['templates'][$template_reference]
314
+			: '';
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * Retrieve registered data.
321
+	 *
322
+	 * @param string $key Name of key to attach data to.
323
+	 * @return mixed                If there is no for the given key, then false is returned.
324
+	 */
325
+	public function getData($key)
326
+	{
327
+		return isset($this->jsdata[$key])
328
+			? $this->jsdata[$key]
329
+			: false;
330
+	}
331
+
332
+
333
+	/**
334
+	 * Get the actual asset path for asset manifests.
335
+	 * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
336
+	 * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
337
+	 *                           asset file location.
338
+	 * @param string $chunk_name
339
+	 * @param string $asset_type
340
+	 * @return string
341
+	 * @since 4.9.59.p
342
+	 */
343
+	public function getAssetUrl($namespace, $chunk_name, $asset_type)
344
+	{
345
+		$url = isset(
346
+			$this->manifest_data[$namespace][$chunk_name][$asset_type],
347
+			$this->manifest_data[$namespace]['url_base']
348
+		)
349
+			? $this->manifest_data[$namespace]['url_base']
350
+			  . $this->manifest_data[$namespace][$chunk_name][$asset_type]
351
+			: $chunk_name;
352
+		return apply_filters(
353
+			'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
354
+			$url,
355
+			$namespace,
356
+			$chunk_name,
357
+			$asset_type
358
+		);
359
+	}
360
+
361
+
362
+	/**
363
+	 * Return the url to a js file for the given namespace and chunk name.
364
+	 *
365
+	 * @param string $namespace
366
+	 * @param string $chunk_name
367
+	 * @return string
368
+	 */
369
+	public function getJsUrl($namespace, $chunk_name)
370
+	{
371
+		return $this->getAssetUrl($namespace, $chunk_name, self::ASSET_TYPE_JS);
372
+	}
373
+
374
+
375
+	/**
376
+	 * Return the url to a css file for the given namespace and chunk name.
377
+	 *
378
+	 * @param string $namespace
379
+	 * @param string $chunk_name
380
+	 * @return string
381
+	 */
382
+	public function getCssUrl($namespace, $chunk_name)
383
+	{
384
+		return $this->getAssetUrl($namespace, $chunk_name, self::ASSET_TYPE_CSS);
385
+	}
386
+
387
+
388
+	/**
389
+	 * Used to register a js/css manifest file with the registered_manifest_files property.
390
+	 *
391
+	 * @param string $namespace     Provided to associate the manifest file with a specific namespace.
392
+	 * @param string $url_base      The url base for the manifest file location.
393
+	 * @param string $manifest_file The absolute path to the manifest file.
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidFilePathException
396
+	 * @since 4.9.59.p
397
+	 */
398
+	public function registerManifestFile($namespace, $url_base, $manifest_file)
399
+	{
400
+		if (isset($this->manifest_data[$namespace])) {
401
+			throw new InvalidArgumentException(
402
+				sprintf(
403
+					esc_html__(
404
+						'The namespace for this manifest file has already been registered, choose a namespace other than %s',
405
+						'event_espresso'
406
+					),
407
+					$namespace
408
+				)
409
+			);
410
+		}
411
+		if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
412
+			if (is_admin()) {
413
+				EE_Error::add_error(
414
+					sprintf(
415
+						esc_html__(
416
+							'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
417
+							'event_espresso'
418
+						),
419
+						'Event Espresso',
420
+						$url_base,
421
+						'plugins_url',
422
+						'WP_PLUGIN_URL'
423
+					),
424
+					__FILE__,
425
+					__FUNCTION__,
426
+					__LINE__
427
+				);
428
+			}
429
+			return;
430
+		}
431
+		$this->manifest_data[$namespace] = $this->decodeManifestFile($manifest_file);
432
+		if (! isset($this->manifest_data[$namespace]['url_base'])) {
433
+			$this->manifest_data[$namespace]['url_base'] = trailingslashit($url_base);
434
+		}
435
+	}
436
+
437
+
438
+
439
+	/**
440
+	 * Decodes json from the provided manifest file.
441
+	 *
442
+	 * @since 4.9.59.p
443
+	 * @param string $manifest_file Path to manifest file.
444
+	 * @return array
445
+	 * @throws InvalidFilePathException
446
+	 */
447
+	private function decodeManifestFile($manifest_file)
448
+	{
449
+		if (! file_exists($manifest_file)) {
450
+			throw new InvalidFilePathException($manifest_file);
451
+		}
452
+		return json_decode(file_get_contents($manifest_file), true);
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * Verifies whether the given data exists already on the jsdata array.
459
+	 * Overriding data is not allowed.
460
+	 *
461
+	 * @param string $key Index for data.
462
+	 * @return bool        If valid then return true.
463
+	 * @throws InvalidArgumentException if data already exists.
464
+	 */
465
+	protected function verifyDataNotExisting($key)
466
+	{
467
+		if (isset($this->jsdata[$key])) {
468
+			if (is_array($this->jsdata[$key])) {
469
+				throw new InvalidArgumentException(
470
+					sprintf(
471
+						__(
472
+							'The value for %1$s already exists in the Registry::eejs object.
473 473
                             Overrides are not allowed. Since the value of this data is an array, you may want to use the
474 474
                             %2$s method to push your value to the array.',
475
-                            'event_espresso'
476
-                        ),
477
-                        $key,
478
-                        'pushData()'
479
-                    )
480
-                );
481
-            }
482
-            throw new InvalidArgumentException(
483
-                sprintf(
484
-                    __(
485
-                        'The value for %1$s already exists in the Registry::eejs object. Overrides are not
475
+							'event_espresso'
476
+						),
477
+						$key,
478
+						'pushData()'
479
+					)
480
+				);
481
+			}
482
+			throw new InvalidArgumentException(
483
+				sprintf(
484
+					__(
485
+						'The value for %1$s already exists in the Registry::eejs object. Overrides are not
486 486
                         allowed.  Consider attaching your value to a different key',
487
-                        'event_espresso'
488
-                    ),
489
-                    $key
490
-                )
491
-            );
492
-        }
493
-        return true;
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * registers core default stylesheets
500
-     */
501
-    private function loadCoreCss()
502
-    {
503
-        if ($this->template_config->enable_default_style) {
504
-            $default_stylesheet_path = is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
505
-                ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
506
-                : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css';
507
-            wp_register_style(
508
-                'espresso_default',
509
-                $default_stylesheet_path,
510
-                array('dashicons'),
511
-                EVENT_ESPRESSO_VERSION
512
-            );
513
-            //Load custom style sheet if available
514
-            if ($this->template_config->custom_style_sheet !== null) {
515
-                wp_register_style(
516
-                    'espresso_custom_css',
517
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
518
-                    array('espresso_default'),
519
-                    EVENT_ESPRESSO_VERSION
520
-                );
521
-            }
522
-        }
523
-    }
524
-
525
-
526
-
527
-    /**
528
-     * registers core default javascript
529
-     */
530
-    private function loadCoreJs()
531
-    {
532
-        // load core js
533
-        wp_register_script(
534
-            'espresso_core',
535
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
536
-            array('jquery'),
537
-            EVENT_ESPRESSO_VERSION,
538
-            true
539
-        );
540
-    }
541
-
542
-
543
-
544
-    /**
545
-     * registers jQuery Validate for form validation
546
-     */
547
-    private function loadJqueryValidate()
548
-    {
549
-        // register jQuery Validate and additional methods
550
-        wp_register_script(
551
-            'jquery-validate',
552
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
553
-            array('jquery'),
554
-            '1.15.0',
555
-            true
556
-        );
557
-        wp_register_script(
558
-            'jquery-validate-extra-methods',
559
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
560
-            array('jquery', 'jquery-validate'),
561
-            '1.15.0',
562
-            true
563
-        );
564
-    }
565
-
566
-
567
-
568
-    /**
569
-     * registers accounting.js for performing client-side calculations
570
-     */
571
-    private function loadAccountingJs()
572
-    {
573
-        //accounting.js library
574
-        // @link http://josscrowcroft.github.io/accounting.js/
575
-        wp_register_script(
576
-            'ee-accounting-core',
577
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
578
-            array('underscore'),
579
-            '0.3.2',
580
-            true
581
-        );
582
-        wp_register_script(
583
-            'ee-accounting',
584
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
585
-            array('ee-accounting-core'),
586
-            EVENT_ESPRESSO_VERSION,
587
-            true
588
-        );
589
-    }
590
-
591
-
592
-
593
-    /**
594
-     * registers accounting.js for performing client-side calculations
595
-     */
596
-    private function localizeAccountingJs()
597
-    {
598
-        wp_localize_script(
599
-            'ee-accounting',
600
-            'EE_ACCOUNTING_CFG',
601
-            array(
602
-                'currency' => array(
603
-                    'symbol'    => $this->currency_config->sign,
604
-                    'format'    => array(
605
-                        'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
606
-                        'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
607
-                        'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
608
-                    ),
609
-                    'decimal'   => $this->currency_config->dec_mrk,
610
-                    'thousand'  => $this->currency_config->thsnds,
611
-                    'precision' => $this->currency_config->dec_plc,
612
-                ),
613
-                'number'   => array(
614
-                    'precision' => $this->currency_config->dec_plc,
615
-                    'thousand'  => $this->currency_config->thsnds,
616
-                    'decimal'   => $this->currency_config->dec_mrk,
617
-                ),
618
-            )
619
-        );
620
-        $this->addRegisteredScriptHandlesWithData('ee-accounting');
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * registers assets for cleaning your ears
627
-     */
628
-    private function loadQtipJs()
629
-    {
630
-        // qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
631
-        // can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
632
-        if (apply_filters('FHEE_load_qtip', false)) {
633
-            EEH_Qtip_Loader::instance()->register_and_enqueue();
634
-        }
635
-    }
636
-
637
-
638
-    /**
639
-     * This is used to set registered script handles that have data.
640
-     * @param string $script_handle
641
-     */
642
-    private function addRegisteredScriptHandlesWithData($script_handle)
643
-    {
644
-        $this->script_handles_with_data[$script_handle] = $script_handle;
645
-    }
646
-
647
-
648
-    /**i
487
+						'event_espresso'
488
+					),
489
+					$key
490
+				)
491
+			);
492
+		}
493
+		return true;
494
+	}
495
+
496
+
497
+
498
+	/**
499
+	 * registers core default stylesheets
500
+	 */
501
+	private function loadCoreCss()
502
+	{
503
+		if ($this->template_config->enable_default_style) {
504
+			$default_stylesheet_path = is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
505
+				? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
506
+				: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css';
507
+			wp_register_style(
508
+				'espresso_default',
509
+				$default_stylesheet_path,
510
+				array('dashicons'),
511
+				EVENT_ESPRESSO_VERSION
512
+			);
513
+			//Load custom style sheet if available
514
+			if ($this->template_config->custom_style_sheet !== null) {
515
+				wp_register_style(
516
+					'espresso_custom_css',
517
+					EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
518
+					array('espresso_default'),
519
+					EVENT_ESPRESSO_VERSION
520
+				);
521
+			}
522
+		}
523
+	}
524
+
525
+
526
+
527
+	/**
528
+	 * registers core default javascript
529
+	 */
530
+	private function loadCoreJs()
531
+	{
532
+		// load core js
533
+		wp_register_script(
534
+			'espresso_core',
535
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
536
+			array('jquery'),
537
+			EVENT_ESPRESSO_VERSION,
538
+			true
539
+		);
540
+	}
541
+
542
+
543
+
544
+	/**
545
+	 * registers jQuery Validate for form validation
546
+	 */
547
+	private function loadJqueryValidate()
548
+	{
549
+		// register jQuery Validate and additional methods
550
+		wp_register_script(
551
+			'jquery-validate',
552
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
553
+			array('jquery'),
554
+			'1.15.0',
555
+			true
556
+		);
557
+		wp_register_script(
558
+			'jquery-validate-extra-methods',
559
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
560
+			array('jquery', 'jquery-validate'),
561
+			'1.15.0',
562
+			true
563
+		);
564
+	}
565
+
566
+
567
+
568
+	/**
569
+	 * registers accounting.js for performing client-side calculations
570
+	 */
571
+	private function loadAccountingJs()
572
+	{
573
+		//accounting.js library
574
+		// @link http://josscrowcroft.github.io/accounting.js/
575
+		wp_register_script(
576
+			'ee-accounting-core',
577
+			EE_THIRD_PARTY_URL . 'accounting/accounting.js',
578
+			array('underscore'),
579
+			'0.3.2',
580
+			true
581
+		);
582
+		wp_register_script(
583
+			'ee-accounting',
584
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
585
+			array('ee-accounting-core'),
586
+			EVENT_ESPRESSO_VERSION,
587
+			true
588
+		);
589
+	}
590
+
591
+
592
+
593
+	/**
594
+	 * registers accounting.js for performing client-side calculations
595
+	 */
596
+	private function localizeAccountingJs()
597
+	{
598
+		wp_localize_script(
599
+			'ee-accounting',
600
+			'EE_ACCOUNTING_CFG',
601
+			array(
602
+				'currency' => array(
603
+					'symbol'    => $this->currency_config->sign,
604
+					'format'    => array(
605
+						'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
606
+						'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
607
+						'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
608
+					),
609
+					'decimal'   => $this->currency_config->dec_mrk,
610
+					'thousand'  => $this->currency_config->thsnds,
611
+					'precision' => $this->currency_config->dec_plc,
612
+				),
613
+				'number'   => array(
614
+					'precision' => $this->currency_config->dec_plc,
615
+					'thousand'  => $this->currency_config->thsnds,
616
+					'decimal'   => $this->currency_config->dec_mrk,
617
+				),
618
+			)
619
+		);
620
+		$this->addRegisteredScriptHandlesWithData('ee-accounting');
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * registers assets for cleaning your ears
627
+	 */
628
+	private function loadQtipJs()
629
+	{
630
+		// qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
631
+		// can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
632
+		if (apply_filters('FHEE_load_qtip', false)) {
633
+			EEH_Qtip_Loader::instance()->register_and_enqueue();
634
+		}
635
+	}
636
+
637
+
638
+	/**
639
+	 * This is used to set registered script handles that have data.
640
+	 * @param string $script_handle
641
+	 */
642
+	private function addRegisteredScriptHandlesWithData($script_handle)
643
+	{
644
+		$this->script_handles_with_data[$script_handle] = $script_handle;
645
+	}
646
+
647
+
648
+	/**i
649 649
      * Checks WP_Scripts for all of each script handle registered internally as having data and unsets from the
650 650
      * Dependency stored in WP_Scripts if its set.
651 651
      */
652
-    private function removeAlreadyRegisteredDataForScriptHandles()
653
-    {
654
-        if (empty($this->script_handles_with_data)) {
655
-            return;
656
-        }
657
-        foreach ($this->script_handles_with_data as $script_handle) {
658
-            $this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
659
-        }
660
-    }
661
-
662
-
663
-    /**
664
-     * Removes any data dependency registered in WP_Scripts if its set.
665
-     * @param string $script_handle
666
-     */
667
-    private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
668
-    {
669
-        if (isset($this->script_handles_with_data[$script_handle])) {
670
-            global $wp_scripts;
671
-            $unset_handle = false;
672
-            if ($wp_scripts->get_data($script_handle, 'data')) {
673
-                unset($wp_scripts->registered[$script_handle]->extra['data']);
674
-                $unset_handle = true;
675
-            }
676
-            //deal with inline_scripts
677
-            if ($wp_scripts->get_data($script_handle, 'before')) {
678
-                unset($wp_scripts->registered[$script_handle]->extra['before']);
679
-                $unset_handle = true;
680
-            }
681
-            if ($wp_scripts->get_data($script_handle, 'after')) {
682
-                unset($wp_scripts->registered[$script_handle]->extra['after']);
683
-            }
684
-            if ($unset_handle) {
685
-                unset($this->script_handles_with_data[$script_handle]);
686
-            }
687
-        }
688
-    }
689
-
690
-
691
-    /**
692
-     * Registers assets that are used in the WordPress admin.
693
-     */
694
-    private function registerAdminAssets()
695
-    {
696
-        wp_register_script(
697
-            'ee-wp-plugins-page',
698
-            $this->getJsUrl(self::ASSET_NAMESPACE, 'wp-plugins-page'),
699
-            array(
700
-                'jquery',
701
-                'ee-vendor-react'
702
-            ),
703
-            null,
704
-            true
705
-        );
706
-        wp_register_style(
707
-            'ee-wp-plugins-page',
708
-            $this->getCssUrl(self::ASSET_NAMESPACE, 'wp-plugins-page'),
709
-            array(),
710
-            null
711
-        );
712
-        $this->registerTranslationsForHandles(array('ee-wp-plugins-page'));
713
-    }
714
-
715
-
716
-    /**
717
-     * All handles that are registered via the registry that might have translations have their translations registered
718
-     *
719
-     * @param array $handles_to_register
720
-     */
721
-    private function registerTranslationsForHandles(array $handles_to_register)
722
-    {
723
-        foreach($handles_to_register as $handle) {
724
-            $this->i18n_registry->registerScriptI18n($handle);
725
-        }
726
-    }
652
+	private function removeAlreadyRegisteredDataForScriptHandles()
653
+	{
654
+		if (empty($this->script_handles_with_data)) {
655
+			return;
656
+		}
657
+		foreach ($this->script_handles_with_data as $script_handle) {
658
+			$this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
659
+		}
660
+	}
661
+
662
+
663
+	/**
664
+	 * Removes any data dependency registered in WP_Scripts if its set.
665
+	 * @param string $script_handle
666
+	 */
667
+	private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
668
+	{
669
+		if (isset($this->script_handles_with_data[$script_handle])) {
670
+			global $wp_scripts;
671
+			$unset_handle = false;
672
+			if ($wp_scripts->get_data($script_handle, 'data')) {
673
+				unset($wp_scripts->registered[$script_handle]->extra['data']);
674
+				$unset_handle = true;
675
+			}
676
+			//deal with inline_scripts
677
+			if ($wp_scripts->get_data($script_handle, 'before')) {
678
+				unset($wp_scripts->registered[$script_handle]->extra['before']);
679
+				$unset_handle = true;
680
+			}
681
+			if ($wp_scripts->get_data($script_handle, 'after')) {
682
+				unset($wp_scripts->registered[$script_handle]->extra['after']);
683
+			}
684
+			if ($unset_handle) {
685
+				unset($this->script_handles_with_data[$script_handle]);
686
+			}
687
+		}
688
+	}
689
+
690
+
691
+	/**
692
+	 * Registers assets that are used in the WordPress admin.
693
+	 */
694
+	private function registerAdminAssets()
695
+	{
696
+		wp_register_script(
697
+			'ee-wp-plugins-page',
698
+			$this->getJsUrl(self::ASSET_NAMESPACE, 'wp-plugins-page'),
699
+			array(
700
+				'jquery',
701
+				'ee-vendor-react'
702
+			),
703
+			null,
704
+			true
705
+		);
706
+		wp_register_style(
707
+			'ee-wp-plugins-page',
708
+			$this->getCssUrl(self::ASSET_NAMESPACE, 'wp-plugins-page'),
709
+			array(),
710
+			null
711
+		);
712
+		$this->registerTranslationsForHandles(array('ee-wp-plugins-page'));
713
+	}
714
+
715
+
716
+	/**
717
+	 * All handles that are registered via the registry that might have translations have their translations registered
718
+	 *
719
+	 * @param array $handles_to_register
720
+	 */
721
+	private function registerTranslationsForHandles(array $handles_to_register)
722
+	{
723
+		foreach($handles_to_register as $handle) {
724
+			$this->i18n_registry->registerScriptI18n($handle);
725
+		}
726
+	}
727 727
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
         $this->registerManifestFile(
114 114
             self::ASSET_NAMESPACE,
115 115
             $this->domain->distributionAssetsUrl(),
116
-            $this->domain->distributionAssetsPath() . 'build-manifest.json'
116
+            $this->domain->distributionAssetsPath().'build-manifest.json'
117 117
         );
118 118
         add_action('wp_enqueue_scripts', array($this, 'scripts'), 1);
119 119
         add_action('admin_enqueue_scripts', array($this, 'scripts'), 1);
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
             //js.api
171 171
             wp_register_script(
172 172
                 'eejs-api',
173
-                EE_LIBRARIES_URL . 'rest_api/assets/js/eejs-api.min.js',
173
+                EE_LIBRARIES_URL.'rest_api/assets/js/eejs-api.min.js',
174 174
                 array('underscore', 'eejs-core'),
175 175
                 EVENT_ESPRESSO_VERSION,
176 176
                 true
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
             $this->jsdata['eejs_api_nonce'] = wp_create_nonce('wp_rest');
179 179
             $this->jsdata['paths'] = array('rest_route' => rest_url('ee/v4.8.36/'));
180 180
         }
181
-        if (! is_admin()) {
181
+        if ( ! is_admin()) {
182 182
             $this->loadCoreCss();
183 183
         }
184 184
         $this->registerTranslationsForHandles(array('eejs-core'));
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         $this->removeAlreadyRegisteredDataForScriptHandles();
203 203
         wp_add_inline_script(
204 204
             'eejs-core',
205
-            'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
205
+            'var eejsdata='.wp_json_encode(array('data' => $this->jsdata)),
206 206
             'before'
207 207
         );
208 208
         wp_localize_script('espresso_core', 'eei18n', EE_Registry::$i18n_js_strings);
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
      */
282 282
     public function addTemplate($template_reference, $template_content)
283 283
     {
284
-        if (! isset($this->jsdata['templates'])) {
284
+        if ( ! isset($this->jsdata['templates'])) {
285 285
             $this->jsdata['templates'] = array();
286 286
         }
287 287
         //no overrides allowed.
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
             return;
430 430
         }
431 431
         $this->manifest_data[$namespace] = $this->decodeManifestFile($manifest_file);
432
-        if (! isset($this->manifest_data[$namespace]['url_base'])) {
432
+        if ( ! isset($this->manifest_data[$namespace]['url_base'])) {
433 433
             $this->manifest_data[$namespace]['url_base'] = trailingslashit($url_base);
434 434
         }
435 435
     }
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
      */
447 447
     private function decodeManifestFile($manifest_file)
448 448
     {
449
-        if (! file_exists($manifest_file)) {
449
+        if ( ! file_exists($manifest_file)) {
450 450
             throw new InvalidFilePathException($manifest_file);
451 451
         }
452 452
         return json_decode(file_get_contents($manifest_file), true);
@@ -501,9 +501,9 @@  discard block
 block discarded – undo
501 501
     private function loadCoreCss()
502 502
     {
503 503
         if ($this->template_config->enable_default_style) {
504
-            $default_stylesheet_path = is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
504
+            $default_stylesheet_path = is_readable(EVENT_ESPRESSO_UPLOAD_DIR.'css/style.css')
505 505
                 ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
506
-                : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css';
506
+                : EE_GLOBAL_ASSETS_URL.'css/espresso_default.css';
507 507
             wp_register_style(
508 508
                 'espresso_default',
509 509
                 $default_stylesheet_path,
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
             if ($this->template_config->custom_style_sheet !== null) {
515 515
                 wp_register_style(
516 516
                     'espresso_custom_css',
517
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
517
+                    EVENT_ESPRESSO_UPLOAD_URL.'css/'.$this->template_config->custom_style_sheet,
518 518
                     array('espresso_default'),
519 519
                     EVENT_ESPRESSO_VERSION
520 520
                 );
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
         // load core js
533 533
         wp_register_script(
534 534
             'espresso_core',
535
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
535
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
536 536
             array('jquery'),
537 537
             EVENT_ESPRESSO_VERSION,
538 538
             true
@@ -549,14 +549,14 @@  discard block
 block discarded – undo
549 549
         // register jQuery Validate and additional methods
550 550
         wp_register_script(
551 551
             'jquery-validate',
552
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
552
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
553 553
             array('jquery'),
554 554
             '1.15.0',
555 555
             true
556 556
         );
557 557
         wp_register_script(
558 558
             'jquery-validate-extra-methods',
559
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
559
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
560 560
             array('jquery', 'jquery-validate'),
561 561
             '1.15.0',
562 562
             true
@@ -574,14 +574,14 @@  discard block
 block discarded – undo
574 574
         // @link http://josscrowcroft.github.io/accounting.js/
575 575
         wp_register_script(
576 576
             'ee-accounting-core',
577
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
577
+            EE_THIRD_PARTY_URL.'accounting/accounting.js',
578 578
             array('underscore'),
579 579
             '0.3.2',
580 580
             true
581 581
         );
582 582
         wp_register_script(
583 583
             'ee-accounting',
584
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
584
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-accounting-config.js',
585 585
             array('ee-accounting-core'),
586 586
             EVENT_ESPRESSO_VERSION,
587 587
             true
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
      */
721 721
     private function registerTranslationsForHandles(array $handles_to_register)
722 722
     {
723
-        foreach($handles_to_register as $handle) {
723
+        foreach ($handles_to_register as $handle) {
724 724
             $this->i18n_registry->registerScriptI18n($handle);
725 725
         }
726 726
     }
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Indentation   +1253 added lines, -1253 removed lines patch added patch discarded remove patch
@@ -26,1260 +26,1260 @@
 block discarded – undo
26 26
 class EED_Core_Rest_Api extends \EED_Module
27 27
 {
28 28
 
29
-    const ee_api_namespace           = Domain::API_NAMESPACE;
29
+	const ee_api_namespace           = Domain::API_NAMESPACE;
30 30
 
31
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
32
-
33
-    const saved_routes_option_names  = 'ee_core_routes';
34
-
35
-    /**
36
-     * string used in _links response bodies to make them globally unique.
37
-     *
38
-     * @see http://v2.wp-api.org/extending/linking/
39
-     */
40
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
41
-
42
-    /**
43
-     * @var CalculatedModelFields
44
-     */
45
-    protected static $_field_calculator;
46
-
47
-
48
-
49
-    /**
50
-     * @return EED_Core_Rest_Api|EED_Module
51
-     */
52
-    public static function instance()
53
-    {
54
-        self::$_field_calculator = new CalculatedModelFields();
55
-        return parent::get_instance(__CLASS__);
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     *    set_hooks - for hooking into EE Core, other modules, etc
62
-     *
63
-     * @access    public
64
-     * @return    void
65
-     */
66
-    public static function set_hooks()
67
-    {
68
-        self::set_hooks_both();
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
75
-     *
76
-     * @access    public
77
-     * @return    void
78
-     */
79
-    public static function set_hooks_admin()
80
-    {
81
-        self::set_hooks_both();
82
-    }
83
-
84
-
85
-
86
-    public static function set_hooks_both()
87
-    {
88
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
89
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
90
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
91
-        add_filter('rest_index',
92
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
93
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
94
-    }
95
-
96
-
97
-
98
-    /**
99
-     * sets up hooks which only need to be included as part of REST API requests;
100
-     * other requests like to the frontend or admin etc don't need them
101
-     *
102
-     * @throws \EE_Error
103
-     */
104
-    public static function set_hooks_rest_api()
105
-    {
106
-        //set hooks which account for changes made to the API
107
-        EED_Core_Rest_Api::_set_hooks_for_changes();
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * public wrapper of _set_hooks_for_changes.
114
-     * Loads all the hooks which make requests to old versions of the API
115
-     * appear the same as they always did
116
-     *
117
-     * @throws EE_Error
118
-     */
119
-    public static function set_hooks_for_changes()
120
-    {
121
-        self::_set_hooks_for_changes();
122
-    }
123
-
124
-
125
-
126
-    /**
127
-     * Loads all the hooks which make requests to old versions of the API
128
-     * appear the same as they always did
129
-     *
130
-     * @throws EE_Error
131
-     */
132
-    protected static function _set_hooks_for_changes()
133
-    {
134
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
135
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
136
-            //ignore the base parent class
137
-            //and legacy named classes
138
-            if ($classname_in_namespace === 'ChangesInBase'
139
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
140
-            ) {
141
-                continue;
142
-            }
143
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
144
-            if (class_exists($full_classname)) {
145
-                $instance_of_class = new $full_classname;
146
-                if ($instance_of_class instanceof ChangesInBase) {
147
-                    $instance_of_class->setHooks();
148
-                }
149
-            }
150
-        }
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
157
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
158
-     *
159
-     * @throws \EE_Error
160
-     */
161
-    public static function register_routes()
162
-    {
163
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
164
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
165
-                /**
166
-                 * @var array $data_for_multiple_endpoints numerically indexed array
167
-                 *                                         but can also contain route options like {
168
-                 * @type array    $schema                      {
169
-                 * @type callable $schema_callback
170
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
171
-                 * WP_REST_Request of course
172
-                 * }
173
-                 * }
174
-                 */
175
-                //when registering routes, register all the endpoints' data at the same time
176
-                $multiple_endpoint_args = array();
177
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
178
-                    /**
179
-                     * @var array     $data_for_single_endpoint {
180
-                     * @type callable $callback
181
-                     * @type string methods
182
-                     * @type array args
183
-                     * @type array _links
184
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
185
-                     * WP_REST_Request of course
186
-                     * }
187
-                     */
188
-                    //skip route options
189
-                    if (! is_numeric($endpoint_key)) {
190
-                        continue;
191
-                    }
192
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
193
-                        throw new EE_Error(
194
-                            esc_html__(
195
-                                // @codingStandardsIgnoreStart
196
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
197
-                                // @codingStandardsIgnoreEnd
198
-                                'event_espresso')
199
-                        );
200
-                    }
201
-                    $callback = $data_for_single_endpoint['callback'];
202
-                    $single_endpoint_args = array(
203
-                        'methods' => $data_for_single_endpoint['methods'],
204
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
205
-                            : array(),
206
-                    );
207
-                    if (isset($data_for_single_endpoint['_links'])) {
208
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
209
-                    }
210
-                    if (isset($data_for_single_endpoint['callback_args'])) {
211
-                        $callback_args = $data_for_single_endpoint['callback_args'];
212
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
213
-                            $callback,
214
-                            $callback_args
215
-                        ) {
216
-                            array_unshift($callback_args, $request);
217
-                            return call_user_func_array(
218
-                                $callback,
219
-                                $callback_args
220
-                            );
221
-                        };
222
-                    } else {
223
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
224
-                    }
225
-                    $multiple_endpoint_args[] = $single_endpoint_args;
226
-                }
227
-                if (isset($data_for_multiple_endpoints['schema'])) {
228
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
229
-                    $schema_callback = $schema_route_data['schema_callback'];
230
-                    $callback_args = $schema_route_data['callback_args'];
231
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
-                        return call_user_func_array(
233
-                            $schema_callback,
234
-                            $callback_args
235
-                        );
236
-                    };
237
-                }
238
-                register_rest_route(
239
-                    $namespace,
240
-                    $relative_route,
241
-                    $multiple_endpoint_args
242
-                );
243
-            }
244
-        }
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Checks if there was a version change or something that merits invalidating the cached
251
-     * route data. If so, invalidates the cached route data so that it gets refreshed
252
-     * next time the WP API is used
253
-     */
254
-    public static function invalidate_cached_route_data_on_version_change()
255
-    {
256
-        if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
257
-            EED_Core_Rest_Api::invalidate_cached_route_data();
258
-        }
259
-        foreach (EE_Registry::instance()->addons as $addon) {
260
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
261
-                EED_Core_Rest_Api::invalidate_cached_route_data();
262
-            }
263
-        }
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * Removes the cached route data so it will get refreshed next time the WP API is used
270
-     */
271
-    public static function invalidate_cached_route_data()
272
-    {
273
-        //delete the saved EE REST API routes
274
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
275
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
276
-        }
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * Gets the EE route data
283
-     *
284
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
285
-     * @throws \EE_Error
286
-     * @type string|array $callback
287
-     * @type string       $methods
288
-     * @type boolean      $hidden_endpoint
289
-     * }
290
-     */
291
-    public static function get_ee_route_data()
292
-    {
293
-        $ee_routes = array();
294
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
295
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
296
-                $version,
297
-                $hidden_endpoints
298
-            );
299
-        }
300
-        return $ee_routes;
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     * Gets the EE route data from the wp options if it exists already,
307
-     * otherwise re-generates it and saves it to the option
308
-     *
309
-     * @param string  $version
310
-     * @param boolean $hidden_endpoints
311
-     * @return array
312
-     * @throws \EE_Error
313
-     */
314
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
315
-    {
316
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
317
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
318
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
319
-        }
320
-        return $ee_routes;
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Saves the EE REST API route data to a wp option and returns it
327
-     *
328
-     * @param string  $version
329
-     * @param boolean $hidden_endpoints
330
-     * @return mixed|null
331
-     * @throws \EE_Error
332
-     */
333
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
334
-    {
335
-        $instance = self::instance();
336
-        $routes = apply_filters(
337
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
338
-            array_replace_recursive(
339
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
340
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
341
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
342
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
343
-            )
344
-        );
345
-        $option_name = self::saved_routes_option_names . $version;
346
-        if (get_option($option_name)) {
347
-            update_option($option_name, $routes, true);
348
-        } else {
349
-            add_option($option_name, $routes, null, 'no');
350
-        }
351
-        return $routes;
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
358
-     * need to calculate it on every request
359
-     *
360
-     * @deprecated since version 4.9.1
361
-     * @return void
362
-     */
363
-    public static function save_ee_routes()
364
-    {
365
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
366
-            $instance = self::instance();
367
-            $routes = apply_filters(
368
-                'EED_Core_Rest_Api__save_ee_routes__routes',
369
-                array_replace_recursive(
370
-                    $instance->_register_config_routes(),
371
-                    $instance->_register_meta_routes(),
372
-                    $instance->_register_model_routes(),
373
-                    $instance->_register_rpc_routes()
374
-                )
375
-            );
376
-            update_option(self::saved_routes_option_names, $routes, true);
377
-        }
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * Gets all the route information relating to EE models
384
-     *
385
-     * @return array @see get_ee_route_data
386
-     * @deprecated since version 4.9.1
387
-     */
388
-    protected function _register_model_routes()
389
-    {
390
-        $model_routes = array();
391
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
392
-            $model_routes[EED_Core_Rest_Api::ee_api_namespace
393
-                          . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
394
-        }
395
-        return $model_routes;
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * Decides whether or not to add write endpoints for this model.
402
-     *
403
-     * Currently, this defaults to exclude all global tables and models
404
-     * which would allow inserting WP core data (we don't want to duplicate
405
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
406
-     * @param EEM_Base $model
407
-     * @return bool
408
-     */
409
-    public static function should_have_write_endpoints(EEM_Base $model)
410
-    {
411
-        if ($model->is_wp_core_model()){
412
-            return false;
413
-        }
414
-        foreach($model->get_tables() as $table){
415
-            if( $table->is_global()){
416
-                return false;
417
-            }
418
-        }
419
-        return true;
420
-    }
421
-
422
-
423
-
424
-    /**
425
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
426
-     * in this versioned namespace of EE4
427
-     * @param $version
428
-     * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
429
-     */
430
-    public static function model_names_with_plural_routes($version){
431
-        $model_version_info = new ModelVersionInfo($version);
432
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
433
-        //let's not bother having endpoints for extra metas
434
-        unset(
435
-            $models_to_register['Extra_Meta'],
436
-            $models_to_register['Extra_Join'],
437
-            $models_to_register['Post_Meta']
438
-        );
439
-        return apply_filters(
440
-            'FHEE__EED_Core_REST_API___register_model_routes',
441
-            $models_to_register
442
-        );
443
-    }
444
-
445
-
446
-
447
-    /**
448
-     * Gets the route data for EE models in the specified version
449
-     *
450
-     * @param string  $version
451
-     * @param boolean $hidden_endpoint
452
-     * @return array
453
-     * @throws EE_Error
454
-     */
455
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
456
-    {
457
-        $model_routes = array();
458
-        $model_version_info = new ModelVersionInfo($version);
459
-        foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
460
-            $model = \EE_Registry::instance()->load_model($model_name);
461
-            //if this isn't a valid model then let's skip iterate to the next item in the loop.
462
-            if (! $model instanceof EEM_Base) {
463
-                continue;
464
-            }
465
-            //yes we could just register one route for ALL models, but then they wouldn't show up in the index
466
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
467
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
468
-            $model_routes[$plural_model_route] = array(
469
-                array(
470
-                    'callback'        => array(
471
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
472
-                        'handleRequestGetAll',
473
-                    ),
474
-                    'callback_args'   => array($version, $model_name),
475
-                    'methods'         => WP_REST_Server::READABLE,
476
-                    'hidden_endpoint' => $hidden_endpoint,
477
-                    'args'            => $this->_get_read_query_params($model, $version),
478
-                    '_links'          => array(
479
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
480
-                    ),
481
-                ),
482
-                'schema' => array(
483
-                    'schema_callback' => array(
484
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
485
-                        'handleSchemaRequest',
486
-                    ),
487
-                    'callback_args'   => array($version, $model_name),
488
-                ),
489
-            );
490
-            $model_routes[$singular_model_route] = array(
491
-                array(
492
-                    'callback'        => array(
493
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
494
-                        'handleRequestGetOne',
495
-                    ),
496
-                    'callback_args'   => array($version, $model_name),
497
-                    'methods'         => WP_REST_Server::READABLE,
498
-                    'hidden_endpoint' => $hidden_endpoint,
499
-                    'args'            => $this->_get_response_selection_query_params($model, $version),
500
-                ),
501
-            );
502
-            if( apply_filters(
503
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
504
-                EED_Core_Rest_Api::should_have_write_endpoints($model),
505
-                $model
506
-            )){
507
-                $model_routes[$plural_model_route][] = array(
508
-                    'callback'        => array(
509
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
510
-                        'handleRequestInsert',
511
-                    ),
512
-                    'callback_args'   => array($version, $model_name),
513
-                    'methods'         => WP_REST_Server::CREATABLE,
514
-                    'hidden_endpoint' => $hidden_endpoint,
515
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
516
-                );
517
-                $model_routes[$singular_model_route] = array_merge(
518
-                    $model_routes[$singular_model_route],
519
-                    array(
520
-                        array(
521
-                            'callback'        => array(
522
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
523
-                                'handleRequestUpdate',
524
-                            ),
525
-                            'callback_args'   => array($version, $model_name),
526
-                            'methods'         => WP_REST_Server::EDITABLE,
527
-                            'hidden_endpoint' => $hidden_endpoint,
528
-                            'args'            => $this->_get_write_params($model_name, $model_version_info),
529
-                        ),
530
-                        array(
531
-                            'callback'        => array(
532
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
533
-                                'handleRequestDelete',
534
-                            ),
535
-                            'callback_args'   => array($version, $model_name),
536
-                            'methods'         => WP_REST_Server::DELETABLE,
537
-                            'hidden_endpoint' => $hidden_endpoint,
538
-                            'args'            => $this->_get_delete_query_params($model, $version),
539
-                        )
540
-                    )
541
-                );
542
-            }
543
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
544
-
545
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
546
-                    $model,
547
-                    '(?P<id>[^\/]+)',
548
-                    $relation_obj
549
-                );
550
-                $endpoints = array(
551
-                    array(
552
-                        'callback'        => array(
553
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
554
-                            'handleRequestGetRelated',
555
-                        ),
556
-                        'callback_args'   => array($version, $model_name, $relation_name),
557
-                        'methods'         => WP_REST_Server::READABLE,
558
-                        'hidden_endpoint' => $hidden_endpoint,
559
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
560
-                    ),
561
-                );
562
-                $model_routes[$related_route] = $endpoints;
563
-            }
564
-        }
565
-        return $model_routes;
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
572
-     * excluding the preceding slash.
573
-     * Eg you pass get_plural_route_to('Event') = 'events'
574
-     *
575
-     * @param EEM_Base $model
576
-     * @return string
577
-     */
578
-    public static function get_collection_route(EEM_Base $model)
579
-    {
580
-        return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
587
-     * excluding the preceding slash.
588
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
589
-     *
590
-     * @param EEM_Base $model eg Event or Venue
591
-     * @param string $id
592
-     * @return string
593
-     */
594
-    public static function get_entity_route($model, $id)
595
-    {
596
-        return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
597
-    }
598
-
599
-
600
-    /**
601
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
-     * excluding the preceding slash.
603
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
-     *
605
-     * @param EEM_Base                 $model eg Event or Venue
606
-     * @param string                 $id
607
-     * @param EE_Model_Relation_Base $relation_obj
608
-     * @return string
609
-     */
610
-    public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
611
-    {
612
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
613
-            $relation_obj->get_other_model()->get_this_model_name(),
614
-            $relation_obj
615
-        );
616
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
617
-    }
618
-
619
-
620
-
621
-    /**
622
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
623
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
624
-     * @param string $relative_route
625
-     * @param string $version
626
-     * @return string
627
-     */
628
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
629
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
630
-    }
631
-
632
-
633
-
634
-    /**
635
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
636
-     * routes that don't conform to the traditional REST CRUD-style).
637
-     *
638
-     * @deprecated since 4.9.1
639
-     */
640
-    protected function _register_rpc_routes()
641
-    {
642
-        $routes = array();
643
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
644
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
645
-                $version,
646
-                $hidden_endpoint
647
-            );
648
-        }
649
-        return $routes;
650
-    }
651
-
652
-
653
-
654
-    /**
655
-     * @param string  $version
656
-     * @param boolean $hidden_endpoint
657
-     * @return array
658
-     */
659
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
660
-    {
661
-        $this_versions_routes = array();
662
-        //checkin endpoint
663
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
664
-            array(
665
-                'callback'        => array(
666
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
667
-                    'handleRequestToggleCheckin',
668
-                ),
669
-                'methods'         => WP_REST_Server::CREATABLE,
670
-                'hidden_endpoint' => $hidden_endpoint,
671
-                'args'            => array(
672
-                    'force' => array(
673
-                        'required'    => false,
674
-                        'default'     => false,
675
-                        'description' => __(
676
-                            // @codingStandardsIgnoreStart
677
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
678
-                            // @codingStandardsIgnoreEnd
679
-                            'event_espresso'
680
-                        ),
681
-                    ),
682
-                ),
683
-                'callback_args'   => array($version),
684
-            ),
685
-        );
686
-        return apply_filters(
687
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
688
-            $this_versions_routes,
689
-            $version,
690
-            $hidden_endpoint
691
-        );
692
-    }
693
-
694
-
695
-
696
-    /**
697
-     * Gets the query params that can be used when request one or many
698
-     *
699
-     * @param EEM_Base $model
700
-     * @param string   $version
701
-     * @return array
702
-     */
703
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version)
704
-    {
705
-        return apply_filters(
706
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
707
-            array(
708
-                'include'   => array(
709
-                    'required' => false,
710
-                    'default'  => '*',
711
-                    'type'     => 'string',
712
-                ),
713
-                'calculate' => array(
714
-                    'required'          => false,
715
-                    'default'           => '',
716
-                    'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
717
-                    'type'              => 'string',
718
-                    //because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
719
-                    //freaks out. We'll just validate this argument while handling the request
720
-                    'validate_callback' => null,
721
-                    'sanitize_callback' => null,
722
-                ),
723
-            ),
724
-            $model,
725
-            $version
726
-        );
727
-    }
728
-
729
-
730
-
731
-    /**
732
-     * Gets the parameters acceptable for delete requests
733
-     *
734
-     * @param \EEM_Base $model
735
-     * @param string    $version
736
-     * @return array
737
-     */
738
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
739
-    {
740
-        $params_for_delete = array(
741
-            'allow_blocking' => array(
742
-                'required' => false,
743
-                'default'  => true,
744
-                'type'     => 'boolean',
745
-            ),
746
-        );
747
-        $params_for_delete['force'] = array(
748
-            'required' => false,
749
-            'default'  => false,
750
-            'type'     => 'boolean',
751
-        );
752
-        return apply_filters(
753
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
754
-            $params_for_delete,
755
-            $model,
756
-            $version
757
-        );
758
-    }
759
-
760
-
761
-
762
-    /**
763
-     * Gets info about reading query params that are acceptable
764
-     *
765
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
766
-     * @param  string   $version
767
-     * @return array    describing the args acceptable when querying this model
768
-     * @throws EE_Error
769
-     */
770
-    protected function _get_read_query_params(\EEM_Base $model, $version)
771
-    {
772
-        $default_orderby = array();
773
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
774
-            $default_orderby[$key_field->get_name()] = 'ASC';
775
-        }
776
-        return array_merge(
777
-            $this->_get_response_selection_query_params($model, $version),
778
-            array(
779
-                'where'    => array(
780
-                    'required' => false,
781
-                    'default'  => array(),
782
-                    'type'     => 'object',
783
-                    //because we accept an almost infinite list of possible where conditions, WP
784
-                    // core validation and sanitization freaks out. We'll just validate this argument
785
-                    // while handling the request
786
-                    'validate_callback' => null,
787
-                    'sanitize_callback' => null,
788
-                ),
789
-                'limit'    => array(
790
-                    'required' => false,
791
-                    'default'  => EED_Core_Rest_Api::get_default_query_limit(),
792
-                    'type'     => array(
793
-                        'array',
794
-                        'string',
795
-                        'integer',
796
-                    ),
797
-                    //because we accept a variety of types, WP core validation and sanitization
798
-                    //freaks out. We'll just validate this argument while handling the request
799
-                    'validate_callback' => null,
800
-                    'sanitize_callback' => null,
801
-                ),
802
-                'order_by' => array(
803
-                    'required' => false,
804
-                    'default'  => $default_orderby,
805
-                    'type'     => array(
806
-                        'object',
807
-                        'string',
808
-                    ),//because we accept a variety of types, WP core validation and sanitization
809
-                    //freaks out. We'll just validate this argument while handling the request
810
-                    'validate_callback' => null,
811
-                    'sanitize_callback' => null,
812
-                ),
813
-                'group_by' => array(
814
-                    'required' => false,
815
-                    'default'  => null,
816
-                    'type'     => array(
817
-                        'object',
818
-                        'string',
819
-                    ),
820
-                    //because we accept  an almost infinite list of possible groupings,
821
-                    // WP core validation and sanitization
822
-                    //freaks out. We'll just validate this argument while handling the request
823
-                    'validate_callback' => null,
824
-                    'sanitize_callback' => null,
825
-                ),
826
-                'having'   => array(
827
-                    'required' => false,
828
-                    'default'  => null,
829
-                    'type'     => 'object',
830
-                    //because we accept an almost infinite list of possible where conditions, WP
831
-                    // core validation and sanitization freaks out. We'll just validate this argument
832
-                    // while handling the request
833
-                    'validate_callback' => null,
834
-                    'sanitize_callback' => null,
835
-                ),
836
-                'caps'     => array(
837
-                    'required' => false,
838
-                    'default'  => EEM_Base::caps_read,
839
-                    'type'     => 'string',
840
-                    'enum'     => array(
841
-                        EEM_Base::caps_read,
842
-                        EEM_Base::caps_read_admin,
843
-                        EEM_Base::caps_edit,
844
-                        EEM_Base::caps_delete
845
-                    )
846
-                ),
847
-            )
848
-        );
849
-    }
850
-
851
-
852
-
853
-    /**
854
-     * Gets parameter information for a model regarding writing data
855
-     *
856
-     * @param string           $model_name
857
-     * @param ModelVersionInfo $model_version_info
858
-     * @param boolean          $create                                       whether this is for request to create (in which case we need
859
-     *                                                                       all required params) or just to update (in which case we don't need those on every request)
860
-     * @return array
861
-     */
862
-    protected function _get_write_params(
863
-        $model_name,
864
-        ModelVersionInfo $model_version_info,
865
-        $create = false
866
-    ) {
867
-        $model = EE_Registry::instance()->load_model($model_name);
868
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
869
-        $args_info = array();
870
-        foreach ($fields as $field_name => $field_obj) {
871
-            if ($field_obj->is_auto_increment()) {
872
-                //totally ignore auto increment IDs
873
-                continue;
874
-            }
875
-            $arg_info = $field_obj->getSchema();
876
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
877
-            $arg_info['required'] = $required;
878
-            //remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
879
-            unset($arg_info['readonly']);
880
-            $schema_properties = $field_obj->getSchemaProperties();
881
-            if (
882
-                isset($schema_properties['raw'])
883
-                && $field_obj->getSchemaType() === 'object'
884
-            ) {
885
-                //if there's a "raw" form of this argument, use those properties instead
886
-                $arg_info = array_replace(
887
-                    $arg_info,
888
-                    $schema_properties['raw']
889
-                );
890
-            }
891
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
892
-                $field_obj,
893
-                $field_obj->get_default_value(),
894
-                $model_version_info->requestedVersion()
895
-            );
896
-            //we do our own validation and sanitization within the controller
897
-            if(function_exists('rest_validate_value_from_schema')){
898
-                $sanitize_callback = array(
899
-                    'EED_Core_Rest_Api',
900
-                    'default_sanitize_callback',
901
-                );
902
-            } else {
903
-                $sanitize_callback = null;
904
-            }
905
-            $arg_info['sanitize_callback'] = $sanitize_callback;
906
-            $args_info[$field_name] = $arg_info;
907
-            if ($field_obj instanceof EE_Datetime_Field) {
908
-                $gmt_arg_info = $arg_info;
909
-                $gmt_arg_info['description'] = sprintf(
910
-                    esc_html__(
911
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
912
-                        'event_espresso'
913
-                    ),
914
-                    $field_obj->get_nicename(),
915
-                    $field_name
916
-                );
917
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
918
-            }
919
-        }
920
-        return $args_info;
921
-    }
922
-
923
-
924
-
925
-    /**
926
-     * Replacement for WP API's 'rest_parse_request_arg'.
927
-     * If the value is blank but not required, don't bother validating it.
928
-     * Also, it uses our email validation instead of WP API's default.
929
-     *
930
-     * @param                 $value
931
-     * @param WP_REST_Request $request
932
-     * @param                 $param
933
-     * @return bool|true|WP_Error
934
-     * @throws InvalidArgumentException
935
-     * @throws InvalidInterfaceException
936
-     * @throws InvalidDataTypeException
937
-     */
938
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
939
-    {
940
-        $attributes = $request->get_attributes();
941
-        if (! isset($attributes['args'][$param])
942
-            || ! is_array($attributes['args'][$param])) {
943
-            $validation_result = true;
944
-        } else {
945
-            $args = $attributes['args'][$param];
946
-            if ((
947
-                    $value === ''
948
-                    || $value === null
949
-                )
950
-                && (! isset($args['required'])
951
-                    || $args['required'] === false
952
-                )
953
-            ) {
954
-                //not required and not provided? that's cool
955
-                $validation_result = true;
956
-            } elseif (isset($args['format'])
957
-                && $args['format'] === 'email'
958
-            ) {
959
-                $validation_result = true;
960
-                if (! self::_validate_email($value)) {
961
-                    $validation_result = new WP_Error(
962
-                        'rest_invalid_param',
963
-                        esc_html__(
964
-                            'The email address is not valid or does not exist.',
965
-                            'event_espresso'
966
-                        )
967
-                    );
968
-                }
969
-            } else {
970
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
971
-            }
972
-        }
973
-        if (is_wp_error($validation_result)) {
974
-            return $validation_result;
975
-        }
976
-        return rest_sanitize_request_arg($value, $request, $param);
977
-    }
978
-
979
-
980
-
981
-    /**
982
-     * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
983
-     *
984
-     * @param $email
985
-     * @return bool
986
-     * @throws InvalidArgumentException
987
-     * @throws InvalidInterfaceException
988
-     * @throws InvalidDataTypeException
989
-     */
990
-    protected static function _validate_email($email){
991
-        try {
992
-            EmailAddressFactory::create($email);
993
-            return true;
994
-        } catch (EmailValidationException $e) {
995
-            return false;
996
-        }
997
-    }
998
-
999
-
1000
-
1001
-    /**
1002
-     * Gets routes for the config
1003
-     *
1004
-     * @return array @see _register_model_routes
1005
-     * @deprecated since version 4.9.1
1006
-     */
1007
-    protected function _register_config_routes()
1008
-    {
1009
-        $config_routes = array();
1010
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1011
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1012
-                $version,
1013
-                $hidden_endpoint
1014
-            );
1015
-        }
1016
-        return $config_routes;
1017
-    }
1018
-
1019
-
1020
-
1021
-    /**
1022
-     * Gets routes for the config for the specified version
1023
-     *
1024
-     * @param string  $version
1025
-     * @param boolean $hidden_endpoint
1026
-     * @return array
1027
-     */
1028
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1029
-    {
1030
-        return array(
1031
-            'config'    => array(
1032
-                array(
1033
-                    'callback'        => array(
1034
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1035
-                        'handleRequest',
1036
-                    ),
1037
-                    'methods'         => WP_REST_Server::READABLE,
1038
-                    'hidden_endpoint' => $hidden_endpoint,
1039
-                    'callback_args'   => array($version),
1040
-                ),
1041
-            ),
1042
-            'site_info' => array(
1043
-                array(
1044
-                    'callback'        => array(
1045
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1046
-                        'handleRequestSiteInfo',
1047
-                    ),
1048
-                    'methods'         => WP_REST_Server::READABLE,
1049
-                    'hidden_endpoint' => $hidden_endpoint,
1050
-                    'callback_args'   => array($version),
1051
-                ),
1052
-            ),
1053
-        );
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * Gets the meta info routes
1060
-     *
1061
-     * @return array @see _register_model_routes
1062
-     * @deprecated since version 4.9.1
1063
-     */
1064
-    protected function _register_meta_routes()
1065
-    {
1066
-        $meta_routes = array();
1067
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1068
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1069
-                $version,
1070
-                $hidden_endpoint
1071
-            );
1072
-        }
1073
-        return $meta_routes;
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     * @param string  $version
1080
-     * @param boolean $hidden_endpoint
1081
-     * @return array
1082
-     */
1083
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1084
-    {
1085
-        return array(
1086
-            'resources' => array(
1087
-                array(
1088
-                    'callback'        => array(
1089
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1090
-                        'handleRequestModelsMeta',
1091
-                    ),
1092
-                    'methods'         => WP_REST_Server::READABLE,
1093
-                    'hidden_endpoint' => $hidden_endpoint,
1094
-                    'callback_args'   => array($version),
1095
-                ),
1096
-            ),
1097
-        );
1098
-    }
1099
-
1100
-
1101
-
1102
-    /**
1103
-     * Tries to hide old 4.6 endpoints from the
1104
-     *
1105
-     * @param array $route_data
1106
-     * @return array
1107
-     * @throws \EE_Error
1108
-     */
1109
-    public static function hide_old_endpoints($route_data)
1110
-    {
1111
-        //allow API clients to override which endpoints get hidden, in case
1112
-        //they want to discover particular endpoints
1113
-        //also, we don't have access to the request so we have to just grab it from the superglobal
1114
-        $force_show_ee_namespace = ltrim(
1115
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1116
-            '/'
1117
-        );
1118
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1119
-            foreach ($relative_urls as $resource_name => $endpoints) {
1120
-                foreach ($endpoints as $key => $endpoint) {
1121
-                    //skip schema and other route options
1122
-                    if (! is_numeric($key)) {
1123
-                        continue;
1124
-                    }
1125
-                    //by default, hide "hidden_endpoint"s, unless the request indicates
1126
-                    //to $force_show_ee_namespace, in which case only show that one
1127
-                    //namespace's endpoints (and hide all others)
1128
-                    if (
1129
-                        ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1130
-                        || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1131
-                    ) {
1132
-                        $full_route = '/' . ltrim($namespace, '/');
1133
-                        $full_route .= '/' . ltrim($resource_name, '/');
1134
-                        unset($route_data[$full_route]);
1135
-                    }
1136
-                }
1137
-            }
1138
-        }
1139
-        return $route_data;
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * Returns an array describing which versions of core support serving requests for.
1146
-     * Keys are core versions' major and minor version, and values are the
1147
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1148
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1149
-     * the answers table entirely, in which case it would be very difficult for
1150
-     * it to serve 4.6-style responses.
1151
-     * Versions of core that are missing from this array are unknowns.
1152
-     * previous ver
1153
-     *
1154
-     * @return array
1155
-     */
1156
-    public static function version_compatibilities()
1157
-    {
1158
-        return apply_filters(
1159
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1160
-            array(
1161
-                '4.8.29' => '4.8.29',
1162
-                '4.8.33' => '4.8.29',
1163
-                '4.8.34' => '4.8.29',
1164
-                '4.8.36' => '4.8.29',
1165
-            )
1166
-        );
1167
-    }
1168
-
1169
-
1170
-
1171
-    /**
1172
-     * Gets the latest API version served. Eg if there
1173
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1174
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1175
-     *
1176
-     * @return string
1177
-     */
1178
-    public static function latest_rest_api_version()
1179
-    {
1180
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1181
-        $versions_served_keys = array_keys($versions_served);
1182
-        return end($versions_served_keys);
1183
-    }
1184
-
1185
-
1186
-
1187
-    /**
1188
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1189
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1190
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1191
-     * We also indicate whether or not this version should be put in the index or not
1192
-     *
1193
-     * @return array keys are API version numbers (just major and minor numbers), and values
1194
-     * are whether or not they should be hidden
1195
-     */
1196
-    public static function versions_served()
1197
-    {
1198
-        $versions_served = array();
1199
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1200
-        $lowest_compatible_version = end($possibly_served_versions);
1201
-        reset($possibly_served_versions);
1202
-        $versions_served_historically = array_keys($possibly_served_versions);
1203
-        $latest_version = end($versions_served_historically);
1204
-        reset($versions_served_historically);
1205
-        //for each version of core we have ever served:
1206
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1207
-            //if it's not above the current core version, and it's compatible with the current version of core
1208
-            if ($key_versioned_endpoint === $latest_version) {
1209
-                //don't hide the latest version in the index
1210
-                $versions_served[$key_versioned_endpoint] = false;
1211
-            } elseif (
1212
-                $key_versioned_endpoint >= $lowest_compatible_version
1213
-                && $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1214
-            ) {
1215
-                //include, but hide, previous versions which are still supported
1216
-                $versions_served[$key_versioned_endpoint] = true;
1217
-            } elseif (apply_filters(
1218
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1219
-                false,
1220
-                $possibly_served_versions
1221
-            )) {
1222
-                //if a version is no longer supported, don't include it in index or list of versions served
1223
-                $versions_served[$key_versioned_endpoint] = true;
1224
-            }
1225
-        }
1226
-        return $versions_served;
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets the major and minor version of EE core's version string
1233
-     *
1234
-     * @return string
1235
-     */
1236
-    public static function core_version()
1237
-    {
1238
-        return apply_filters(
1239
-            'FHEE__EED_Core_REST_API__core_version',
1240
-            implode(
1241
-                '.',
1242
-                array_slice(
1243
-                    explode(
1244
-                        '.',
1245
-                        espresso_version()
1246
-                    ),
1247
-                0,
1248
-                3
1249
-                )
1250
-            )
1251
-        );
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Gets the default limit that should be used when querying for resources
1258
-     *
1259
-     * @return int
1260
-     */
1261
-    public static function get_default_query_limit()
1262
-    {
1263
-        //we actually don't use a const because we want folks to always use
1264
-        //this method, not the const directly
1265
-        return apply_filters(
1266
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1267
-            50
1268
-        );
1269
-    }
1270
-
1271
-
1272
-
1273
-    /**
1274
-     *    run - initial module setup
1275
-     *
1276
-     * @access    public
1277
-     * @param  WP $WP
1278
-     * @return    void
1279
-     */
1280
-    public function run($WP)
1281
-    {
1282
-    }
31
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
32
+
33
+	const saved_routes_option_names  = 'ee_core_routes';
34
+
35
+	/**
36
+	 * string used in _links response bodies to make them globally unique.
37
+	 *
38
+	 * @see http://v2.wp-api.org/extending/linking/
39
+	 */
40
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
41
+
42
+	/**
43
+	 * @var CalculatedModelFields
44
+	 */
45
+	protected static $_field_calculator;
46
+
47
+
48
+
49
+	/**
50
+	 * @return EED_Core_Rest_Api|EED_Module
51
+	 */
52
+	public static function instance()
53
+	{
54
+		self::$_field_calculator = new CalculatedModelFields();
55
+		return parent::get_instance(__CLASS__);
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 *    set_hooks - for hooking into EE Core, other modules, etc
62
+	 *
63
+	 * @access    public
64
+	 * @return    void
65
+	 */
66
+	public static function set_hooks()
67
+	{
68
+		self::set_hooks_both();
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
75
+	 *
76
+	 * @access    public
77
+	 * @return    void
78
+	 */
79
+	public static function set_hooks_admin()
80
+	{
81
+		self::set_hooks_both();
82
+	}
83
+
84
+
85
+
86
+	public static function set_hooks_both()
87
+	{
88
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
89
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
90
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
91
+		add_filter('rest_index',
92
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
93
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
94
+	}
95
+
96
+
97
+
98
+	/**
99
+	 * sets up hooks which only need to be included as part of REST API requests;
100
+	 * other requests like to the frontend or admin etc don't need them
101
+	 *
102
+	 * @throws \EE_Error
103
+	 */
104
+	public static function set_hooks_rest_api()
105
+	{
106
+		//set hooks which account for changes made to the API
107
+		EED_Core_Rest_Api::_set_hooks_for_changes();
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * public wrapper of _set_hooks_for_changes.
114
+	 * Loads all the hooks which make requests to old versions of the API
115
+	 * appear the same as they always did
116
+	 *
117
+	 * @throws EE_Error
118
+	 */
119
+	public static function set_hooks_for_changes()
120
+	{
121
+		self::_set_hooks_for_changes();
122
+	}
123
+
124
+
125
+
126
+	/**
127
+	 * Loads all the hooks which make requests to old versions of the API
128
+	 * appear the same as they always did
129
+	 *
130
+	 * @throws EE_Error
131
+	 */
132
+	protected static function _set_hooks_for_changes()
133
+	{
134
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
135
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
136
+			//ignore the base parent class
137
+			//and legacy named classes
138
+			if ($classname_in_namespace === 'ChangesInBase'
139
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
140
+			) {
141
+				continue;
142
+			}
143
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
144
+			if (class_exists($full_classname)) {
145
+				$instance_of_class = new $full_classname;
146
+				if ($instance_of_class instanceof ChangesInBase) {
147
+					$instance_of_class->setHooks();
148
+				}
149
+			}
150
+		}
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
157
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
158
+	 *
159
+	 * @throws \EE_Error
160
+	 */
161
+	public static function register_routes()
162
+	{
163
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
164
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
165
+				/**
166
+				 * @var array $data_for_multiple_endpoints numerically indexed array
167
+				 *                                         but can also contain route options like {
168
+				 * @type array    $schema                      {
169
+				 * @type callable $schema_callback
170
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
171
+				 * WP_REST_Request of course
172
+				 * }
173
+				 * }
174
+				 */
175
+				//when registering routes, register all the endpoints' data at the same time
176
+				$multiple_endpoint_args = array();
177
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
178
+					/**
179
+					 * @var array     $data_for_single_endpoint {
180
+					 * @type callable $callback
181
+					 * @type string methods
182
+					 * @type array args
183
+					 * @type array _links
184
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
185
+					 * WP_REST_Request of course
186
+					 * }
187
+					 */
188
+					//skip route options
189
+					if (! is_numeric($endpoint_key)) {
190
+						continue;
191
+					}
192
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
193
+						throw new EE_Error(
194
+							esc_html__(
195
+								// @codingStandardsIgnoreStart
196
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
197
+								// @codingStandardsIgnoreEnd
198
+								'event_espresso')
199
+						);
200
+					}
201
+					$callback = $data_for_single_endpoint['callback'];
202
+					$single_endpoint_args = array(
203
+						'methods' => $data_for_single_endpoint['methods'],
204
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
205
+							: array(),
206
+					);
207
+					if (isset($data_for_single_endpoint['_links'])) {
208
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
209
+					}
210
+					if (isset($data_for_single_endpoint['callback_args'])) {
211
+						$callback_args = $data_for_single_endpoint['callback_args'];
212
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
213
+							$callback,
214
+							$callback_args
215
+						) {
216
+							array_unshift($callback_args, $request);
217
+							return call_user_func_array(
218
+								$callback,
219
+								$callback_args
220
+							);
221
+						};
222
+					} else {
223
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
224
+					}
225
+					$multiple_endpoint_args[] = $single_endpoint_args;
226
+				}
227
+				if (isset($data_for_multiple_endpoints['schema'])) {
228
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
229
+					$schema_callback = $schema_route_data['schema_callback'];
230
+					$callback_args = $schema_route_data['callback_args'];
231
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
232
+						return call_user_func_array(
233
+							$schema_callback,
234
+							$callback_args
235
+						);
236
+					};
237
+				}
238
+				register_rest_route(
239
+					$namespace,
240
+					$relative_route,
241
+					$multiple_endpoint_args
242
+				);
243
+			}
244
+		}
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Checks if there was a version change or something that merits invalidating the cached
251
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
252
+	 * next time the WP API is used
253
+	 */
254
+	public static function invalidate_cached_route_data_on_version_change()
255
+	{
256
+		if (EE_System::instance()->detect_req_type() !== EE_System::req_type_normal) {
257
+			EED_Core_Rest_Api::invalidate_cached_route_data();
258
+		}
259
+		foreach (EE_Registry::instance()->addons as $addon) {
260
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() !== EE_System::req_type_normal) {
261
+				EED_Core_Rest_Api::invalidate_cached_route_data();
262
+			}
263
+		}
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
270
+	 */
271
+	public static function invalidate_cached_route_data()
272
+	{
273
+		//delete the saved EE REST API routes
274
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
275
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
276
+		}
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * Gets the EE route data
283
+	 *
284
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
285
+	 * @throws \EE_Error
286
+	 * @type string|array $callback
287
+	 * @type string       $methods
288
+	 * @type boolean      $hidden_endpoint
289
+	 * }
290
+	 */
291
+	public static function get_ee_route_data()
292
+	{
293
+		$ee_routes = array();
294
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
295
+			$ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
296
+				$version,
297
+				$hidden_endpoints
298
+			);
299
+		}
300
+		return $ee_routes;
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 * Gets the EE route data from the wp options if it exists already,
307
+	 * otherwise re-generates it and saves it to the option
308
+	 *
309
+	 * @param string  $version
310
+	 * @param boolean $hidden_endpoints
311
+	 * @return array
312
+	 * @throws \EE_Error
313
+	 */
314
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
315
+	{
316
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
317
+		if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
318
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
319
+		}
320
+		return $ee_routes;
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Saves the EE REST API route data to a wp option and returns it
327
+	 *
328
+	 * @param string  $version
329
+	 * @param boolean $hidden_endpoints
330
+	 * @return mixed|null
331
+	 * @throws \EE_Error
332
+	 */
333
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
334
+	{
335
+		$instance = self::instance();
336
+		$routes = apply_filters(
337
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
338
+			array_replace_recursive(
339
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
340
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
341
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
342
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
343
+			)
344
+		);
345
+		$option_name = self::saved_routes_option_names . $version;
346
+		if (get_option($option_name)) {
347
+			update_option($option_name, $routes, true);
348
+		} else {
349
+			add_option($option_name, $routes, null, 'no');
350
+		}
351
+		return $routes;
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
358
+	 * need to calculate it on every request
359
+	 *
360
+	 * @deprecated since version 4.9.1
361
+	 * @return void
362
+	 */
363
+	public static function save_ee_routes()
364
+	{
365
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
366
+			$instance = self::instance();
367
+			$routes = apply_filters(
368
+				'EED_Core_Rest_Api__save_ee_routes__routes',
369
+				array_replace_recursive(
370
+					$instance->_register_config_routes(),
371
+					$instance->_register_meta_routes(),
372
+					$instance->_register_model_routes(),
373
+					$instance->_register_rpc_routes()
374
+				)
375
+			);
376
+			update_option(self::saved_routes_option_names, $routes, true);
377
+		}
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Gets all the route information relating to EE models
384
+	 *
385
+	 * @return array @see get_ee_route_data
386
+	 * @deprecated since version 4.9.1
387
+	 */
388
+	protected function _register_model_routes()
389
+	{
390
+		$model_routes = array();
391
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
392
+			$model_routes[EED_Core_Rest_Api::ee_api_namespace
393
+						  . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
394
+		}
395
+		return $model_routes;
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * Decides whether or not to add write endpoints for this model.
402
+	 *
403
+	 * Currently, this defaults to exclude all global tables and models
404
+	 * which would allow inserting WP core data (we don't want to duplicate
405
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
406
+	 * @param EEM_Base $model
407
+	 * @return bool
408
+	 */
409
+	public static function should_have_write_endpoints(EEM_Base $model)
410
+	{
411
+		if ($model->is_wp_core_model()){
412
+			return false;
413
+		}
414
+		foreach($model->get_tables() as $table){
415
+			if( $table->is_global()){
416
+				return false;
417
+			}
418
+		}
419
+		return true;
420
+	}
421
+
422
+
423
+
424
+	/**
425
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
426
+	 * in this versioned namespace of EE4
427
+	 * @param $version
428
+	 * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
429
+	 */
430
+	public static function model_names_with_plural_routes($version){
431
+		$model_version_info = new ModelVersionInfo($version);
432
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
433
+		//let's not bother having endpoints for extra metas
434
+		unset(
435
+			$models_to_register['Extra_Meta'],
436
+			$models_to_register['Extra_Join'],
437
+			$models_to_register['Post_Meta']
438
+		);
439
+		return apply_filters(
440
+			'FHEE__EED_Core_REST_API___register_model_routes',
441
+			$models_to_register
442
+		);
443
+	}
444
+
445
+
446
+
447
+	/**
448
+	 * Gets the route data for EE models in the specified version
449
+	 *
450
+	 * @param string  $version
451
+	 * @param boolean $hidden_endpoint
452
+	 * @return array
453
+	 * @throws EE_Error
454
+	 */
455
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
456
+	{
457
+		$model_routes = array();
458
+		$model_version_info = new ModelVersionInfo($version);
459
+		foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
460
+			$model = \EE_Registry::instance()->load_model($model_name);
461
+			//if this isn't a valid model then let's skip iterate to the next item in the loop.
462
+			if (! $model instanceof EEM_Base) {
463
+				continue;
464
+			}
465
+			//yes we could just register one route for ALL models, but then they wouldn't show up in the index
466
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model);
467
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model, '(?P<id>[^\/]+)');
468
+			$model_routes[$plural_model_route] = array(
469
+				array(
470
+					'callback'        => array(
471
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
472
+						'handleRequestGetAll',
473
+					),
474
+					'callback_args'   => array($version, $model_name),
475
+					'methods'         => WP_REST_Server::READABLE,
476
+					'hidden_endpoint' => $hidden_endpoint,
477
+					'args'            => $this->_get_read_query_params($model, $version),
478
+					'_links'          => array(
479
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
480
+					),
481
+				),
482
+				'schema' => array(
483
+					'schema_callback' => array(
484
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
485
+						'handleSchemaRequest',
486
+					),
487
+					'callback_args'   => array($version, $model_name),
488
+				),
489
+			);
490
+			$model_routes[$singular_model_route] = array(
491
+				array(
492
+					'callback'        => array(
493
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
494
+						'handleRequestGetOne',
495
+					),
496
+					'callback_args'   => array($version, $model_name),
497
+					'methods'         => WP_REST_Server::READABLE,
498
+					'hidden_endpoint' => $hidden_endpoint,
499
+					'args'            => $this->_get_response_selection_query_params($model, $version),
500
+				),
501
+			);
502
+			if( apply_filters(
503
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
504
+				EED_Core_Rest_Api::should_have_write_endpoints($model),
505
+				$model
506
+			)){
507
+				$model_routes[$plural_model_route][] = array(
508
+					'callback'        => array(
509
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
510
+						'handleRequestInsert',
511
+					),
512
+					'callback_args'   => array($version, $model_name),
513
+					'methods'         => WP_REST_Server::CREATABLE,
514
+					'hidden_endpoint' => $hidden_endpoint,
515
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
516
+				);
517
+				$model_routes[$singular_model_route] = array_merge(
518
+					$model_routes[$singular_model_route],
519
+					array(
520
+						array(
521
+							'callback'        => array(
522
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
523
+								'handleRequestUpdate',
524
+							),
525
+							'callback_args'   => array($version, $model_name),
526
+							'methods'         => WP_REST_Server::EDITABLE,
527
+							'hidden_endpoint' => $hidden_endpoint,
528
+							'args'            => $this->_get_write_params($model_name, $model_version_info),
529
+						),
530
+						array(
531
+							'callback'        => array(
532
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
533
+								'handleRequestDelete',
534
+							),
535
+							'callback_args'   => array($version, $model_name),
536
+							'methods'         => WP_REST_Server::DELETABLE,
537
+							'hidden_endpoint' => $hidden_endpoint,
538
+							'args'            => $this->_get_delete_query_params($model, $version),
539
+						)
540
+					)
541
+				);
542
+			}
543
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
544
+
545
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
546
+					$model,
547
+					'(?P<id>[^\/]+)',
548
+					$relation_obj
549
+				);
550
+				$endpoints = array(
551
+					array(
552
+						'callback'        => array(
553
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
554
+							'handleRequestGetRelated',
555
+						),
556
+						'callback_args'   => array($version, $model_name, $relation_name),
557
+						'methods'         => WP_REST_Server::READABLE,
558
+						'hidden_endpoint' => $hidden_endpoint,
559
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
560
+					),
561
+				);
562
+				$model_routes[$related_route] = $endpoints;
563
+			}
564
+		}
565
+		return $model_routes;
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
572
+	 * excluding the preceding slash.
573
+	 * Eg you pass get_plural_route_to('Event') = 'events'
574
+	 *
575
+	 * @param EEM_Base $model
576
+	 * @return string
577
+	 */
578
+	public static function get_collection_route(EEM_Base $model)
579
+	{
580
+		return EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
587
+	 * excluding the preceding slash.
588
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
589
+	 *
590
+	 * @param EEM_Base $model eg Event or Venue
591
+	 * @param string $id
592
+	 * @return string
593
+	 */
594
+	public static function get_entity_route($model, $id)
595
+	{
596
+		return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
597
+	}
598
+
599
+
600
+	/**
601
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
602
+	 * excluding the preceding slash.
603
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
604
+	 *
605
+	 * @param EEM_Base                 $model eg Event or Venue
606
+	 * @param string                 $id
607
+	 * @param EE_Model_Relation_Base $relation_obj
608
+	 * @return string
609
+	 */
610
+	public static function get_relation_route_via(EEM_Base $model, $id, EE_Model_Relation_Base $relation_obj)
611
+	{
612
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
613
+			$relation_obj->get_other_model()->get_this_model_name(),
614
+			$relation_obj
615
+		);
616
+		return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
617
+	}
618
+
619
+
620
+
621
+	/**
622
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
623
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
624
+	 * @param string $relative_route
625
+	 * @param string $version
626
+	 * @return string
627
+	 */
628
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
629
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
630
+	}
631
+
632
+
633
+
634
+	/**
635
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
636
+	 * routes that don't conform to the traditional REST CRUD-style).
637
+	 *
638
+	 * @deprecated since 4.9.1
639
+	 */
640
+	protected function _register_rpc_routes()
641
+	{
642
+		$routes = array();
643
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
644
+			$routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
645
+				$version,
646
+				$hidden_endpoint
647
+			);
648
+		}
649
+		return $routes;
650
+	}
651
+
652
+
653
+
654
+	/**
655
+	 * @param string  $version
656
+	 * @param boolean $hidden_endpoint
657
+	 * @return array
658
+	 */
659
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
660
+	{
661
+		$this_versions_routes = array();
662
+		//checkin endpoint
663
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
664
+			array(
665
+				'callback'        => array(
666
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
667
+					'handleRequestToggleCheckin',
668
+				),
669
+				'methods'         => WP_REST_Server::CREATABLE,
670
+				'hidden_endpoint' => $hidden_endpoint,
671
+				'args'            => array(
672
+					'force' => array(
673
+						'required'    => false,
674
+						'default'     => false,
675
+						'description' => __(
676
+							// @codingStandardsIgnoreStart
677
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
678
+							// @codingStandardsIgnoreEnd
679
+							'event_espresso'
680
+						),
681
+					),
682
+				),
683
+				'callback_args'   => array($version),
684
+			),
685
+		);
686
+		return apply_filters(
687
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
688
+			$this_versions_routes,
689
+			$version,
690
+			$hidden_endpoint
691
+		);
692
+	}
693
+
694
+
695
+
696
+	/**
697
+	 * Gets the query params that can be used when request one or many
698
+	 *
699
+	 * @param EEM_Base $model
700
+	 * @param string   $version
701
+	 * @return array
702
+	 */
703
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version)
704
+	{
705
+		return apply_filters(
706
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
707
+			array(
708
+				'include'   => array(
709
+					'required' => false,
710
+					'default'  => '*',
711
+					'type'     => 'string',
712
+				),
713
+				'calculate' => array(
714
+					'required'          => false,
715
+					'default'           => '',
716
+					'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
717
+					'type'              => 'string',
718
+					//because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
719
+					//freaks out. We'll just validate this argument while handling the request
720
+					'validate_callback' => null,
721
+					'sanitize_callback' => null,
722
+				),
723
+			),
724
+			$model,
725
+			$version
726
+		);
727
+	}
728
+
729
+
730
+
731
+	/**
732
+	 * Gets the parameters acceptable for delete requests
733
+	 *
734
+	 * @param \EEM_Base $model
735
+	 * @param string    $version
736
+	 * @return array
737
+	 */
738
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
739
+	{
740
+		$params_for_delete = array(
741
+			'allow_blocking' => array(
742
+				'required' => false,
743
+				'default'  => true,
744
+				'type'     => 'boolean',
745
+			),
746
+		);
747
+		$params_for_delete['force'] = array(
748
+			'required' => false,
749
+			'default'  => false,
750
+			'type'     => 'boolean',
751
+		);
752
+		return apply_filters(
753
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
754
+			$params_for_delete,
755
+			$model,
756
+			$version
757
+		);
758
+	}
759
+
760
+
761
+
762
+	/**
763
+	 * Gets info about reading query params that are acceptable
764
+	 *
765
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
766
+	 * @param  string   $version
767
+	 * @return array    describing the args acceptable when querying this model
768
+	 * @throws EE_Error
769
+	 */
770
+	protected function _get_read_query_params(\EEM_Base $model, $version)
771
+	{
772
+		$default_orderby = array();
773
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
774
+			$default_orderby[$key_field->get_name()] = 'ASC';
775
+		}
776
+		return array_merge(
777
+			$this->_get_response_selection_query_params($model, $version),
778
+			array(
779
+				'where'    => array(
780
+					'required' => false,
781
+					'default'  => array(),
782
+					'type'     => 'object',
783
+					//because we accept an almost infinite list of possible where conditions, WP
784
+					// core validation and sanitization freaks out. We'll just validate this argument
785
+					// while handling the request
786
+					'validate_callback' => null,
787
+					'sanitize_callback' => null,
788
+				),
789
+				'limit'    => array(
790
+					'required' => false,
791
+					'default'  => EED_Core_Rest_Api::get_default_query_limit(),
792
+					'type'     => array(
793
+						'array',
794
+						'string',
795
+						'integer',
796
+					),
797
+					//because we accept a variety of types, WP core validation and sanitization
798
+					//freaks out. We'll just validate this argument while handling the request
799
+					'validate_callback' => null,
800
+					'sanitize_callback' => null,
801
+				),
802
+				'order_by' => array(
803
+					'required' => false,
804
+					'default'  => $default_orderby,
805
+					'type'     => array(
806
+						'object',
807
+						'string',
808
+					),//because we accept a variety of types, WP core validation and sanitization
809
+					//freaks out. We'll just validate this argument while handling the request
810
+					'validate_callback' => null,
811
+					'sanitize_callback' => null,
812
+				),
813
+				'group_by' => array(
814
+					'required' => false,
815
+					'default'  => null,
816
+					'type'     => array(
817
+						'object',
818
+						'string',
819
+					),
820
+					//because we accept  an almost infinite list of possible groupings,
821
+					// WP core validation and sanitization
822
+					//freaks out. We'll just validate this argument while handling the request
823
+					'validate_callback' => null,
824
+					'sanitize_callback' => null,
825
+				),
826
+				'having'   => array(
827
+					'required' => false,
828
+					'default'  => null,
829
+					'type'     => 'object',
830
+					//because we accept an almost infinite list of possible where conditions, WP
831
+					// core validation and sanitization freaks out. We'll just validate this argument
832
+					// while handling the request
833
+					'validate_callback' => null,
834
+					'sanitize_callback' => null,
835
+				),
836
+				'caps'     => array(
837
+					'required' => false,
838
+					'default'  => EEM_Base::caps_read,
839
+					'type'     => 'string',
840
+					'enum'     => array(
841
+						EEM_Base::caps_read,
842
+						EEM_Base::caps_read_admin,
843
+						EEM_Base::caps_edit,
844
+						EEM_Base::caps_delete
845
+					)
846
+				),
847
+			)
848
+		);
849
+	}
850
+
851
+
852
+
853
+	/**
854
+	 * Gets parameter information for a model regarding writing data
855
+	 *
856
+	 * @param string           $model_name
857
+	 * @param ModelVersionInfo $model_version_info
858
+	 * @param boolean          $create                                       whether this is for request to create (in which case we need
859
+	 *                                                                       all required params) or just to update (in which case we don't need those on every request)
860
+	 * @return array
861
+	 */
862
+	protected function _get_write_params(
863
+		$model_name,
864
+		ModelVersionInfo $model_version_info,
865
+		$create = false
866
+	) {
867
+		$model = EE_Registry::instance()->load_model($model_name);
868
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
869
+		$args_info = array();
870
+		foreach ($fields as $field_name => $field_obj) {
871
+			if ($field_obj->is_auto_increment()) {
872
+				//totally ignore auto increment IDs
873
+				continue;
874
+			}
875
+			$arg_info = $field_obj->getSchema();
876
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
877
+			$arg_info['required'] = $required;
878
+			//remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
879
+			unset($arg_info['readonly']);
880
+			$schema_properties = $field_obj->getSchemaProperties();
881
+			if (
882
+				isset($schema_properties['raw'])
883
+				&& $field_obj->getSchemaType() === 'object'
884
+			) {
885
+				//if there's a "raw" form of this argument, use those properties instead
886
+				$arg_info = array_replace(
887
+					$arg_info,
888
+					$schema_properties['raw']
889
+				);
890
+			}
891
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
892
+				$field_obj,
893
+				$field_obj->get_default_value(),
894
+				$model_version_info->requestedVersion()
895
+			);
896
+			//we do our own validation and sanitization within the controller
897
+			if(function_exists('rest_validate_value_from_schema')){
898
+				$sanitize_callback = array(
899
+					'EED_Core_Rest_Api',
900
+					'default_sanitize_callback',
901
+				);
902
+			} else {
903
+				$sanitize_callback = null;
904
+			}
905
+			$arg_info['sanitize_callback'] = $sanitize_callback;
906
+			$args_info[$field_name] = $arg_info;
907
+			if ($field_obj instanceof EE_Datetime_Field) {
908
+				$gmt_arg_info = $arg_info;
909
+				$gmt_arg_info['description'] = sprintf(
910
+					esc_html__(
911
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
912
+						'event_espresso'
913
+					),
914
+					$field_obj->get_nicename(),
915
+					$field_name
916
+				);
917
+				$args_info[$field_name . '_gmt'] = $gmt_arg_info;
918
+			}
919
+		}
920
+		return $args_info;
921
+	}
922
+
923
+
924
+
925
+	/**
926
+	 * Replacement for WP API's 'rest_parse_request_arg'.
927
+	 * If the value is blank but not required, don't bother validating it.
928
+	 * Also, it uses our email validation instead of WP API's default.
929
+	 *
930
+	 * @param                 $value
931
+	 * @param WP_REST_Request $request
932
+	 * @param                 $param
933
+	 * @return bool|true|WP_Error
934
+	 * @throws InvalidArgumentException
935
+	 * @throws InvalidInterfaceException
936
+	 * @throws InvalidDataTypeException
937
+	 */
938
+	public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
939
+	{
940
+		$attributes = $request->get_attributes();
941
+		if (! isset($attributes['args'][$param])
942
+			|| ! is_array($attributes['args'][$param])) {
943
+			$validation_result = true;
944
+		} else {
945
+			$args = $attributes['args'][$param];
946
+			if ((
947
+					$value === ''
948
+					|| $value === null
949
+				)
950
+				&& (! isset($args['required'])
951
+					|| $args['required'] === false
952
+				)
953
+			) {
954
+				//not required and not provided? that's cool
955
+				$validation_result = true;
956
+			} elseif (isset($args['format'])
957
+				&& $args['format'] === 'email'
958
+			) {
959
+				$validation_result = true;
960
+				if (! self::_validate_email($value)) {
961
+					$validation_result = new WP_Error(
962
+						'rest_invalid_param',
963
+						esc_html__(
964
+							'The email address is not valid or does not exist.',
965
+							'event_espresso'
966
+						)
967
+					);
968
+				}
969
+			} else {
970
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
971
+			}
972
+		}
973
+		if (is_wp_error($validation_result)) {
974
+			return $validation_result;
975
+		}
976
+		return rest_sanitize_request_arg($value, $request, $param);
977
+	}
978
+
979
+
980
+
981
+	/**
982
+	 * Returns whether or not this email address is valid. Copied from EE_Email_Validation_Strategy::_validate_email()
983
+	 *
984
+	 * @param $email
985
+	 * @return bool
986
+	 * @throws InvalidArgumentException
987
+	 * @throws InvalidInterfaceException
988
+	 * @throws InvalidDataTypeException
989
+	 */
990
+	protected static function _validate_email($email){
991
+		try {
992
+			EmailAddressFactory::create($email);
993
+			return true;
994
+		} catch (EmailValidationException $e) {
995
+			return false;
996
+		}
997
+	}
998
+
999
+
1000
+
1001
+	/**
1002
+	 * Gets routes for the config
1003
+	 *
1004
+	 * @return array @see _register_model_routes
1005
+	 * @deprecated since version 4.9.1
1006
+	 */
1007
+	protected function _register_config_routes()
1008
+	{
1009
+		$config_routes = array();
1010
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1011
+			$config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1012
+				$version,
1013
+				$hidden_endpoint
1014
+			);
1015
+		}
1016
+		return $config_routes;
1017
+	}
1018
+
1019
+
1020
+
1021
+	/**
1022
+	 * Gets routes for the config for the specified version
1023
+	 *
1024
+	 * @param string  $version
1025
+	 * @param boolean $hidden_endpoint
1026
+	 * @return array
1027
+	 */
1028
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1029
+	{
1030
+		return array(
1031
+			'config'    => array(
1032
+				array(
1033
+					'callback'        => array(
1034
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1035
+						'handleRequest',
1036
+					),
1037
+					'methods'         => WP_REST_Server::READABLE,
1038
+					'hidden_endpoint' => $hidden_endpoint,
1039
+					'callback_args'   => array($version),
1040
+				),
1041
+			),
1042
+			'site_info' => array(
1043
+				array(
1044
+					'callback'        => array(
1045
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1046
+						'handleRequestSiteInfo',
1047
+					),
1048
+					'methods'         => WP_REST_Server::READABLE,
1049
+					'hidden_endpoint' => $hidden_endpoint,
1050
+					'callback_args'   => array($version),
1051
+				),
1052
+			),
1053
+		);
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * Gets the meta info routes
1060
+	 *
1061
+	 * @return array @see _register_model_routes
1062
+	 * @deprecated since version 4.9.1
1063
+	 */
1064
+	protected function _register_meta_routes()
1065
+	{
1066
+		$meta_routes = array();
1067
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1068
+			$meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1069
+				$version,
1070
+				$hidden_endpoint
1071
+			);
1072
+		}
1073
+		return $meta_routes;
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 * @param string  $version
1080
+	 * @param boolean $hidden_endpoint
1081
+	 * @return array
1082
+	 */
1083
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1084
+	{
1085
+		return array(
1086
+			'resources' => array(
1087
+				array(
1088
+					'callback'        => array(
1089
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1090
+						'handleRequestModelsMeta',
1091
+					),
1092
+					'methods'         => WP_REST_Server::READABLE,
1093
+					'hidden_endpoint' => $hidden_endpoint,
1094
+					'callback_args'   => array($version),
1095
+				),
1096
+			),
1097
+		);
1098
+	}
1099
+
1100
+
1101
+
1102
+	/**
1103
+	 * Tries to hide old 4.6 endpoints from the
1104
+	 *
1105
+	 * @param array $route_data
1106
+	 * @return array
1107
+	 * @throws \EE_Error
1108
+	 */
1109
+	public static function hide_old_endpoints($route_data)
1110
+	{
1111
+		//allow API clients to override which endpoints get hidden, in case
1112
+		//they want to discover particular endpoints
1113
+		//also, we don't have access to the request so we have to just grab it from the superglobal
1114
+		$force_show_ee_namespace = ltrim(
1115
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1116
+			'/'
1117
+		);
1118
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1119
+			foreach ($relative_urls as $resource_name => $endpoints) {
1120
+				foreach ($endpoints as $key => $endpoint) {
1121
+					//skip schema and other route options
1122
+					if (! is_numeric($key)) {
1123
+						continue;
1124
+					}
1125
+					//by default, hide "hidden_endpoint"s, unless the request indicates
1126
+					//to $force_show_ee_namespace, in which case only show that one
1127
+					//namespace's endpoints (and hide all others)
1128
+					if (
1129
+						($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1130
+						|| ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1131
+					) {
1132
+						$full_route = '/' . ltrim($namespace, '/');
1133
+						$full_route .= '/' . ltrim($resource_name, '/');
1134
+						unset($route_data[$full_route]);
1135
+					}
1136
+				}
1137
+			}
1138
+		}
1139
+		return $route_data;
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * Returns an array describing which versions of core support serving requests for.
1146
+	 * Keys are core versions' major and minor version, and values are the
1147
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1148
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1149
+	 * the answers table entirely, in which case it would be very difficult for
1150
+	 * it to serve 4.6-style responses.
1151
+	 * Versions of core that are missing from this array are unknowns.
1152
+	 * previous ver
1153
+	 *
1154
+	 * @return array
1155
+	 */
1156
+	public static function version_compatibilities()
1157
+	{
1158
+		return apply_filters(
1159
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1160
+			array(
1161
+				'4.8.29' => '4.8.29',
1162
+				'4.8.33' => '4.8.29',
1163
+				'4.8.34' => '4.8.29',
1164
+				'4.8.36' => '4.8.29',
1165
+			)
1166
+		);
1167
+	}
1168
+
1169
+
1170
+
1171
+	/**
1172
+	 * Gets the latest API version served. Eg if there
1173
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1174
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1175
+	 *
1176
+	 * @return string
1177
+	 */
1178
+	public static function latest_rest_api_version()
1179
+	{
1180
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1181
+		$versions_served_keys = array_keys($versions_served);
1182
+		return end($versions_served_keys);
1183
+	}
1184
+
1185
+
1186
+
1187
+	/**
1188
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1189
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1190
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1191
+	 * We also indicate whether or not this version should be put in the index or not
1192
+	 *
1193
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1194
+	 * are whether or not they should be hidden
1195
+	 */
1196
+	public static function versions_served()
1197
+	{
1198
+		$versions_served = array();
1199
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1200
+		$lowest_compatible_version = end($possibly_served_versions);
1201
+		reset($possibly_served_versions);
1202
+		$versions_served_historically = array_keys($possibly_served_versions);
1203
+		$latest_version = end($versions_served_historically);
1204
+		reset($versions_served_historically);
1205
+		//for each version of core we have ever served:
1206
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1207
+			//if it's not above the current core version, and it's compatible with the current version of core
1208
+			if ($key_versioned_endpoint === $latest_version) {
1209
+				//don't hide the latest version in the index
1210
+				$versions_served[$key_versioned_endpoint] = false;
1211
+			} elseif (
1212
+				$key_versioned_endpoint >= $lowest_compatible_version
1213
+				&& $key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1214
+			) {
1215
+				//include, but hide, previous versions which are still supported
1216
+				$versions_served[$key_versioned_endpoint] = true;
1217
+			} elseif (apply_filters(
1218
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1219
+				false,
1220
+				$possibly_served_versions
1221
+			)) {
1222
+				//if a version is no longer supported, don't include it in index or list of versions served
1223
+				$versions_served[$key_versioned_endpoint] = true;
1224
+			}
1225
+		}
1226
+		return $versions_served;
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets the major and minor version of EE core's version string
1233
+	 *
1234
+	 * @return string
1235
+	 */
1236
+	public static function core_version()
1237
+	{
1238
+		return apply_filters(
1239
+			'FHEE__EED_Core_REST_API__core_version',
1240
+			implode(
1241
+				'.',
1242
+				array_slice(
1243
+					explode(
1244
+						'.',
1245
+						espresso_version()
1246
+					),
1247
+				0,
1248
+				3
1249
+				)
1250
+			)
1251
+		);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Gets the default limit that should be used when querying for resources
1258
+	 *
1259
+	 * @return int
1260
+	 */
1261
+	public static function get_default_query_limit()
1262
+	{
1263
+		//we actually don't use a const because we want folks to always use
1264
+		//this method, not the const directly
1265
+		return apply_filters(
1266
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1267
+			50
1268
+		);
1269
+	}
1270
+
1271
+
1272
+
1273
+	/**
1274
+	 *    run - initial module setup
1275
+	 *
1276
+	 * @access    public
1277
+	 * @param  WP $WP
1278
+	 * @return    void
1279
+	 */
1280
+	public function run($WP)
1281
+	{
1282
+	}
1283 1283
 }
1284 1284
 
1285 1285
 // End of file EED_Core_Rest_Api.module.php
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     protected static function _set_hooks_for_changes()
133 133
     {
134
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
134
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api'.DS.'changes'), false);
135 135
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
136 136
             //ignore the base parent class
137 137
             //and legacy named classes
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
             ) {
141 141
                 continue;
142 142
             }
143
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
143
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
144 144
             if (class_exists($full_classname)) {
145 145
                 $instance_of_class = new $full_classname;
146 146
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -186,10 +186,10 @@  discard block
 block discarded – undo
186 186
                      * }
187 187
                      */
188 188
                     //skip route options
189
-                    if (! is_numeric($endpoint_key)) {
189
+                    if ( ! is_numeric($endpoint_key)) {
190 190
                         continue;
191 191
                     }
192
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
192
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
193 193
                         throw new EE_Error(
194 194
                             esc_html__(
195 195
                                 // @codingStandardsIgnoreStart
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
                     }
210 210
                     if (isset($data_for_single_endpoint['callback_args'])) {
211 211
                         $callback_args = $data_for_single_endpoint['callback_args'];
212
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
212
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
213 213
                             $callback,
214 214
                             $callback_args
215 215
                         ) {
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
229 229
                     $schema_callback = $schema_route_data['schema_callback'];
230 230
                     $callback_args = $schema_route_data['callback_args'];
231
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
231
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
232 232
                         return call_user_func_array(
233 233
                             $schema_callback,
234 234
                             $callback_args
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
     {
273 273
         //delete the saved EE REST API routes
274 274
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
275
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
275
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
276 276
         }
277 277
     }
278 278
 
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
     {
293 293
         $ee_routes = array();
294 294
         foreach (self::versions_served() as $version => $hidden_endpoints) {
295
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
295
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
296 296
                 $version,
297 297
                 $hidden_endpoints
298 298
             );
@@ -313,8 +313,8 @@  discard block
 block discarded – undo
313 313
      */
314 314
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
315 315
     {
316
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
317
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
316
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
317
+        if ( ! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
318 318
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
319 319
         }
320 320
         return $ee_routes;
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
343 343
             )
344 344
         );
345
-        $option_name = self::saved_routes_option_names . $version;
345
+        $option_name = self::saved_routes_option_names.$version;
346 346
         if (get_option($option_name)) {
347 347
             update_option($option_name, $routes, true);
348 348
         } else {
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
      */
409 409
     public static function should_have_write_endpoints(EEM_Base $model)
410 410
     {
411
-        if ($model->is_wp_core_model()){
411
+        if ($model->is_wp_core_model()) {
412 412
             return false;
413 413
         }
414
-        foreach($model->get_tables() as $table){
415
-            if( $table->is_global()){
414
+        foreach ($model->get_tables() as $table) {
415
+            if ($table->is_global()) {
416 416
                 return false;
417 417
             }
418 418
         }
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
      * @param $version
428 428
      * @return array keys are model names (eg 'Event') and values ar either classnames (eg 'EEM_Event')
429 429
      */
430
-    public static function model_names_with_plural_routes($version){
430
+    public static function model_names_with_plural_routes($version) {
431 431
         $model_version_info = new ModelVersionInfo($version);
432 432
         $models_to_register = $model_version_info->modelsForRequestedVersion();
433 433
         //let's not bother having endpoints for extra metas
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
         foreach (EED_Core_Rest_Api::model_names_with_plural_routes($version) as $model_name => $model_classname) {
460 460
             $model = \EE_Registry::instance()->load_model($model_name);
461 461
             //if this isn't a valid model then let's skip iterate to the next item in the loop.
462
-            if (! $model instanceof EEM_Base) {
462
+            if ( ! $model instanceof EEM_Base) {
463 463
                 continue;
464 464
             }
465 465
             //yes we could just register one route for ALL models, but then they wouldn't show up in the index
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
                     'hidden_endpoint' => $hidden_endpoint,
477 477
                     'args'            => $this->_get_read_query_params($model, $version),
478 478
                     '_links'          => array(
479
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
479
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
480 480
                     ),
481 481
                 ),
482 482
                 'schema' => array(
@@ -499,11 +499,11 @@  discard block
 block discarded – undo
499 499
                     'args'            => $this->_get_response_selection_query_params($model, $version),
500 500
                 ),
501 501
             );
502
-            if( apply_filters(
502
+            if (apply_filters(
503 503
                 'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
504 504
                 EED_Core_Rest_Api::should_have_write_endpoints($model),
505 505
                 $model
506
-            )){
506
+            )) {
507 507
                 $model_routes[$plural_model_route][] = array(
508 508
                     'callback'        => array(
509 509
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
      */
594 594
     public static function get_entity_route($model, $id)
595 595
     {
596
-        return EED_Core_Rest_Api::get_collection_route($model). '/' . $id;
596
+        return EED_Core_Rest_Api::get_collection_route($model).'/'.$id;
597 597
     }
598 598
 
599 599
 
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
             $relation_obj->get_other_model()->get_this_model_name(),
614 614
             $relation_obj
615 615
         );
616
-        return EED_Core_Rest_Api::get_entity_route($model, $id) . '/' . $related_model_name_endpoint_part;
616
+        return EED_Core_Rest_Api::get_entity_route($model, $id).'/'.$related_model_name_endpoint_part;
617 617
     }
618 618
 
619 619
 
@@ -625,8 +625,8 @@  discard block
 block discarded – undo
625 625
      * @param string $version
626 626
      * @return string
627 627
      */
628
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
629
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
628
+    public static function get_versioned_route_to($relative_route, $version = '4.8.36') {
629
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
630 630
     }
631 631
 
632 632
 
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
     {
642 642
         $routes = array();
643 643
         foreach (self::versions_served() as $version => $hidden_endpoint) {
644
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
644
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
645 645
                 $version,
646 646
                 $hidden_endpoint
647 647
             );
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
                     'type'     => array(
806 806
                         'object',
807 807
                         'string',
808
-                    ),//because we accept a variety of types, WP core validation and sanitization
808
+                    ), //because we accept a variety of types, WP core validation and sanitization
809 809
                     //freaks out. We'll just validate this argument while handling the request
810 810
                     'validate_callback' => null,
811 811
                     'sanitize_callback' => null,
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
                 $model_version_info->requestedVersion()
895 895
             );
896 896
             //we do our own validation and sanitization within the controller
897
-            if(function_exists('rest_validate_value_from_schema')){
897
+            if (function_exists('rest_validate_value_from_schema')) {
898 898
                 $sanitize_callback = array(
899 899
                     'EED_Core_Rest_Api',
900 900
                     'default_sanitize_callback',
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
                     $field_obj->get_nicename(),
915 915
                     $field_name
916 916
                 );
917
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
917
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
918 918
             }
919 919
         }
920 920
         return $args_info;
@@ -935,10 +935,10 @@  discard block
 block discarded – undo
935 935
      * @throws InvalidInterfaceException
936 936
      * @throws InvalidDataTypeException
937 937
      */
938
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
938
+    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
939 939
     {
940 940
         $attributes = $request->get_attributes();
941
-        if (! isset($attributes['args'][$param])
941
+        if ( ! isset($attributes['args'][$param])
942 942
             || ! is_array($attributes['args'][$param])) {
943 943
             $validation_result = true;
944 944
         } else {
@@ -947,7 +947,7 @@  discard block
 block discarded – undo
947 947
                     $value === ''
948 948
                     || $value === null
949 949
                 )
950
-                && (! isset($args['required'])
950
+                && ( ! isset($args['required'])
951 951
                     || $args['required'] === false
952 952
                 )
953 953
             ) {
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
                 && $args['format'] === 'email'
958 958
             ) {
959 959
                 $validation_result = true;
960
-                if (! self::_validate_email($value)) {
960
+                if ( ! self::_validate_email($value)) {
961 961
                     $validation_result = new WP_Error(
962 962
                         'rest_invalid_param',
963 963
                         esc_html__(
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
      * @throws InvalidInterfaceException
988 988
      * @throws InvalidDataTypeException
989 989
      */
990
-    protected static function _validate_email($email){
990
+    protected static function _validate_email($email) {
991 991
         try {
992 992
             EmailAddressFactory::create($email);
993 993
             return true;
@@ -1008,7 +1008,7 @@  discard block
 block discarded – undo
1008 1008
     {
1009 1009
         $config_routes = array();
1010 1010
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1011
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
1011
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
1012 1012
                 $version,
1013 1013
                 $hidden_endpoint
1014 1014
             );
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
     {
1066 1066
         $meta_routes = array();
1067 1067
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1068
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1068
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1069 1069
                 $version,
1070 1070
                 $hidden_endpoint
1071 1071
             );
@@ -1119,7 +1119,7 @@  discard block
 block discarded – undo
1119 1119
             foreach ($relative_urls as $resource_name => $endpoints) {
1120 1120
                 foreach ($endpoints as $key => $endpoint) {
1121 1121
                     //skip schema and other route options
1122
-                    if (! is_numeric($key)) {
1122
+                    if ( ! is_numeric($key)) {
1123 1123
                         continue;
1124 1124
                     }
1125 1125
                     //by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1129,8 +1129,8 @@  discard block
 block discarded – undo
1129 1129
                         ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1130 1130
                         || ($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1131 1131
                     ) {
1132
-                        $full_route = '/' . ltrim($namespace, '/');
1133
-                        $full_route .= '/' . ltrim($resource_name, '/');
1132
+                        $full_route = '/'.ltrim($namespace, '/');
1133
+                        $full_route .= '/'.ltrim($resource_name, '/');
1134 1134
                         unset($route_data[$full_route]);
1135 1135
                     }
1136 1136
                 }
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelectorRowStandard.php 2 patches
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -21,369 +21,369 @@
 block discarded – undo
21 21
 class TicketSelectorRowStandard extends TicketSelectorRow
22 22
 {
23 23
 
24
-    /**
25
-     * @var TicketDetails $ticket_details
26
-     */
27
-    protected $ticket_details;
28
-
29
-    /**
30
-     * @var \EE_Ticket_Selector_Config $template_settings
31
-     */
32
-    protected $template_settings;
33
-
34
-    /**
35
-     * @var EE_Tax_Config $tax_settings
36
-     */
37
-    protected $tax_settings;
38
-
39
-    /**
40
-     * @var boolean $prices_displayed_including_taxes
41
-     */
42
-    protected $prices_displayed_including_taxes;
43
-
44
-    /**
45
-     * @var int $row
46
-     */
47
-    protected $row;
48
-
49
-    /**
50
-     * @var int $cols
51
-     */
52
-    protected $cols;
53
-
54
-    /**
55
-     * @var boolean $hidden_input_qty
56
-     */
57
-    protected $hidden_input_qty;
58
-
59
-    /**
60
-     * @var string $ticket_datetime_classes
61
-     */
62
-    protected $ticket_datetime_classes;
63
-
64
-
65
-
66
-    /**
67
-     * TicketDetails constructor.
68
-     *
69
-     * @param TicketDetails  $ticket_details
70
-     * @param EE_Tax_Config $tax_settings
71
-     * @param int            $total_tickets
72
-     * @param int            $max_attendees
73
-     * @param int            $row
74
-     * @param int            $cols
75
-     * @param boolean        $required_ticket_sold_out
76
-     * @param string         $event_status
77
-     * @param string         $ticket_datetime_classes
78
-     * @throws EE_Error
79
-     * @throws UnexpectedEntityException
80
-     */
81
-    public function __construct(
82
-        TicketDetails $ticket_details,
83
-        EE_Tax_Config $tax_settings,
84
-        $total_tickets,
85
-        $max_attendees,
86
-        $row,
87
-        $cols,
88
-        $required_ticket_sold_out,
89
-        $event_status,
90
-        $ticket_datetime_classes
91
-    ) {
92
-        $this->ticket_details = $ticket_details;
93
-        $this->template_settings = $ticket_details->getTemplateSettings();
94
-        $this->tax_settings = $tax_settings;
95
-        $this->row = $row;
96
-        $this->cols = $cols;
97
-        $this->ticket_datetime_classes = $ticket_datetime_classes;
98
-        parent::__construct(
99
-            $ticket_details->getTicket(),
100
-            $max_attendees,
101
-            $ticket_details->getDateFormat(),
102
-            $event_status,
103
-            $required_ticket_sold_out,
104
-            $total_tickets
105
-        );
106
-    }
107
-
108
-
109
-
110
-    /**
111
-     * other ticket rows will need to know if a required ticket is sold out,
112
-     * so that they are not offered for sale
113
-     *
114
-     * @return boolean
115
-     */
116
-    public function getRequiredTicketSoldOut()
117
-    {
118
-        return $this->required_ticket_sold_out;
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * @return int
125
-     */
126
-    public function getCols()
127
-    {
128
-        return $this->cols;
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * getHtml
135
-     *
136
-     * @return string
137
-     * @throws EE_Error
138
-     */
139
-    public function getHtml()
140
-    {
141
-        $this->min = 0;
142
-        $this->max = $this->ticket->max();
143
-        $remaining = $this->ticket->remaining();
144
-        if ($this->ticket->is_on_sale() && $this->ticket->is_remaining()) {
145
-             $this->setTicketMinAndMax($remaining);
146
-        } else {
147
-            // set flag if ticket is required (flag is set to start date so that future tickets are not blocked)
148
-            $this->required_ticket_sold_out = $this->ticket->required() && ! $remaining
149
-                ? $this->ticket->start_date()
150
-                : $this->required_ticket_sold_out;
151
-        }
152
-        $this->setTicketPriceDetails();
153
-        $this->setTicketStatusClasses($remaining);
154
-        $filtered_row_html = $this->getFilteredRowHtml();
155
-        if ($filtered_row_html !== false) {
156
-            return $filtered_row_html;
157
-        }
158
-        $ticket_selector_row_html = EEH_HTML::tr(
159
-            '', '',
160
-            "tckt-slctr-tbl-tr {$this->status_class}{$this->ticket_datetime_classes} "
161
-            . espresso_get_object_css_class($this->ticket)
162
-        );
163
-        $filtered_row_content = $this->getFilteredRowContents();
164
-        if ($filtered_row_content !== false && $this->max_attendees === 1) {
165
-            return $ticket_selector_row_html
166
-                   . $filtered_row_content
167
-                   . $this->ticketQtyAndIdHiddenInputs()
168
-                   . EEH_HTML::trx();
169
-        }
170
-        if ($filtered_row_content !== false) {
171
-            return $ticket_selector_row_html
172
-                   . $filtered_row_content
173
-                   . EEH_HTML::trx();
174
-        }
175
-        $this->hidden_input_qty = $this->max_attendees > 1;
176
-
177
-        $ticket_selector_row_html .= $this->ticketNameTableCell();
178
-        $ticket_selector_row_html .= $this->ticketPriceTableCell();
179
-        $ticket_selector_row_html .= EEH_HTML::td(
180
-            '', 
181
-            '', 
182
-            'tckt-slctr-tbl-td-qty cntr',
183
-            '',
184
-            'headers="quantity-' . $this->EVT_ID . '"'
185
-        );
186
-        $this->setTicketStatusDisplay($remaining);
187
-        if (empty($this->ticket_status_display)) {
188
-            if ($this->max_attendees === 1) {
189
-                // only ONE attendee is allowed to register at a time
190
-                $ticket_selector_row_html .= $this->onlyOneAttendeeCanRegister();
191
-            } elseif ($this->max > 0) {
192
-                $ticket_selector_row_html .= $this->ticketQuantitySelector();
193
-            }
194
-        }
195
-        $ticket_selector_row_html .= $this->ticket_status_display;
196
-        $ticket_selector_row_html .= $this->ticketQtyAndIdHiddenInputs();
197
-        $ticket_selector_row_html .= $this->ticket_details->display(
198
-            $this->ticket_price,
199
-            $remaining,
200
-            $this->cols
201
-        );
202
-        $ticket_selector_row_html .= EEH_HTML::tdx();
203
-        $ticket_selector_row_html .= EEH_HTML::trx();
204
-
205
-
206
-        $this->row++;
207
-        return $ticket_selector_row_html;
208
-    }
209
-
210
-
211
-
212
-
213
-    /**
214
-     * getTicketPriceDetails
215
-     *
216
-     * @return void
217
-     * @throws EE_Error
218
-     */
219
-    protected function setTicketPriceDetails()
220
-    {
221
-        $this->ticket_price = $this->tax_settings->prices_displayed_including_taxes
222
-            ? $this->ticket->get_ticket_total_with_taxes()
223
-            : $this->ticket->get_ticket_subtotal();
224
-        $this->ticket_bundle = false;
225
-        $ticket_min = $this->ticket->min();
226
-        // for ticket bundles, set min and max qty the same
227
-        if ($ticket_min !== 0 && $ticket_min === $this->ticket->max()) {
228
-            $this->ticket_price *= $ticket_min;
229
-            $this->ticket_bundle = true;
230
-        }
231
-        $this->ticket_price = apply_filters(
232
-            'FHEE__ticket_selector_chart_template__ticket_price',
233
-            $this->ticket_price,
234
-            $this->ticket
235
-        );
236
-    }
237
-
238
-
239
-
240
-
241
-    /**
242
-     * ticketNameTableCell
243
-     *
244
-     * @return string
245
-     * @throws EE_Error
246
-     */
247
-    protected function ticketNameTableCell()
248
-    {
249
-        $html = EEH_HTML::td(
250
-            '', 
251
-            '', 
252
-            'tckt-slctr-tbl-td-name', 
253
-            '', 
254
-            'headers="details-' . $this->EVT_ID . '"'
255
-        );
256
-        $html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
257
-        $html .= $this->ticket_details->getShowHideLinks();
258
-        if ($this->ticket->required()) {
259
-            $html .= EEH_HTML::p(
260
-                apply_filters(
261
-                        'FHEE__ticket_selector_chart_template__ticket_required_message',
262
-                        esc_html__('This ticket is required and must be purchased.', 'event_espresso')
263
-                ),
264
-                '', 'ticket-required-pg'
265
-            );
266
-        }
267
-        $html .= EEH_HTML::tdx();
268
-        return $html;
269
-    }
270
-
271
-
272
-
273
-    /**
274
-     * ticketPriceTableCell
275
-     *
276
-     * @return string
277
-     * @throws EE_Error
278
-     */
279
-    protected function ticketPriceTableCell()
280
-    {
281
-        $html = '';
282
-        if (apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', true)) {
283
-            $html .= EEH_HTML::td(
284
-                '', 
285
-                '', 
286
-                'tckt-slctr-tbl-td-price jst-rght', 
287
-                '', 
288
-                'headers="price-' . $this->EVT_ID . '"'
289
-            );
290
-            $html .= \EEH_Template::format_currency($this->ticket_price);
291
-            $html .= $this->ticket->taxable()
292
-                ? EEH_HTML::span( '*', '', 'taxable-tickets-asterisk grey-text' )
293
-                : '';
294
-            $html .= '&nbsp;';
295
-            $html .= EEH_HTML::span(
296
-                $this->ticket_bundle
297
-                    ? apply_filters(
298
-                        'FHEE__ticket_selector_chart_template__per_ticket_bundle_text',
299
-                        __(' / bundle', 'event_espresso')
300
-                    )
301
-                    : apply_filters(
302
-                        'FHEE__ticket_selector_chart_template__per_ticket_text',
303
-                        __('', 'event_espresso')
304
-                    ),
305
-                '', 'smaller-text no-bold'
306
-            );
307
-            $html .= '&nbsp;';
308
-            $html .= EEH_HTML::tdx();
309
-            $this->cols++;
310
-        }
311
-        return $html;
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * onlyOneAttendeeCanRegister
318
-     *
319
-     * @return string
320
-     */
321
-    protected function onlyOneAttendeeCanRegister()
322
-    {
323
-        // display submit button since we have tickets available
324
-        add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
325
-        $this->hidden_input_qty = false;
326
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
327
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
328
-        $html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
329
-        $html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
330
-        $html .= ' id="' . $id . '"';
331
-        $html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
332
-        $html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
333
-        $html .= ' title=""/>';
334
-        return $html;
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * ticketQuantitySelector
341
-     *
342
-     * @return string
343
-     * @throws EE_Error
344
-     */
345
-    protected function ticketQuantitySelector()
346
-    {
347
-        // display submit button since we have tickets available
348
-        add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
349
-        $this->hidden_input_qty = false;
350
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
351
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
352
-        $html .= esc_html__('Quantity', 'event_espresso') . '</label>';
353
-        $html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
354
-        $html .= ' id="' . $id . '"';
355
-        $html .= ' class="ticket-selector-tbl-qty-slct">';
356
-        // this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
357
-        if ($this->min !== 0 && ! $this->ticket->required()) {
358
-            $html .= '<option value="0">&nbsp;0&nbsp;</option>';
359
-        }
360
-        // offer ticket quantities from the min to the max
361
-        for ($i = $this->min; $i <= $this->max; $i++) {
362
-            $html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
363
-        }
364
-        $html .= '</select>';
365
-        return $html;
366
-    }
367
-
368
-
369
-
370
-    /**
371
-     * getHiddenInputs
372
-     *
373
-     * @return string
374
-     * @throws EE_Error
375
-     */
376
-    protected function ticketQtyAndIdHiddenInputs()
377
-    {
378
-        $html = '';
379
-        // depending on group reg we need to change the format for qty
380
-        if ($this->hidden_input_qty) {
381
-            $html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
382
-        }
383
-        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
384
-        $html .= ' value="' . $this->ticket->ID() . '"/>';
385
-        return $html;
386
-    }
24
+	/**
25
+	 * @var TicketDetails $ticket_details
26
+	 */
27
+	protected $ticket_details;
28
+
29
+	/**
30
+	 * @var \EE_Ticket_Selector_Config $template_settings
31
+	 */
32
+	protected $template_settings;
33
+
34
+	/**
35
+	 * @var EE_Tax_Config $tax_settings
36
+	 */
37
+	protected $tax_settings;
38
+
39
+	/**
40
+	 * @var boolean $prices_displayed_including_taxes
41
+	 */
42
+	protected $prices_displayed_including_taxes;
43
+
44
+	/**
45
+	 * @var int $row
46
+	 */
47
+	protected $row;
48
+
49
+	/**
50
+	 * @var int $cols
51
+	 */
52
+	protected $cols;
53
+
54
+	/**
55
+	 * @var boolean $hidden_input_qty
56
+	 */
57
+	protected $hidden_input_qty;
58
+
59
+	/**
60
+	 * @var string $ticket_datetime_classes
61
+	 */
62
+	protected $ticket_datetime_classes;
63
+
64
+
65
+
66
+	/**
67
+	 * TicketDetails constructor.
68
+	 *
69
+	 * @param TicketDetails  $ticket_details
70
+	 * @param EE_Tax_Config $tax_settings
71
+	 * @param int            $total_tickets
72
+	 * @param int            $max_attendees
73
+	 * @param int            $row
74
+	 * @param int            $cols
75
+	 * @param boolean        $required_ticket_sold_out
76
+	 * @param string         $event_status
77
+	 * @param string         $ticket_datetime_classes
78
+	 * @throws EE_Error
79
+	 * @throws UnexpectedEntityException
80
+	 */
81
+	public function __construct(
82
+		TicketDetails $ticket_details,
83
+		EE_Tax_Config $tax_settings,
84
+		$total_tickets,
85
+		$max_attendees,
86
+		$row,
87
+		$cols,
88
+		$required_ticket_sold_out,
89
+		$event_status,
90
+		$ticket_datetime_classes
91
+	) {
92
+		$this->ticket_details = $ticket_details;
93
+		$this->template_settings = $ticket_details->getTemplateSettings();
94
+		$this->tax_settings = $tax_settings;
95
+		$this->row = $row;
96
+		$this->cols = $cols;
97
+		$this->ticket_datetime_classes = $ticket_datetime_classes;
98
+		parent::__construct(
99
+			$ticket_details->getTicket(),
100
+			$max_attendees,
101
+			$ticket_details->getDateFormat(),
102
+			$event_status,
103
+			$required_ticket_sold_out,
104
+			$total_tickets
105
+		);
106
+	}
107
+
108
+
109
+
110
+	/**
111
+	 * other ticket rows will need to know if a required ticket is sold out,
112
+	 * so that they are not offered for sale
113
+	 *
114
+	 * @return boolean
115
+	 */
116
+	public function getRequiredTicketSoldOut()
117
+	{
118
+		return $this->required_ticket_sold_out;
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * @return int
125
+	 */
126
+	public function getCols()
127
+	{
128
+		return $this->cols;
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * getHtml
135
+	 *
136
+	 * @return string
137
+	 * @throws EE_Error
138
+	 */
139
+	public function getHtml()
140
+	{
141
+		$this->min = 0;
142
+		$this->max = $this->ticket->max();
143
+		$remaining = $this->ticket->remaining();
144
+		if ($this->ticket->is_on_sale() && $this->ticket->is_remaining()) {
145
+			 $this->setTicketMinAndMax($remaining);
146
+		} else {
147
+			// set flag if ticket is required (flag is set to start date so that future tickets are not blocked)
148
+			$this->required_ticket_sold_out = $this->ticket->required() && ! $remaining
149
+				? $this->ticket->start_date()
150
+				: $this->required_ticket_sold_out;
151
+		}
152
+		$this->setTicketPriceDetails();
153
+		$this->setTicketStatusClasses($remaining);
154
+		$filtered_row_html = $this->getFilteredRowHtml();
155
+		if ($filtered_row_html !== false) {
156
+			return $filtered_row_html;
157
+		}
158
+		$ticket_selector_row_html = EEH_HTML::tr(
159
+			'', '',
160
+			"tckt-slctr-tbl-tr {$this->status_class}{$this->ticket_datetime_classes} "
161
+			. espresso_get_object_css_class($this->ticket)
162
+		);
163
+		$filtered_row_content = $this->getFilteredRowContents();
164
+		if ($filtered_row_content !== false && $this->max_attendees === 1) {
165
+			return $ticket_selector_row_html
166
+				   . $filtered_row_content
167
+				   . $this->ticketQtyAndIdHiddenInputs()
168
+				   . EEH_HTML::trx();
169
+		}
170
+		if ($filtered_row_content !== false) {
171
+			return $ticket_selector_row_html
172
+				   . $filtered_row_content
173
+				   . EEH_HTML::trx();
174
+		}
175
+		$this->hidden_input_qty = $this->max_attendees > 1;
176
+
177
+		$ticket_selector_row_html .= $this->ticketNameTableCell();
178
+		$ticket_selector_row_html .= $this->ticketPriceTableCell();
179
+		$ticket_selector_row_html .= EEH_HTML::td(
180
+			'', 
181
+			'', 
182
+			'tckt-slctr-tbl-td-qty cntr',
183
+			'',
184
+			'headers="quantity-' . $this->EVT_ID . '"'
185
+		);
186
+		$this->setTicketStatusDisplay($remaining);
187
+		if (empty($this->ticket_status_display)) {
188
+			if ($this->max_attendees === 1) {
189
+				// only ONE attendee is allowed to register at a time
190
+				$ticket_selector_row_html .= $this->onlyOneAttendeeCanRegister();
191
+			} elseif ($this->max > 0) {
192
+				$ticket_selector_row_html .= $this->ticketQuantitySelector();
193
+			}
194
+		}
195
+		$ticket_selector_row_html .= $this->ticket_status_display;
196
+		$ticket_selector_row_html .= $this->ticketQtyAndIdHiddenInputs();
197
+		$ticket_selector_row_html .= $this->ticket_details->display(
198
+			$this->ticket_price,
199
+			$remaining,
200
+			$this->cols
201
+		);
202
+		$ticket_selector_row_html .= EEH_HTML::tdx();
203
+		$ticket_selector_row_html .= EEH_HTML::trx();
204
+
205
+
206
+		$this->row++;
207
+		return $ticket_selector_row_html;
208
+	}
209
+
210
+
211
+
212
+
213
+	/**
214
+	 * getTicketPriceDetails
215
+	 *
216
+	 * @return void
217
+	 * @throws EE_Error
218
+	 */
219
+	protected function setTicketPriceDetails()
220
+	{
221
+		$this->ticket_price = $this->tax_settings->prices_displayed_including_taxes
222
+			? $this->ticket->get_ticket_total_with_taxes()
223
+			: $this->ticket->get_ticket_subtotal();
224
+		$this->ticket_bundle = false;
225
+		$ticket_min = $this->ticket->min();
226
+		// for ticket bundles, set min and max qty the same
227
+		if ($ticket_min !== 0 && $ticket_min === $this->ticket->max()) {
228
+			$this->ticket_price *= $ticket_min;
229
+			$this->ticket_bundle = true;
230
+		}
231
+		$this->ticket_price = apply_filters(
232
+			'FHEE__ticket_selector_chart_template__ticket_price',
233
+			$this->ticket_price,
234
+			$this->ticket
235
+		);
236
+	}
237
+
238
+
239
+
240
+
241
+	/**
242
+	 * ticketNameTableCell
243
+	 *
244
+	 * @return string
245
+	 * @throws EE_Error
246
+	 */
247
+	protected function ticketNameTableCell()
248
+	{
249
+		$html = EEH_HTML::td(
250
+			'', 
251
+			'', 
252
+			'tckt-slctr-tbl-td-name', 
253
+			'', 
254
+			'headers="details-' . $this->EVT_ID . '"'
255
+		);
256
+		$html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
257
+		$html .= $this->ticket_details->getShowHideLinks();
258
+		if ($this->ticket->required()) {
259
+			$html .= EEH_HTML::p(
260
+				apply_filters(
261
+						'FHEE__ticket_selector_chart_template__ticket_required_message',
262
+						esc_html__('This ticket is required and must be purchased.', 'event_espresso')
263
+				),
264
+				'', 'ticket-required-pg'
265
+			);
266
+		}
267
+		$html .= EEH_HTML::tdx();
268
+		return $html;
269
+	}
270
+
271
+
272
+
273
+	/**
274
+	 * ticketPriceTableCell
275
+	 *
276
+	 * @return string
277
+	 * @throws EE_Error
278
+	 */
279
+	protected function ticketPriceTableCell()
280
+	{
281
+		$html = '';
282
+		if (apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', true)) {
283
+			$html .= EEH_HTML::td(
284
+				'', 
285
+				'', 
286
+				'tckt-slctr-tbl-td-price jst-rght', 
287
+				'', 
288
+				'headers="price-' . $this->EVT_ID . '"'
289
+			);
290
+			$html .= \EEH_Template::format_currency($this->ticket_price);
291
+			$html .= $this->ticket->taxable()
292
+				? EEH_HTML::span( '*', '', 'taxable-tickets-asterisk grey-text' )
293
+				: '';
294
+			$html .= '&nbsp;';
295
+			$html .= EEH_HTML::span(
296
+				$this->ticket_bundle
297
+					? apply_filters(
298
+						'FHEE__ticket_selector_chart_template__per_ticket_bundle_text',
299
+						__(' / bundle', 'event_espresso')
300
+					)
301
+					: apply_filters(
302
+						'FHEE__ticket_selector_chart_template__per_ticket_text',
303
+						__('', 'event_espresso')
304
+					),
305
+				'', 'smaller-text no-bold'
306
+			);
307
+			$html .= '&nbsp;';
308
+			$html .= EEH_HTML::tdx();
309
+			$this->cols++;
310
+		}
311
+		return $html;
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * onlyOneAttendeeCanRegister
318
+	 *
319
+	 * @return string
320
+	 */
321
+	protected function onlyOneAttendeeCanRegister()
322
+	{
323
+		// display submit button since we have tickets available
324
+		add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
325
+		$this->hidden_input_qty = false;
326
+		$id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
327
+		$html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
328
+		$html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
329
+		$html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
330
+		$html .= ' id="' . $id . '"';
331
+		$html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
332
+		$html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
333
+		$html .= ' title=""/>';
334
+		return $html;
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * ticketQuantitySelector
341
+	 *
342
+	 * @return string
343
+	 * @throws EE_Error
344
+	 */
345
+	protected function ticketQuantitySelector()
346
+	{
347
+		// display submit button since we have tickets available
348
+		add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
349
+		$this->hidden_input_qty = false;
350
+		$id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
351
+		$html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
352
+		$html .= esc_html__('Quantity', 'event_espresso') . '</label>';
353
+		$html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
354
+		$html .= ' id="' . $id . '"';
355
+		$html .= ' class="ticket-selector-tbl-qty-slct">';
356
+		// this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
357
+		if ($this->min !== 0 && ! $this->ticket->required()) {
358
+			$html .= '<option value="0">&nbsp;0&nbsp;</option>';
359
+		}
360
+		// offer ticket quantities from the min to the max
361
+		for ($i = $this->min; $i <= $this->max; $i++) {
362
+			$html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
363
+		}
364
+		$html .= '</select>';
365
+		return $html;
366
+	}
367
+
368
+
369
+
370
+	/**
371
+	 * getHiddenInputs
372
+	 *
373
+	 * @return string
374
+	 * @throws EE_Error
375
+	 */
376
+	protected function ticketQtyAndIdHiddenInputs()
377
+	{
378
+		$html = '';
379
+		// depending on group reg we need to change the format for qty
380
+		if ($this->hidden_input_qty) {
381
+			$html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
382
+		}
383
+		$html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
384
+		$html .= ' value="' . $this->ticket->ID() . '"/>';
385
+		return $html;
386
+	}
387 387
 
388 388
 }
389 389
 // End of file TicketSelectorRowStandard.php
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
             '', 
182 182
             'tckt-slctr-tbl-td-qty cntr',
183 183
             '',
184
-            'headers="quantity-' . $this->EVT_ID . '"'
184
+            'headers="quantity-'.$this->EVT_ID.'"'
185 185
         );
186 186
         $this->setTicketStatusDisplay($remaining);
187 187
         if (empty($this->ticket_status_display)) {
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
             '', 
252 252
             'tckt-slctr-tbl-td-name', 
253 253
             '', 
254
-            'headers="details-' . $this->EVT_ID . '"'
254
+            'headers="details-'.$this->EVT_ID.'"'
255 255
         );
256 256
         $html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
257 257
         $html .= $this->ticket_details->getShowHideLinks();
@@ -285,11 +285,11 @@  discard block
 block discarded – undo
285 285
                 '', 
286 286
                 'tckt-slctr-tbl-td-price jst-rght', 
287 287
                 '', 
288
-                'headers="price-' . $this->EVT_ID . '"'
288
+                'headers="price-'.$this->EVT_ID.'"'
289 289
             );
290 290
             $html .= \EEH_Template::format_currency($this->ticket_price);
291 291
             $html .= $this->ticket->taxable()
292
-                ? EEH_HTML::span( '*', '', 'taxable-tickets-asterisk grey-text' )
292
+                ? EEH_HTML::span('*', '', 'taxable-tickets-asterisk grey-text')
293 293
                 : '';
294 294
             $html .= '&nbsp;';
295 295
             $html .= EEH_HTML::span(
@@ -323,12 +323,12 @@  discard block
 block discarded – undo
323 323
         // display submit button since we have tickets available
324 324
         add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
325 325
         $this->hidden_input_qty = false;
326
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
327
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
328
-        $html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
329
-        $html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
330
-        $html .= ' id="' . $id . '"';
331
-        $html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
326
+        $id = 'ticket-selector-tbl-qty-slct-'.$this->EVT_ID.'-'.$this->row;
327
+        $html = '<label class="ee-a11y-screen-reader-text" for="'.$id.'">';
328
+        $html .= esc_html__('Select this ticket', 'event_espresso').'</label>';
329
+        $html .= '<input type="radio" name="tkt-slctr-qty-'.$this->EVT_ID.'"';
330
+        $html .= ' id="'.$id.'"';
331
+        $html .= ' class="ticket-selector-tbl-qty-slct" value="'.$this->row.'-1"';
332 332
         $html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
333 333
         $html .= ' title=""/>';
334 334
         return $html;
@@ -347,11 +347,11 @@  discard block
 block discarded – undo
347 347
         // display submit button since we have tickets available
348 348
         add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
349 349
         $this->hidden_input_qty = false;
350
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
351
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
352
-        $html .= esc_html__('Quantity', 'event_espresso') . '</label>';
353
-        $html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
354
-        $html .= ' id="' . $id . '"';
350
+        $id = 'ticket-selector-tbl-qty-slct-'.$this->EVT_ID.'-'.$this->row;
351
+        $html = '<label class="ee-a11y-screen-reader-text" for="'.$id.'">';
352
+        $html .= esc_html__('Quantity', 'event_espresso').'</label>';
353
+        $html .= '<select name="tkt-slctr-qty-'.$this->EVT_ID.'[]"';
354
+        $html .= ' id="'.$id.'"';
355 355
         $html .= ' class="ticket-selector-tbl-qty-slct">';
356 356
         // this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
357 357
         if ($this->min !== 0 && ! $this->ticket->required()) {
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
         }
360 360
         // offer ticket quantities from the min to the max
361 361
         for ($i = $this->min; $i <= $this->max; $i++) {
362
-            $html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
362
+            $html .= '<option value="'.$i.'">&nbsp;'.$i.'&nbsp;</option>';
363 363
         }
364 364
         $html .= '</select>';
365 365
         return $html;
@@ -378,10 +378,10 @@  discard block
 block discarded – undo
378 378
         $html = '';
379 379
         // depending on group reg we need to change the format for qty
380 380
         if ($this->hidden_input_qty) {
381
-            $html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
381
+            $html .= '<input type="hidden" name="tkt-slctr-qty-'.$this->EVT_ID.'[]" value="0"/>';
382 382
         }
383
-        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
384
-        $html .= ' value="' . $this->ticket->ID() . '"/>';
383
+        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-'.$this->EVT_ID.'[]"';
384
+        $html .= ' value="'.$this->ticket->ID().'"/>';
385 385
         return $html;
386 386
     }
387 387
 
Please login to merge, or discard this patch.
modules/ticket_selector/templates/ticket_details.template.php 1 patch
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -12,13 +12,13 @@  discard block
 block discarded – undo
12 12
 /** @var string $price_breakdown_heading */
13 13
 /** @var \EventEspresso\modules\ticket_selector\TicketDetails $ticket_details */
14 14
 ?>
15
-<?php if ( $show_ticket_details ) : ?>
15
+<?php if ($show_ticket_details) : ?>
16 16
 <tr class="tckt-slctr-tkt-details-tr <?php echo $ticket_details_row_class; ?>">
17 17
     <td class="tckt-slctr-tkt-details-td" colspan="<?php echo $cols; ?>">
18 18
         <div id="<?php echo $ticket_details_css_id; ?>-dv" class="tckt-slctr-tkt-details-dv" style="display: none;">
19 19
 
20 20
             <section class="tckt-slctr-tkt-details-sctn">
21
-                <h4><?php echo esc_html__( 'Details', 'event_espresso' ); ?></h4>
21
+                <h4><?php echo esc_html__('Details', 'event_espresso'); ?></h4>
22 22
                 <p><?php echo $ticket->description(); ?></p>
23 23
 
24 24
                 <?php
@@ -33,42 +33,42 @@  discard block
 block discarded – undo
33 33
                 <section class="tckt-slctr-tkt-sale-dates-sctn">
34 34
                     <h5><?php echo apply_filters(
35 35
                         'FHEE__ticket_selector_chart_template__ticket_details_sales_date_heading',
36
-                        esc_html__( 'Sale Dates', 'event_espresso' )
36
+                        esc_html__('Sale Dates', 'event_espresso')
37 37
                         ); ?>
38 38
                     </h5>
39 39
                     <span class="drk-grey-text small-text no-bold"> - <?php echo apply_filters(
40 40
                         'FHEE__ticket_selector_chart_template__ticket_details_dates_available_message',
41
-                        esc_html__( 'The dates when this option is available for purchase.', 'event_espresso' )
41
+                        esc_html__('The dates when this option is available for purchase.', 'event_espresso')
42 42
                         ); ?></span>
43 43
                     <br/>
44 44
                     <span class="ticket-details-label-spn drk-grey-text"><?php echo apply_filters(
45 45
                         'FHEE__ticket_selector_chart_template__ticket_details_goes_on_sale',
46
-                        esc_html__( 'Goes On Sale:', 'event_espresso' )
46
+                        esc_html__('Goes On Sale:', 'event_espresso')
47 47
                         ); ?></span>
48 48
                     <span class="dashicons dashicons-calendar"></span>
49
-                    <?php echo $ticket->get_i18n_datetime('TKT_start_date', $date_format) . ' &nbsp; '; ?>
49
+                    <?php echo $ticket->get_i18n_datetime('TKT_start_date', $date_format).' &nbsp; '; ?>
50 50
                     <span  class="dashicons dashicons-clock"></span>
51
-                    <?php echo $ticket->get_i18n_datetime('TKT_start_date',$time_format); ?>
51
+                    <?php echo $ticket->get_i18n_datetime('TKT_start_date', $time_format); ?>
52 52
                     <br/>
53 53
                     <span class="ticket-details-label-spn drk-grey-text"><?php echo apply_filters(
54 54
                         'FHEE__ticket_selector_chart_template__ticket_details_sales_end',
55
-                        esc_html__( 'Sales End:', 'event_espresso' )
55
+                        esc_html__('Sales End:', 'event_espresso')
56 56
                         ); ?></span>
57 57
                     <span class="dashicons dashicons-calendar"></span>
58
-                    <?php echo $ticket->get_i18n_datetime('TKT_end_date', $date_format) . ' &nbsp; '; ?>
58
+                    <?php echo $ticket->get_i18n_datetime('TKT_end_date', $date_format).' &nbsp; '; ?>
59 59
                     <span class="dashicons dashicons-clock"></span>
60 60
                     <?php echo $ticket->get_i18n_datetime('TKT_end_date', $time_format); ?>
61 61
                     <br/>
62 62
                 </section>
63 63
                 <br/>
64 64
 
65
-                <?php do_action( 'AHEE__ticket_selector_chart_template__after_ticket_date', $ticket ); ?>
65
+                <?php do_action('AHEE__ticket_selector_chart_template__after_ticket_date', $ticket); ?>
66 66
 
67
-                <?php if ( $ticket->min() && $ticket->max() ) { ?>
67
+                <?php if ($ticket->min() && $ticket->max()) { ?>
68 68
                     <section class="tckt-slctr-tkt-quantities-sctn">
69 69
                         <h5><?php echo apply_filters(
70 70
                             'FHEE__ticket_selector_chart_template__ticket_details_purchasable_quantities_heading',
71
-                            esc_html__( 'Purchasable Quantities', 'event_espresso' )
71
+                            esc_html__('Purchasable Quantities', 'event_espresso')
72 72
                             ); ?></h5>
73 73
                         <span class="drk-grey-text small-text no-bold"> - <?php echo apply_filters(
74 74
                             'FHEE__ticket_selector_chart_template__ticket_details_purchasable_quantities_message',
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
                             ); ?></span><br/>
80 80
                         <span class="ticket-details-label-spn drk-grey-text"><?php echo apply_filters(
81 81
                             'FHEE__ticket_selector_chart_template__ticket_details_purchasable_quantities_min_qty',
82
-                            esc_html__( 'Minimum Qty:', 'event_espresso' )
82
+                            esc_html__('Minimum Qty:', 'event_espresso')
83 83
                             ); ?></span><?php echo $ticket->min() > 0 ? $ticket->min() : 0; ?>
84
-                        <?php if ( $ticket->min() > $remaining ) { ?> &nbsp; <span
84
+                        <?php if ($ticket->min() > $remaining) { ?> &nbsp; <span
85 85
                         class="important-notice small-text"><?php echo apply_filters(
86 86
                         'FHEE__ticket_selector_chart_template__ticket_details_purchasable_quantities_min_qty_message',
87 87
                         esc_html__(
@@ -92,18 +92,18 @@  discard block
 block discarded – undo
92 92
                         <?php //$max = min( $max, $max_atndz );?>
93 93
                         <span class="ticket-details-label-spn drk-grey-text"><?php echo apply_filters(
94 94
                             'FHEE__ticket_selector_chart_template__ticket_details_purchasable_quantities_max_qty',
95
-                            esc_html__( 'Maximum Qty:', 'event_espresso' )
96
-                            ); ?></span><?php echo $ticket->max() === EE_INF ? esc_html__( 'no limit', 'event_espresso' )
97
-                        : max( $ticket->max(), 1 ); ?><br/>
95
+                            esc_html__('Maximum Qty:', 'event_espresso')
96
+                            ); ?></span><?php echo $ticket->max() === EE_INF ? esc_html__('no limit', 'event_espresso')
97
+                        : max($ticket->max(), 1); ?><br/>
98 98
                     </section>
99 99
                     <br/>
100 100
                 <?php } ?>
101 101
 
102
-                <?php if ( ( ! defined( 'EE_DECAF' ) || EE_DECAF !== true ) && $ticket->uses() !== EE_INF ) { ?>
102
+                <?php if (( ! defined('EE_DECAF') || EE_DECAF !== true) && $ticket->uses() !== EE_INF) { ?>
103 103
                     <section class="tckt-slctr-tkt-uses-sctn">
104 104
                         <h5><?php echo apply_filters(
105 105
                                 'FHEE__ticket_selector_chart_template__ticket_details_event_date_ticket_uses_heading',
106
-                                esc_html__( 'Event Date Ticket Uses', 'event_espresso' )
106
+                                esc_html__('Event Date Ticket Uses', 'event_espresso')
107 107
                             ); ?></h5>
108 108
                         <span class="drk-grey-text small-text no-bold"> - <?php
109 109
                             echo apply_filters(
@@ -121,23 +121,23 @@  discard block
 block discarded – undo
121 121
                             ?></span><br/>
122 122
                         <span class="ticket-details-label-spn drk-grey-text"><?php echo apply_filters(
123 123
                             'FHEE__ticket_selector_chart_template__ticket_details_event_date_number_datetimes',
124
-                            esc_html__( '# Datetimes:', 'event_espresso' )
124
+                            esc_html__('# Datetimes:', 'event_espresso')
125 125
                             ); ?></span><?php echo $ticket->uses(); ?><br/>
126 126
                     </section>
127 127
                 <?php } ?>
128 128
 
129 129
                 <?php
130
-                $datetimes = $ticket->datetimes_ordered( $event_is_expired, false );
130
+                $datetimes = $ticket->datetimes_ordered($event_is_expired, false);
131 131
                 $chart_column_width = $show_ticket_sale_columns ? ' ee-fourth-width' : ' ee-half-width';
132
-                if ( ! empty( $datetimes ) ) { ?>
132
+                if ( ! empty($datetimes)) { ?>
133 133
                     <section class="tckt-slctr-tkt-datetimes-sctn">
134 134
                         <h5><?php echo apply_filters(
135 135
                             'FHEE__ticket_selector_chart_template__ticket_details_event_access_heading',
136
-                            esc_html__( 'Access', 'event_espresso' )
136
+                            esc_html__('Access', 'event_espresso')
137 137
                             ); ?></h5>
138 138
                         <span class="drk-grey-text small-text no-bold"> - <?php echo apply_filters(
139 139
                             'FHEE__ticket_selector_chart_template__ticket_details_event_access_message',
140
-                            esc_html__( 'This option allows access to the following dates and times.', 'event_espresso' )
140
+                            esc_html__('This option allows access to the following dates and times.', 'event_espresso')
141 141
                             ); ?></span>
142 142
                         <div class="tckt-slctr-tkt-details-tbl-wrap-dv">
143 143
                             <table class="tckt-slctr-tkt-details-tbl">
@@ -147,38 +147,38 @@  discard block
 block discarded – undo
147 147
                                         <span class="dashicons dashicons-calendar"></span><span
148 148
                                         class="small-text"><?php echo apply_filters(
149 149
                                             'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_event_date',
150
-                                            esc_html__( 'Date ', 'event_espresso' )
150
+                                            esc_html__('Date ', 'event_espresso')
151 151
                                             ); ?></span>
152 152
                                     </th>
153 153
                                     <th class="tckt-slctr-tkt-details-time-th <?php echo $chart_column_width; ?>">
154 154
                                         <span class="dashicons dashicons-clock"></span><span
155
-                                        class="small-text"><?php esc_html_e( 'Time ', 'event_espresso' ); ?></span>
155
+                                        class="small-text"><?php esc_html_e('Time ', 'event_espresso'); ?></span>
156 156
                                     </th>
157
-                                    <?php if ( $show_ticket_sale_columns ) : ?>
157
+                                    <?php if ($show_ticket_sale_columns) : ?>
158 158
                                         <th class="tckt-slctr-tkt-details-this-ticket-sold-th ee-fourth-width cntr">
159 159
                                             <span class="smaller-text"><?php echo apply_filters(
160 160
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_this_ticket_sold',
161
-                                                sprintf( esc_html__( 'Sold', 'event_espresso' ), '<br/>' )
161
+                                                sprintf(esc_html__('Sold', 'event_espresso'), '<br/>')
162 162
                                                 ); ?></span>
163 163
                                         </th>
164 164
                                         <th class="tckt-slctr-tkt-details-this-ticket-left-th ee-fourth-width cntr">
165 165
                                             <span class="smaller-text"><?php echo apply_filters(
166 166
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_this_ticket_left',
167
-                                                sprintf( esc_html__( 'Remaining', 'event_espresso' ), '<br/>' )
167
+                                                sprintf(esc_html__('Remaining', 'event_espresso'), '<br/>')
168 168
                                                 ); ?></span>
169 169
                                         </th>
170 170
                                         <th
171 171
                                         class="tckt-slctr-tkt-details-total-tickets-sold-th ee-fourth-width cntr">
172 172
                                             <span class="smaller-text"><?php echo apply_filters(
173 173
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_total_ticket_sold',
174
-                                                sprintf( esc_html__( 'Total%sSold', 'event_espresso' ), '<br/>' )
174
+                                                sprintf(esc_html__('Total%sSold', 'event_espresso'), '<br/>')
175 175
                                                 ); ?></span>
176 176
                                         </th>
177 177
                                         <th
178 178
                                         class="tckt-slctr-tkt-details-total-tickets-left-th ee-fourth-width cntr">
179 179
                                             <span class="smaller-text"><?php echo apply_filters(
180 180
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_total_ticket_left',
181
-                                                sprintf( esc_html__( 'Total Spaces%sLeft', 'event_espresso' ), '<br/>' )
181
+                                                sprintf(esc_html__('Total Spaces%sLeft', 'event_espresso'), '<br/>')
182 182
                                                 ); ?></span>
183 183
                                         </th>
184 184
                                     <?php endif; //end $show_ticket_sale_columns conditional ?>
@@ -186,62 +186,62 @@  discard block
 block discarded – undo
186 186
                                 </thead>
187 187
                                 <tbody>
188 188
                                 <?php
189
-                                foreach ( $datetimes as $datetime ) {
190
-                                    if ( $datetime instanceof EE_Datetime ) {
189
+                                foreach ($datetimes as $datetime) {
190
+                                    if ($datetime instanceof EE_Datetime) {
191 191
                                         ?>
192 192
 
193 193
                                         <tr>
194 194
                                             <td data-th="<?php echo apply_filters(
195 195
                                             'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_event_date',
196
-                                            esc_html__( 'Event Date ', 'event_espresso' )
196
+                                            esc_html__('Event Date ', 'event_espresso')
197 197
                                             ); ?>" class="small-text">
198 198
                                                 <?php $datetime_name = $datetime->name(); ?>
199
-                                                <?php echo ! empty( $datetime_name ) ? '<b>'
199
+                                                <?php echo ! empty($datetime_name) ? '<b>'
200 200
                                                                                        . $datetime_name
201 201
                                                                                        . '</b><br/>' : ''; ?>
202 202
                                                 <?php echo $datetime->date_range(
203 203
                                                 $date_format,
204
-                                                esc_html__( ' to  ', 'event_espresso' )
204
+                                                esc_html__(' to  ', 'event_espresso')
205 205
                                                 ); ?>
206 206
                                             </td>
207
-                                            <td data-th="<?php esc_html_e( 'Time ', 'event_espresso' ); ?>"
207
+                                            <td data-th="<?php esc_html_e('Time ', 'event_espresso'); ?>"
208 208
                                                 class="cntr small-text">
209 209
                                                 <?php echo $datetime->time_range(
210 210
                                                 $time_format,
211
-                                                esc_html__( ' to  ', 'event_espresso' )
211
+                                                esc_html__(' to  ', 'event_espresso')
212 212
                                                 ); ?>
213 213
                                             </td>
214
-                                            <?php if ( $show_ticket_sale_columns ) : ?>
214
+                                            <?php if ($show_ticket_sale_columns) : ?>
215 215
                                                 <td data-th="<?php echo apply_filters(
216 216
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_this_ticket_sold',
217
-                                                esc_html__( 'Sold', 'event_espresso' )
217
+                                                esc_html__('Sold', 'event_espresso')
218 218
                                                 ); ?>" class="cntr small-text">
219 219
                                                     <?php echo $ticket->sold(); ?>
220 220
                                                 </td>
221 221
                                                 <td data-th="<?php echo apply_filters(
222 222
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_this_ticket_left',
223
-                                                esc_html__( 'Remaining', 'event_espresso' )
223
+                                                esc_html__('Remaining', 'event_espresso')
224 224
                                                 ); ?>" class="cntr small-text">
225 225
                                                     <?php echo $remaining === EE_INF
226
-                                                    ? '<span class="smaller-text">' . esc_html__(
226
+                                                    ? '<span class="smaller-text">'.esc_html__(
227 227
                                                     'unlimited ',
228 228
                                                     'event_espresso'
229
-                                                    ) . '</span>' : $remaining; ?>
229
+                                                    ).'</span>' : $remaining; ?>
230 230
                                                 </td>
231 231
                                                 <td data-th="<?php echo apply_filters(
232 232
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_total_ticket_sold',
233
-                                                esc_html__( 'Total Sold', 'event_espresso' )
233
+                                                esc_html__('Total Sold', 'event_espresso')
234 234
                                                 ); ?>" class="cntr small-text">
235 235
                                                     <?php echo $datetime->sold(); ?>
236 236
                                                 </td>
237 237
                                                 <?php $tkts_left = $datetime->sold_out()
238
-                                                ? '<span class="sold-out smaller-text">' . esc_html__(
238
+                                                ? '<span class="sold-out smaller-text">'.esc_html__(
239 239
                                                 'Sold&nbsp;Out',
240 240
                                                 'event_espresso'
241
-                                                ) . '</span>' : $datetime->spaces_remaining(); ?>
241
+                                                ).'</span>' : $datetime->spaces_remaining(); ?>
242 242
                                                 <td data-th="<?php echo apply_filters(
243 243
                                                 'FHEE__ticket_selector_chart_template__ticket_details_event_access_table_total_ticket_left',
244
-                                                esc_html__( 'Total Spaces Left', 'event_espresso' )
244
+                                                esc_html__('Total Spaces Left', 'event_espresso')
245 245
                                                 ); ?>" class="cntr small-text">
246 246
                                                     <?php echo $tkts_left === EE_INF ? '<span class="smaller-text">'
247 247
                                                                                        . esc_html__(
@@ -266,4 +266,4 @@  discard block
 block discarded – undo
266 266
         </div>
267 267
     </td>
268 268
 </tr>
269
-<?php endif;  //end template_settings->show_ticket_details check?>
270 269
\ No newline at end of file
270
+<?php endif; //end template_settings->show_ticket_details check?>
271 271
\ No newline at end of file
Please login to merge, or discard this patch.